const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-DGdoA_hj.js","assets/useLeadSiteSearchSuggestions-Dt2hXC99.js","assets/CityPagesModule-BcR7hO65.js","assets/imageOptimization-D_YRwPcx.js","assets/LeadSiteLuxuryHome-BX7ef1Qv.js","assets/LeadSiteLandRanchHome-CtbCFo3g.js","assets/LeadSiteSearch-CV4AWby9.js","assets/SaveSearchButton-JEIs-buF.js","assets/LeadSiteMap-BJrisLHi.js","assets/LeadSiteLuxurySearch-BiewJoBE.js","assets/LeadSiteListingDetail-oNSdmSb7.js","assets/ListingVideoTour-hxBjV-rn.js","assets/useListingVideos-D61pHkWq.js","assets/LeadSiteLuxuryListingDetail-DHek7nIb.js","assets/LeadSiteBlog-Box57FZU.js","assets/purify.es-CPrKKeqe.js","assets/LeadSiteCityPage-BiikyE4v.js","assets/LeadSiteSubdivisionPage-BpEjEZTD.js","assets/PostcardManager-DadD7OYO.js","assets/usePostcardZones-PkaFrIJj.js","assets/DirectMail-sUcvg2W0.js","assets/jspdf.es.min-BbAl5gPR.js","assets/LeadSiteEditor-Ca1NAcjg.js","assets/ImageUrlField-Bcd9X0EF.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-LjY0IePs.js","assets/MLSListingDetail-CXV9Tp_B.js","assets/EmailCampaignComposer-DcMI_C6O.js","assets/EditorModeSelector-BkyqziOt.js","assets/SharedCampaignTemplates-B8cyztft.js","assets/TemplateEditorDialog-DtmOooYl.js","assets/AgentTemplates-ByfaOTBu.js","assets/TheLocalMoveHome-DUUuHS2a.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-uQ02rXoP.js"])))=>i.map(i=>d[i]); var Ubt=Object.defineProperty;var L6e=s=>{throw TypeError(s)};var qbt=(s,t,r)=>t in s?Ubt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r;var Vn=(s,t,r)=>qbt(s,typeof t!="symbol"?t+"":t,r),gve=(s,t,r)=>t.has(s)||L6e("Cannot "+r);var Ts=(s,t,r)=>(gve(s,t,"read from private field"),r?r.call(s):t.get(s)),Ua=(s,t,r)=>t.has(s)?L6e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,r),Zn=(s,t,r,n)=>(gve(s,t,"write to private field"),n?n.call(s,r):t.set(s,r),r),Wi=(s,t,r)=>(gve(s,t,"access private method"),r);var y$=(s,t,r,n)=>({set _(a){Zn(s,t,a,r)},get _(){return Ts(s,t,n)}});function Vbt(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 Hbt="modulepreload",Gbt=function(s){return"/"+s},D6e={},ni=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=Gbt(c),c in D6e)return;D6e[c]=!0;const d=c.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Hbt,d||(m.as="script"),m.crossOrigin="",m.href=c,o&&m.setAttribute("nonce",o),document.head.appendChild(m),d)return new Promise((x,g)=>{m.addEventListener("load",x),m.addEventListener("error",()=>g(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 su=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Io(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wbt(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 EWe={exports:{}},Sfe={},AWe={exports:{}},go={};/** * @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 wB=Symbol.for("react.element"),Kbt=Symbol.for("react.portal"),Ybt=Symbol.for("react.fragment"),Zbt=Symbol.for("react.strict_mode"),Xbt=Symbol.for("react.profiler"),Qbt=Symbol.for("react.provider"),Jbt=Symbol.for("react.context"),e_t=Symbol.for("react.forward_ref"),t_t=Symbol.for("react.suspense"),s_t=Symbol.for("react.memo"),r_t=Symbol.for("react.lazy"),R6e=Symbol.iterator;function n_t(s){return s===null||typeof s!="object"?null:(s=R6e&&s[R6e]||s["@@iterator"],typeof s=="function"?s:null)}var MWe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},IWe=Object.assign,PWe={};function mP(s,t,r){this.props=s,this.context=t,this.refs=PWe,this.updater=r||MWe}mP.prototype.isReactComponent={};mP.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")};mP.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function LWe(){}LWe.prototype=mP.prototype;function pCe(s,t,r){this.props=s,this.context=t,this.refs=PWe,this.updater=r||MWe}var xCe=pCe.prototype=new LWe;xCe.constructor=pCe;IWe(xCe,mP.prototype);xCe.isPureReactComponent=!0;var O6e=Array.isArray,DWe=Object.prototype.hasOwnProperty,gCe={current:null},RWe={key:!0,ref:!0,__self:!0,__source:!0};function OWe(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)DWe.call(t,n)&&!RWe.hasOwnProperty(n)&&(a[n]=t[n]);var o=arguments.length-2;if(o===1)a.children=r;else if(1>>1,ge=ae[oe];if(0>>1;oea(Me,me))Pea(Ee,Me)?(ae[oe]=Ee,ae[Pe]=me,oe=Pe):(ae[oe]=Me,ae[Oe]=me,oe=Oe);else if(Pea(Ee,me))ae[oe]=Ee,ae[Pe]=me,oe=Pe;else break e}}return ie}function a(ae,ie){var me=ae.sortIndex-ie.sortIndex;return me!==0?me:ae.id-ie.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],h=1,m=null,x=3,g=!1,v=!1,j=!1,b=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(ae){for(var ie=r(d);ie!==null;){if(ie.callback===null)n(d);else if(ie.startTime<=ae)n(d),ie.sortIndex=ie.expirationTime,t(c,ie);else break;ie=r(d)}}function A(ae){if(j=!1,T(ae),!v)if(r(c)!==null)v=!0,de(P);else{var ie=r(d);ie!==null&&ce(A,ie.startTime-ae)}}function P(ae,ie){v=!1,j&&(j=!1,N(z),z=-1),g=!0;var me=x;try{for(T(ie),m=r(c);m!==null&&(!(m.expirationTime>ie)||ae&&!X());){var oe=m.callback;if(typeof oe=="function"){m.callback=null,x=m.priorityLevel;var ge=oe(m.expirationTime<=ie);ie=s.unstable_now(),typeof ge=="function"?m.callback=ge:m===r(c)&&n(c),T(ie)}else n(c);m=r(c)}if(m!==null)var be=!0;else{var Oe=r(d);Oe!==null&&ce(A,Oe.startTime-ie),be=!1}return be}finally{m=null,x=me,g=!1}}var D=!1,B=null,z=-1,F=5,$=-1;function X(){return!(s.unstable_now()-$ae||125oe?(ae.sortIndex=me,t(d,ae),r(c)===null&&ae===r(d)&&(j?(N(z),z=-1):j=!0,ce(A,me-oe))):(ae.sortIndex=ge,t(c,ae),v||g||(v=!0,de(P))),ae},s.unstable_shouldYield=X,s.unstable_wrapCallback=function(ae){var ie=x;return function(){var me=x;x=ie;try{return ae.apply(this,arguments)}finally{x=me}}}})(UWe);$We.exports=UWe;var p_t=$We.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 x_t=k,Ax=p_t;function dn(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"),pwe=Object.prototype.hasOwnProperty,g_t=/^[: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]*$/,B6e={},z6e={};function y_t(s){return pwe.call(z6e,s)?!0:pwe.call(B6e,s)?!1:g_t.test(s)?z6e[s]=!0:(B6e[s]=!0,!1)}function v_t(s,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function b_t(s,t,r,n){if(t===null||typeof t>"u"||v_t(s,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function If(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 um={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){um[s]=new If(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];um[t]=new If(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){um[s]=new If(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){um[s]=new If(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){um[s]=new If(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){um[s]=new If(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){um[s]=new If(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){um[s]=new If(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){um[s]=new If(s,5,!1,s.toLowerCase(),null,!1,!1)});var vCe=/[\-:]([a-z])/g;function bCe(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(vCe,bCe);um[t]=new If(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(vCe,bCe);um[t]=new If(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(vCe,bCe);um[t]=new If(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){um[s]=new If(s,1,!1,s.toLowerCase(),null,!1,!1)});um.xlinkHref=new If("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){um[s]=new If(s,1,!1,s.toLowerCase(),null,!0,!0)});function _Ce(s,t,r,n){var a=um.hasOwnProperty(t)?um[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{bve=!1,Error.prepareStackTrace=r}return(s=s?s.displayName||s.name:"")?mR(s):""}function __t(s){switch(s.tag){case 5:return mR(s.type);case 16:return mR("Lazy");case 13:return mR("Suspense");case 19:return mR("SuspenseList");case 0:case 2:case 15:return s=_ve(s.type,!1),s;case 11:return s=_ve(s.type.render,!1),s;case 1:return s=_ve(s.type,!0),s;default:return""}}function vwe(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 yA:return"Fragment";case gA:return"Portal";case xwe:return"Profiler";case wCe:return"StrictMode";case gwe:return"Suspense";case ywe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case HWe:return(s.displayName||"Context")+".Consumer";case VWe:return(s._context.displayName||"Context")+".Provider";case jCe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case NCe:return t=s.displayName||null,t!==null?t:vwe(s.type)||"Memo";case Yw:t=s._payload,s=s._init;try{return vwe(s(t))}catch{}}return null}function w_t(s){var t=s.type;switch(s.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return s=t.render,s=s.displayName||s.name||"",t.displayName||(s!==""?"ForwardRef("+s+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return vwe(t);case 8:return t===wCe?"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 x2(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function WWe(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function j_t(s){var t=WWe(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 _$(s){s._valueTracker||(s._valueTracker=j_t(s))}function KWe(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return s&&(n=WWe(s)?s.checked?"true":"false":s.value),s=n,s!==r?(t.setValue(s),!0):!1}function Wde(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 bwe(s,t){var r=t.checked;return gd({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??s._wrapperState.initialChecked})}function U6e(s,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=x2(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 YWe(s,t){t=t.checked,t!=null&&_Ce(s,"checked",t,!1)}function _we(s,t){YWe(s,t);var r=x2(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")?wwe(s,t.type,r):t.hasOwnProperty("defaultValue")&&wwe(s,t.type,x2(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function q6e(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 wwe(s,t,r){(t!=="number"||Wde(s.ownerDocument)!==s)&&(r==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+r&&(s.defaultValue=""+r))}var fR=Array.isArray;function VA(s,t,r,n){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=w$.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function E8(s,t){if(t){var r=s.firstChild;if(r&&r===s.lastChild&&r.nodeType===3){r.nodeValue=t;return}}s.textContent=t}var LR={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},N_t=["Webkit","ms","Moz","O"];Object.keys(LR).forEach(function(s){N_t.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),LR[t]=LR[s]})});function JWe(s,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||LR.hasOwnProperty(s)&&LR[s]?(""+t).trim():t+"px"}function eKe(s,t){s=s.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,a=JWe(r,t[r],n);r==="float"&&(r="cssFloat"),n?s.setProperty(r,a):s[r]=a}}var k_t=gd({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 kwe(s,t){if(t){if(k_t[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(dn(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(dn(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(dn(61))}if(t.style!=null&&typeof t.style!="object")throw Error(dn(62))}}function Swe(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 Cwe=null;function kCe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Twe=null,HA=null,GA=null;function G6e(s){if(s=SB(s)){if(typeof Twe!="function")throw Error(dn(280));var t=s.stateNode;t&&(t=Mfe(t),Twe(s.stateNode,s.type,t))}}function tKe(s){HA?GA?GA.push(s):GA=[s]:HA=s}function sKe(){if(HA){var s=HA,t=GA;if(GA=HA=null,G6e(s),t)for(s=0;s>>=0,s===0?32:31-(R_t(s)/O_t|0)|0}var j$=64,N$=4194304;function pR(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 Xde(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=pR(o):(i&=l,i!==0&&(n=pR(i)))}else l=r&~a,l!==0?n=pR(l):i!==0&&(n=pR(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 NB(s,t,r){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-Qy(t),s[t]=r}function $_t(s,t){var r=s.pendingLanes&~t;s.pendingLanes=t,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=t,s.mutableReadLanes&=t,s.entangledLanes&=t,t=s.entanglements;var n=s.eventTimes;for(s=s.expirationTimes;0=RR),tDe=" ",sDe=!1;function wKe(s,t){switch(s){case"keyup":return pwt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jKe(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var vA=!1;function gwt(s,t){switch(s){case"compositionend":return jKe(t);case"keypress":return t.which!==32?null:(sDe=!0,tDe);case"textInput":return s=t.data,s===tDe&&sDe?null:s;default:return null}}function ywt(s,t){if(vA)return s==="compositionend"||!PCe&&wKe(s,t)?(s=bKe(),Eq=ACe=Sj=null,vA=!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=iDe(r)}}function CKe(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?CKe(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function TKe(){for(var s=window,t=Wde();t instanceof s.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)s=t.contentWindow;else break;t=Wde(s.document)}return t}function LCe(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 Cwt(s){var t=TKe(),r=s.focusedElem,n=s.selectionRange;if(t!==r&&r&&r.ownerDocument&&CKe(r.ownerDocument.documentElement,r)){if(n!==null&&LCe(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=oDe(r,i);var l=oDe(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,bA=null,Lwe=null,FR=null,Dwe=!1;function lDe(s,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Dwe||bA==null||bA!==Wde(n)||(n=bA,"selectionStart"in n&&LCe(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}),FR&&D8(FR,n)||(FR=n,n=eue(Lwe,"onSelect"),0jA||(s.current=$we[jA],$we[jA]=null,jA--)}function fc(s,t){jA++,$we[jA]=s.current,s.current=t}var g2={},Om=R2(g2),up=R2(!1),c5=g2;function sI(s,t){var r=s.type.contextTypes;if(!r)return g2;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 hp(s){return s=s.childContextTypes,s!=null}function sue(){Ic(up),Ic(Om)}function pDe(s,t,r){if(Om.current!==g2)throw Error(dn(168));fc(Om,t),fc(up,r)}function OKe(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(dn(108,w_t(s)||"Unknown",a));return gd({},r,n)}function rue(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||g2,c5=Om.current,fc(Om,s),fc(up,up.current),!0}function xDe(s,t,r){var n=s.stateNode;if(!n)throw Error(dn(169));r?(s=OKe(s,t,c5),n.__reactInternalMemoizedMergedChildContext=s,Ic(up),Ic(Om),fc(Om,s)):Ic(up),fc(up,r)}var Eb=null,Ife=!1,Dve=!1;function FKe(s){Eb===null?Eb=[s]:Eb.push(s)}function Bwt(s){Ife=!0,FKe(s)}function O2(){if(!Dve&&Eb!==null){Dve=!0;var s=0,t=Il;try{var r=Eb;for(Il=1;s>=l,a-=l,zb=1<<32-Qy(t)+a|r<z?(F=B,B=null):F=B.sibling;var $=x(N,B,T[z],A);if($===null){B===null&&(B=F);break}s&&B&&$.alternate===null&&t(N,B),S=i($,S,z),D===null?P=$:D.sibling=$,D=$,B=F}if(z===T.length)return r(N,B),Gc&&pk(N,z),P;if(B===null){for(;zz?(F=B,B=null):F=B.sibling;var X=x(N,B,$.value,A);if(X===null){B===null&&(B=F);break}s&&B&&X.alternate===null&&t(N,B),S=i(X,S,z),D===null?P=X:D.sibling=X,D=X,B=F}if($.done)return r(N,B),Gc&&pk(N,z),P;if(B===null){for(;!$.done;z++,$=T.next())$=m(N,$.value,A),$!==null&&(S=i($,S,z),D===null?P=$:D.sibling=$,D=$);return Gc&&pk(N,z),P}for(B=n(N,B);!$.done;z++,$=T.next())$=g(B,N,z,$.value,A),$!==null&&(s&&$.alternate!==null&&B.delete($.key===null?z:$.key),S=i($,S,z),D===null?P=$:D.sibling=$,D=$);return s&&B.forEach(function(K){return t(N,K)}),Gc&&pk(N,z),P}function b(N,S,T,A){if(typeof T=="object"&&T!==null&&T.type===yA&&T.key===null&&(T=T.props.children),typeof T=="object"&&T!==null){switch(T.$$typeof){case b$:e:{for(var P=T.key,D=S;D!==null;){if(D.key===P){if(P=T.type,P===yA){if(D.tag===7){r(N,D.sibling),S=a(D,T.props.children),S.return=N,N=S;break e}}else if(D.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Yw&&vDe(P)===D.type){r(N,D.sibling),S=a(D,T.props),S.ref=AD(N,D,T),S.return=N,N=S;break e}r(N,D);break}else t(N,D);D=D.sibling}T.type===yA?(S=x3(T.props.children,N.mode,A,T.key),S.return=N,N=S):(A=Oq(T.type,T.key,T.props,null,N.mode,A),A.ref=AD(N,S,T),A.return=N,N=A)}return l(N);case gA:e:{for(D=T.key;S!==null;){if(S.key===D)if(S.tag===4&&S.stateNode.containerInfo===T.containerInfo&&S.stateNode.implementation===T.implementation){r(N,S.sibling),S=a(S,T.children||[]),S.return=N,N=S;break e}else{r(N,S);break}else t(N,S);S=S.sibling}S=qve(T,N.mode,A),S.return=N,N=S}return l(N);case Yw:return D=T._init,b(N,S,D(T._payload),A)}if(fR(T))return v(N,S,T,A);if(kD(T))return j(N,S,T,A);M$(N,T)}return typeof T=="string"&&T!==""||typeof T=="number"?(T=""+T,S!==null&&S.tag===6?(r(N,S.sibling),S=a(S,T),S.return=N,N=S):(r(N,S),S=Uve(T,N.mode,A),S.return=N,N=S),l(N)):r(N,S)}return b}var nI=UKe(!0),qKe=UKe(!1),iue=R2(null),oue=null,SA=null,FCe=null;function BCe(){FCe=SA=oue=null}function zCe(s){var t=iue.current;Ic(iue),s._currentValue=t}function Vwe(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 KA(s,t){oue=s,FCe=SA=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(op=!0),s.firstContext=null)}function Gg(s){var t=s._currentValue;if(FCe!==s)if(s={context:s,memoizedValue:t,next:null},SA===null){if(oue===null)throw Error(dn(308));SA=s,oue.dependencies={lanes:0,firstContext:s}}else SA=SA.next=s;return t}var B4=null;function $Ce(s){B4===null?B4=[s]:B4.push(s)}function VKe(s,t,r,n){var a=t.interleaved;return a===null?(r.next=r,$Ce(t)):(r.next=a.next,a.next=r),t.interleaved=r,f_(s,n)}function f_(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 Zw=!1;function UCe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function HKe(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 Zb(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function Fj(s,t,r){var n=s.updateQueue;if(n===null)return null;if(n=n.shared,Ko&2){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,f_(s,r)}return a=n.interleaved,a===null?(t.next=t,$Ce(n)):(t.next=a.next,a.next=t),n.interleaved=t,f_(s,r)}function Mq(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,CCe(s,r)}}function bDe(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 lue(s,t,r,n){var a=s.updateQueue;Zw=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var h=s.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==l&&(o===null?h.firstBaseUpdate=d:o.next=d,h.lastBaseUpdate=c))}if(i!==null){var m=a.baseState;l=0,h=d=c=null,o=i;do{var x=o.lane,g=o.eventTime;if((n&x)===x){h!==null&&(h=h.next={eventTime:g,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var v=s,j=o;switch(x=t,g=r,j.tag){case 1:if(v=j.payload,typeof v=="function"){m=v.call(g,m,x);break e}m=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=j.payload,x=typeof v=="function"?v.call(g,m,x):v,x==null)break e;m=gd({},m,x);break e;case 2:Zw=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,x=a.effects,x===null?a.effects=[o]:x.push(o))}else g={eventTime:g,lane:x,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(d=h=g,c=m):h=h.next=g,l|=x;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;x=o,o=x.next,x.next=null,a.lastBaseUpdate=x,a.shared.pending=null}}while(!0);if(h===null&&(c=m),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=h,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);h5|=l,s.lanes=l,s.memoizedState=m}}function _De(s,t,r){if(s=t.effects,t.effects=null,s!==null)for(t=0;tr?r:4,s(!0);var n=Ove.transition;Ove.transition={};try{s(!1),t()}finally{Il=r,Ove.transition=n}}function lYe(){return Wg().memoizedState}function qwt(s,t,r){var n=zj(s);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},cYe(s))dYe(t,r);else if(r=VKe(s,t,r,n),r!==null){var a=kf();Jy(r,s,n,a),uYe(r,t,n)}}function Vwt(s,t,r){var n=zj(s),a={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(cYe(s))dYe(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,d0(o,l)){var c=t.interleaved;c===null?(a.next=a,$Ce(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}r=VKe(s,t,a,n),r!==null&&(a=kf(),Jy(r,s,n,a),uYe(r,t,n))}}function cYe(s){var t=s.alternate;return s===md||t!==null&&t===md}function dYe(s,t){BR=due=!0;var r=s.pending;r===null?t.next=t:(t.next=r.next,r.next=t),s.pending=t}function uYe(s,t,r){if(r&4194240){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,CCe(s,r)}}var uue={readContext:Gg,useCallback:Nm,useContext:Nm,useEffect:Nm,useImperativeHandle:Nm,useInsertionEffect:Nm,useLayoutEffect:Nm,useMemo:Nm,useReducer:Nm,useRef:Nm,useState:Nm,useDebugValue:Nm,useDeferredValue:Nm,useTransition:Nm,useMutableSource:Nm,useSyncExternalStore:Nm,useId:Nm,unstable_isNewReconciler:!1},Hwt={readContext:Gg,useCallback:function(s,t){return cv().memoizedState=[s,t===void 0?null:t],s},useContext:Gg,useEffect:jDe,useImperativeHandle:function(s,t,r){return r=r!=null?r.concat([s]):null,Pq(4194308,4,rYe.bind(null,t,s),r)},useLayoutEffect:function(s,t){return Pq(4194308,4,s,t)},useInsertionEffect:function(s,t){return Pq(4,2,s,t)},useMemo:function(s,t){var r=cv();return t=t===void 0?null:t,s=s(),r.memoizedState=[s,t],s},useReducer:function(s,t,r){var n=cv();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=qwt.bind(null,md,s),[n.memoizedState,s]},useRef:function(s){var t=cv();return s={current:s},t.memoizedState=s},useState:wDe,useDebugValue:ZCe,useDeferredValue:function(s){return cv().memoizedState=s},useTransition:function(){var s=wDe(!1),t=s[0];return s=Uwt.bind(null,s[1]),cv().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,r){var n=md,a=cv();if(Gc){if(r===void 0)throw Error(dn(407));r=r()}else{if(r=t(),Sh===null)throw Error(dn(349));u5&30||YKe(n,t,r)}a.memoizedState=r;var i={value:r,getSnapshot:t};return a.queue=i,jDe(XKe.bind(null,n,i,s),[s]),n.flags|=2048,q8(9,ZKe.bind(null,n,i,r,t),void 0,null),r},useId:function(){var s=cv(),t=Sh.identifierPrefix;if(Gc){var r=$b,n=zb;r=(n&~(1<<32-Qy(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=$8++,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[jv]=t,s[F8]=n,_Ye(s,t,!1,!1),t.stateNode=s;e:{switch(l=Swe(r,n),r){case"dialog":Sc("cancel",s),Sc("close",s),a=n;break;case"iframe":case"object":case"embed":Sc("load",s),a=n;break;case"video":case"audio":for(a=0;aoI&&(t.flags|=128,n=!0,MD(i,!1),t.lanes=4194304)}else{if(!n)if(s=cue(l),s!==null){if(t.flags|=128,n=!0,r=s.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),MD(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Gc)return km(t),null}else 2*eu()-i.renderingStartTime>oI&&r!==1073741824&&(t.flags|=128,n=!0,MD(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=eu(),t.sibling=null,r=id.current,fc(id,n?r&1|2:r&1),t):(km(t),null);case 22:case 23:return s4e(),n=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?ex&1073741824&&(km(t),t.subtreeFlags&6&&(t.flags|=8192)):km(t),null;case 24:return null;case 25:return null}throw Error(dn(156,t.tag))}function Jwt(s,t){switch(RCe(t),t.tag){case 1:return hp(t.type)&&sue(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return aI(),Ic(up),Ic(Om),HCe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return VCe(t),null;case 13:if(Ic(id),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(dn(340));rI()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Ic(id),null;case 4:return aI(),null;case 10:return zCe(t.type._context),null;case 22:case 23:return s4e(),null;case 24:return null;default:return null}}var P$=!1,Am=!1,ejt=typeof WeakSet=="function"?WeakSet:Set,ha=null;function CA(s,t){var r=s.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Ed(s,t,n)}else r.current=null}function Jwe(s,t,r){try{r()}catch(n){Ed(s,t,n)}}var LDe=!1;function tjt(s,t){if(Rwe=Qde,s=TKe(),LCe(s)){if("selectionStart"in s)var r={start:s.selectionStart,end:s.selectionEnd};else e:{r=(r=s.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var a=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var l=0,o=-1,c=-1,d=0,h=0,m=s,x=null;t:for(;;){for(var g;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),(g=m.firstChild)!==null;)x=m,m=g;for(;;){if(m===s)break t;if(x===r&&++d===a&&(o=l),x===i&&++h===n&&(c=l),(g=m.nextSibling)!==null)break;m=x,x=m.parentNode}m=g}r=o===-1||c===-1?null:{start:o,end:c}}else r=null}r=r||{start:0,end:0}}else r=null;for(Owe={focusedElem:s,selectionRange:r},Qde=!1,ha=t;ha!==null;)if(t=ha,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,ha=s;else for(;ha!==null;){t=ha;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var j=v.memoizedProps,b=v.memoizedState,N=t.stateNode,S=N.getSnapshotBeforeUpdate(t.elementType===t.type?j:Oy(t.type,j),b);N.__reactInternalSnapshotBeforeUpdate=S}break;case 3:var T=t.stateNode.containerInfo;T.nodeType===1?T.textContent="":T.nodeType===9&&T.documentElement&&T.removeChild(T.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(dn(163))}}catch(A){Ed(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,ha=s;break}ha=t.return}return v=LDe,LDe=!1,v}function zR(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&&Jwe(t,r,i)}a=a.next}while(a!==n)}}function Dfe(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 eje(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 NYe(s){var t=s.alternate;t!==null&&(s.alternate=null,NYe(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[jv],delete t[F8],delete t[zwe],delete t[Owt],delete t[Fwt])),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 kYe(s){return s.tag===5||s.tag===3||s.tag===4}function DDe(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||kYe(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 tje(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=tue));else if(n!==4&&(s=s.child,s!==null))for(tje(s,t,r),s=s.sibling;s!==null;)tje(s,t,r),s=s.sibling}function sje(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(sje(s,t,r),s=s.sibling;s!==null;)sje(s,t,r),s=s.sibling}var Gh=null,By=!1;function Tw(s,t,r){for(r=r.child;r!==null;)SYe(s,t,r),r=r.sibling}function SYe(s,t,r){if(Rv&&typeof Rv.onCommitFiberUnmount=="function")try{Rv.onCommitFiberUnmount(Cfe,r)}catch{}switch(r.tag){case 5:Am||CA(r,t);case 6:var n=Gh,a=By;Gh=null,Tw(s,t,r),Gh=n,By=a,Gh!==null&&(By?(s=Gh,r=r.stateNode,s.nodeType===8?s.parentNode.removeChild(r):s.removeChild(r)):Gh.removeChild(r.stateNode));break;case 18:Gh!==null&&(By?(s=Gh,r=r.stateNode,s.nodeType===8?Lve(s.parentNode,r):s.nodeType===1&&Lve(s,r),P8(s)):Lve(Gh,r.stateNode));break;case 4:n=Gh,a=By,Gh=r.stateNode.containerInfo,By=!0,Tw(s,t,r),Gh=n,By=a;break;case 0:case 11:case 14:case 15:if(!Am&&(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)&&Jwe(r,t,l),a=a.next}while(a!==n)}Tw(s,t,r);break;case 1:if(!Am&&(CA(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){Ed(r,t,o)}Tw(s,t,r);break;case 21:Tw(s,t,r);break;case 22:r.mode&1?(Am=(n=Am)||r.memoizedState!==null,Tw(s,t,r),Am=n):Tw(s,t,r);break;default:Tw(s,t,r)}}function RDe(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var r=s.stateNode;r===null&&(r=s.stateNode=new ejt),t.forEach(function(n){var a=djt.bind(null,s,n);r.has(n)||(r.add(n),n.then(a,a))})}}function Cy(s,t){var r=t.deletions;if(r!==null)for(var n=0;na&&(a=l),n&=~i}if(n=a,n=eu()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*rjt(n/1960))-n,10s?16:s,Cj===null)var n=!1;else{if(s=Cj,Cj=null,fue=0,Ko&6)throw Error(dn(331));var a=Ko;for(Ko|=4,ha=s.current;ha!==null;){var i=ha,l=i.child;if(ha.flags&16){var o=i.deletions;if(o!==null){for(var c=0;ceu()-e4e?p3(s,0):JCe|=r),mp(s,t)}function LYe(s,t){t===0&&(s.mode&1?(t=N$,N$<<=1,!(N$&130023424)&&(N$=4194304)):t=1);var r=kf();s=f_(s,t),s!==null&&(NB(s,t,r),mp(s,r))}function cjt(s){var t=s.memoizedState,r=0;t!==null&&(r=t.retryLane),LYe(s,r)}function djt(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(dn(314))}n!==null&&n.delete(t),LYe(s,r)}var DYe;DYe=function(s,t,r){if(s!==null)if(s.memoizedProps!==t.pendingProps||up.current)op=!0;else{if(!(s.lanes&r)&&!(t.flags&128))return op=!1,Xwt(s,t,r);op=!!(s.flags&131072)}else op=!1,Gc&&t.flags&1048576&&BKe(t,aue,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;Lq(s,t),s=t.pendingProps;var a=sI(t,Om.current);KA(t,r),a=WCe(null,t,n,s,a,r);var i=KCe();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,hp(n)?(i=!0,rue(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,UCe(t),a.updater=Lfe,t.stateNode=a,a._reactInternals=t,Gwe(t,n,s,r),t=Ywe(null,t,n,!0,i,r)):(t.tag=0,Gc&&i&&DCe(t),uf(null,t,a,r),t=t.child),t;case 16:n=t.elementType;e:{switch(Lq(s,t),s=t.pendingProps,a=n._init,n=a(n._payload),t.type=n,a=t.tag=hjt(n),s=Oy(n,s),a){case 0:t=Kwe(null,t,n,s,r);break e;case 1:t=MDe(null,t,n,s,r);break e;case 11:t=EDe(null,t,n,s,r);break e;case 14:t=ADe(null,t,n,Oy(n.type,s),r);break e}throw Error(dn(306,n,""))}return t;case 0:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Oy(n,a),Kwe(s,t,n,a,r);case 1:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Oy(n,a),MDe(s,t,n,a,r);case 3:e:{if(yYe(t),s===null)throw Error(dn(387));n=t.pendingProps,i=t.memoizedState,a=i.element,HKe(s,t),lue(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=iI(Error(dn(423)),t),t=IDe(s,t,n,r,a);break e}else if(n!==a){a=iI(Error(dn(424)),t),t=IDe(s,t,n,r,a);break e}else for(mx=Oj(t.stateNode.containerInfo.firstChild),px=t,Gc=!0,Vy=null,r=qKe(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(rI(),n===a){t=p_(s,t,r);break e}uf(s,t,n,r)}t=t.child}return t;case 5:return GKe(t),s===null&&qwe(t),n=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,Fwe(n,a)?l=null:i!==null&&Fwe(n,i)&&(t.flags|=32),gYe(s,t),uf(s,t,l,r),t.child;case 6:return s===null&&qwe(t),null;case 13:return vYe(s,t,r);case 4:return qCe(t,t.stateNode.containerInfo),n=t.pendingProps,s===null?t.child=nI(t,null,n,r):uf(s,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Oy(n,a),EDe(s,t,n,a,r);case 7:return uf(s,t,t.pendingProps,r),t.child;case 8:return uf(s,t,t.pendingProps.children,r),t.child;case 12:return uf(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,fc(iue,n._currentValue),n._currentValue=l,i!==null)if(d0(i.value,l)){if(i.children===a.children&&!up.current){t=p_(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=Zb(-1,r&-r),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?c.next=c:(c.next=h.next,h.next=c),d.pending=c}}i.lanes|=r,c=i.alternate,c!==null&&(c.lanes|=r),Vwe(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(dn(341));l.lanes|=r,o=l.alternate,o!==null&&(o.lanes|=r),Vwe(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}uf(s,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=t.pendingProps.children,KA(t,r),a=Gg(a),n=n(a),t.flags|=1,uf(s,t,n,r),t.child;case 14:return n=t.type,a=Oy(n,t.pendingProps),a=Oy(n.type,a),ADe(s,t,n,a,r);case 15:return pYe(s,t,t.type,t.pendingProps,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Oy(n,a),Lq(s,t),t.tag=1,hp(n)?(s=!0,rue(t)):s=!1,KA(t,r),hYe(t,n,a),Gwe(t,n,a,r),Ywe(null,t,n,!0,s,r);case 19:return bYe(s,t,r);case 22:return xYe(s,t,r)}throw Error(dn(156,t.tag))};function RYe(s,t){return cKe(s,t)}function ujt(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 Lg(s,t,r,n){return new ujt(s,t,r,n)}function n4e(s){return s=s.prototype,!(!s||!s.isReactComponent)}function hjt(s){if(typeof s=="function")return n4e(s)?1:0;if(s!=null){if(s=s.$$typeof,s===jCe)return 11;if(s===NCe)return 14}return 2}function $j(s,t){var r=s.alternate;return r===null?(r=Lg(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 Oq(s,t,r,n,a,i){var l=2;if(n=s,typeof s=="function")n4e(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case yA:return x3(r.children,a,i,t);case wCe:l=8,a|=8;break;case xwe:return s=Lg(12,r,t,a|2),s.elementType=xwe,s.lanes=i,s;case gwe:return s=Lg(13,r,t,a),s.elementType=gwe,s.lanes=i,s;case ywe:return s=Lg(19,r,t,a),s.elementType=ywe,s.lanes=i,s;case GWe:return Ofe(r,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case VWe:l=10;break e;case HWe:l=9;break e;case jCe:l=11;break e;case NCe:l=14;break e;case Yw:l=16,n=null;break e}throw Error(dn(130,s==null?s:typeof s,""))}return t=Lg(l,r,t,a),t.elementType=s,t.type=n,t.lanes=i,t}function x3(s,t,r,n){return s=Lg(7,s,n,t),s.lanes=r,s}function Ofe(s,t,r,n){return s=Lg(22,s,n,t),s.elementType=GWe,s.lanes=r,s.stateNode={isHidden:!1},s}function Uve(s,t,r){return s=Lg(6,s,null,t),s.lanes=r,s}function qve(s,t,r){return t=Lg(4,s.children!==null?s.children:[],s.key,t),t.lanes=r,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function mjt(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=jve(0),this.expirationTimes=jve(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=jve(0),this.identifierPrefix=n,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function a4e(s,t,r,n,a,i,l,o,c){return s=new mjt(s,t,r,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Lg(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},UCe(i),s}function fjt(s,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(zYe)}catch(s){console.error(s)}}zYe(),zWe.exports=$x;var pf=zWe.exports;const $Ye=Io(pf);var UYe,VDe=pf;UYe=VDe.createRoot,VDe.hydrateRoot;const vjt=1,bjt=1e6;let Vve=0;function _jt(){return Vve=(Vve+1)%Number.MAX_SAFE_INTEGER,Vve.toString()}const Hve=new Map,HDe=s=>{if(Hve.has(s))return;const t=setTimeout(()=>{Hve.delete(s),qR({type:"REMOVE_TOAST",toastId:s})},bjt);Hve.set(s,t)},wjt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,vjt)};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?HDe(r):s.toasts.forEach(n=>{HDe(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)}}},Fq=[];let Bq={toasts:[]};function qR(s){Bq=wjt(Bq,s),Fq.forEach(t=>{t(Bq)})}function nn({...s}){const t=_jt(),r=a=>qR({type:"UPDATE_TOAST",toast:{...a,id:t}}),n=()=>qR({type:"DISMISS_TOAST",toastId:t});return qR({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||n()}}}),{id:t,dismiss:n,update:r}}function Ea(){const[s,t]=k.useState(Bq);return k.useEffect(()=>(Fq.push(t),()=>{const r=Fq.indexOf(t);r>-1&&Fq.splice(r,1)}),[s]),{...s,toast:nn,dismiss:r=>qR({type:"DISMISS_TOAST",toastId:r})}}function Or(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 GDe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function y2(...s){return t=>{let r=!1;const n=s.map(a=>{const i=GDe(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 yd(s,t=[]){let r=[];function n(i,l){const o=k.createContext(l);o.displayName=i+"Context";const c=r.length;r=[...r,l];const d=m=>{var N;const{scope:x,children:g,...v}=m,j=((N=x==null?void 0:x[s])==null?void 0:N[c])||o,b=k.useMemo(()=>v,Object.values(v));return e.jsx(j.Provider,{value:b,children:g})};d.displayName=i+"Provider";function h(m,x){var j;const g=((j=x==null?void 0:x[s])==null?void 0:j[c])||o,v=k.useContext(g);if(v)return v;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${i}\``)}return[d,h]}const a=()=>{const i=r.map(l=>k.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return k.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[n,Njt(a,...t)]}function Njt(...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 v2(s){const t=k.forwardRef((r,n)=>{let{children:a,...i}=r,l=null,o=!1;const c=[];WDe(a)&&typeof R$=="function"&&(a=R$(a._payload)),k.Children.forEach(a,x=>{var g;if(Tjt(x)){o=!0;const v=x;let j="child"in v.props?v.props.child:v.props.children;WDe(j)&&typeof R$=="function"&&(j=R$(j._payload)),l=kjt(v,j),c.push((g=l==null?void 0:l.props)==null?void 0:g.children)}else c.push(x)}),l?l=k.cloneElement(l,void 0,c):!o&&k.Children.count(a)===1&&k.isValidElement(a)&&(l=a);const d=l?Cjt(l):void 0,h=Qa(n,d);if(!l){if(a||a===0)throw new Error(o?Ijt(s):Mjt(s));return a}const m=Sjt(i,l.props??{});return l.type!==k.Fragment&&(m.ref=n?h:d),k.cloneElement(l,m)});return t.displayName=`${s}.Slot`,t}var c4e=v2("Slot"),qYe=Symbol.for("radix.slottable");function VYe(s){const t=r=>"child"in r?r.children(r.child):r.children;return t.displayName=`${s}.Slottable`,t.__radixId=qYe,t}var kjt=(s,t)=>{if("child"in s.props){const r=s.props.child;return k.isValidElement(r)?k.cloneElement(r,void 0,s.props.children(r.props.children)):null}return k.isValidElement(t)?t:null};function Sjt(s,t){const r={...t};for(const n in t){const a=s[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(r[n]=a):n==="style"?r[n]={...a,...i}:n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return{...s,...r}}function Cjt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}function Tjt(s){return k.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===qYe}var Ejt=Symbol.for("react.lazy");function WDe(s){return s!=null&&typeof s=="object"&&"$$typeof"in s&&s.$$typeof===Ejt&&"_payload"in s&&Ajt(s._payload)}function Ajt(s){return typeof s=="object"&&s!==null&&"then"in s}var Mjt=s=>`${s} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Ijt=s=>`${s} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,R$=jB[" use ".trim().toString()];function TB(s){const t=s+"CollectionProvider",[r,n]=yd(t),[a,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),l=j=>{const{scope:b,children:N}=j,S=k.useRef(null),T=k.useRef(new Map).current;return e.jsx(a,{scope:b,itemMap:T,collectionRef:S,children:N})};l.displayName=t;const o=s+"CollectionSlot",c=v2(o),d=k.forwardRef((j,b)=>{const{scope:N,children:S}=j,T=i(o,N),A=Qa(b,T.collectionRef);return e.jsx(c,{ref:A,children:S})});d.displayName=o;const h=s+"CollectionItemSlot",m="data-radix-collection-item",x=v2(h),g=k.forwardRef((j,b)=>{const{scope:N,children:S,...T}=j,A=k.useRef(null),P=Qa(b,A),D=i(h,N);return k.useEffect(()=>(D.itemMap.set(A,{ref:A,...T}),()=>void D.itemMap.delete(A))),e.jsx(x,{[m]:"",ref:P,children:S})});g.displayName=h;function v(j){const b=i(s+"CollectionConsumer",j);return k.useCallback(()=>{const S=b.collectionRef.current;if(!S)return[];const T=Array.from(S.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((D,B)=>T.indexOf(D.ref.current)-T.indexOf(B.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:d,ItemSlot:g},v,n]}var Pjt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=Pjt.reduce((s,t)=>{const r=v2(`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 d4e(s,t){s&&pf.flushSync(()=>s.dispatchEvent(t))}function Ld(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 Ljt(s,t=globalThis==null?void 0:globalThis.document){const r=Ld(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 Djt="DismissableLayer",oje="dismissableLayer.update",Rjt="dismissableLayer.pointerDownOutside",Ojt="dismissableLayer.focusOutside",KDe,HYe=k.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),F2=k.forwardRef((s,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=k.useContext(HYe),[h,m]=k.useState(null),x=(h==null?void 0:h.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,g]=k.useState({}),v=Qa(t,B=>m(B)),j=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),N=j.indexOf(b),S=h?j.indexOf(h):-1,T=d.layersWithOutsidePointerEventsDisabled.size>0,A=S>=N,P=Bjt(B=>{const z=B.target,F=[...d.branches].some($=>$.contains(z));!A||F||(a==null||a(B),l==null||l(B),B.defaultPrevented||o==null||o())},x),D=zjt(B=>{const z=B.target;[...d.branches].some($=>$.contains(z))||(i==null||i(B),l==null||l(B),B.defaultPrevented||o==null||o())},x);return Ljt(B=>{S===d.layers.size-1&&(n==null||n(B),!B.defaultPrevented&&o&&(B.preventDefault(),o()))},x),k.useEffect(()=>{if(h)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(KDe=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(h)),d.layers.add(h),YDe(),()=>{r&&(d.layersWithOutsidePointerEventsDisabled.delete(h),d.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=KDe))}},[h,x,r,d]),k.useEffect(()=>()=>{h&&(d.layers.delete(h),d.layersWithOutsidePointerEventsDisabled.delete(h),YDe())},[h,d]),k.useEffect(()=>{const B=()=>g({});return document.addEventListener(oje,B),()=>document.removeEventListener(oje,B)},[]),e.jsx(pn.div,{...c,ref:v,style:{pointerEvents:T?A?"auto":"none":void 0,...s.style},onFocusCapture:Or(s.onFocusCapture,D.onFocusCapture),onBlurCapture:Or(s.onBlurCapture,D.onBlurCapture),onPointerDownCapture:Or(s.onPointerDownCapture,P.onPointerDownCapture)})});F2.displayName=Djt;var Fjt="DismissableLayerBranch",GYe=k.forwardRef((s,t)=>{const r=k.useContext(HYe),n=k.useRef(null),a=Qa(t,n);return k.useEffect(()=>{const i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),e.jsx(pn.div,{...s,ref:a})});GYe.displayName=Fjt;function Bjt(s,t=globalThis==null?void 0:globalThis.document){const r=Ld(s),n=k.useRef(!1),a=k.useRef(()=>{});return k.useEffect(()=>{const i=o=>{if(o.target&&!n.current){let c=function(){WYe(Rjt,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 zjt(s,t=globalThis==null?void 0:globalThis.document){const r=Ld(s),n=k.useRef(!1);return k.useEffect(()=>{const a=i=>{i.target&&!n.current&&WYe(Ojt,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 YDe(){const s=new CustomEvent(oje);document.dispatchEvent(s)}function WYe(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?d4e(a,i):a.dispatchEvent(i)}var $jt=F2,Ujt=GYe,fd=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},qjt="Portal",xP=k.forwardRef((s,t)=>{var o;const{container:r,...n}=s,[a,i]=k.useState(!1);fd(()=>i(!0),[]);const l=r||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?pf.createPortal(e.jsx(pn.div,{...n,ref:t}),l):null});xP.displayName=qjt;function Vjt(s,t){return k.useReducer((r,n)=>t[r][n]??r,s)}var qd=s=>{const{present:t,children:r}=s,n=Hjt(t),a=typeof r=="function"?r({present:n.isPresent}):k.Children.only(r),i=Gjt(n.ref,Wjt(a));return typeof r=="function"||n.isPresent?k.cloneElement(a,{ref:i}):null};qd.displayName="Presence";function Hjt(s){const[t,r]=k.useState(),n=k.useRef(null),a=k.useRef(s),i=k.useRef("none"),l=s?"mounted":"unmounted",[o,c]=Vjt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return k.useEffect(()=>{const d=O$(n.current);i.current=o==="mounted"?d:"none"},[o]),fd(()=>{const d=n.current,h=a.current;if(h!==s){const x=i.current,g=O$(d);s?c("MOUNT"):g==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(h&&x!==g?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),fd(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,m=g=>{const j=O$(n.current).includes(CSS.escape(g.animationName));if(g.target===t&&j&&(c("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},x=g=>{g.target===t&&(i.current=O$(n.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:k.useCallback(d=>{n.current=d?getComputedStyle(d):null,r(d)},[])}}function ZDe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function Gjt(...s){const t=k.useRef(s);return t.current=s,k.useCallback(r=>{const n=t.current;let a=!1;const i=n.map(l=>{const o=ZDe(l,r);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let l=0;l{},caller:n}){const[a,i,l]=Yjt({defaultProp:t,onChange:r}),o=s!==void 0,c=o?s:a;{const h=k.useRef(s!==void 0);k.useEffect(()=>{const m=h.current;m!==o&&console.warn(`${n} is changing from ${m?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),h.current=o},[o,n])}const d=k.useCallback(h=>{var m;if(o){const x=Zjt(h)?h(s):h;x!==s&&((m=l.current)==null||m.call(l,x))}else i(h)},[o,s,i,l]);return[c,d]}function Yjt({defaultProp:s,onChange:t}){const[r,n]=k.useState(s),a=k.useRef(r),i=k.useRef(t);return Kjt(()=>{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 Zjt(s){return typeof s=="function"}var KYe=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"}),Xjt="VisuallyHidden",Ufe=k.forwardRef((s,t)=>e.jsx(pn.span,{...s,ref:t,style:{...KYe,...s.style}}));Ufe.displayName=Xjt;var Qjt=Ufe,u4e="ToastProvider",[h4e,Jjt,e2t]=TB("Toast"),[YYe]=yd("Toast",[e2t]),[t2t,qfe]=YYe(u4e),ZYe=s=>{const{__scopeToast:t,label:r="Notification",duration:n=5e3,swipeDirection:a="right",swipeThreshold:i=50,announcerContainer:l,children:o}=s,[c,d]=k.useState(null),[h,m]=k.useState(0),x=k.useRef(!1),g=k.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${u4e}\`. Expected non-empty \`string\`.`),e.jsx(h4e.Provider,{scope:t,children:e.jsx(t2t,{scope:t,label:r,duration:n,swipeDirection:a,swipeThreshold:i,toastCount:h,viewport:c,onViewportChange:d,onToastAdd:k.useCallback(()=>m(v=>v+1),[]),onToastRemove:k.useCallback(()=>m(v=>v-1),[]),isFocusedToastEscapeKeyDownRef:x,isClosePausedRef:g,announcerContainer:l,children:o})})};ZYe.displayName=u4e;var XYe="ToastViewport",s2t=["F8"],lje="toast.viewportPause",cje="toast.viewportResume",QYe=k.forwardRef((s,t)=>{const{__scopeToast:r,hotkey:n=s2t,label:a="Notifications ({hotkey})",...i}=s,l=qfe(XYe,r),o=Jjt(r),c=k.useRef(null),d=k.useRef(null),h=k.useRef(null),m=k.useRef(null),x=Qa(t,m,l.onViewportChange),g=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),v=l.toastCount>0;k.useEffect(()=>{const b=N=>{var T;n.length!==0&&n.every(A=>N[A]||N.code===A)&&((T=m.current)==null||T.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),k.useEffect(()=>{const b=c.current,N=m.current;if(v&&b&&N){const S=()=>{if(!l.isClosePausedRef.current){const D=new CustomEvent(lje);N.dispatchEvent(D),l.isClosePausedRef.current=!0}},T=()=>{if(l.isClosePausedRef.current){const D=new CustomEvent(cje);N.dispatchEvent(D),l.isClosePausedRef.current=!1}},A=D=>{!b.contains(D.relatedTarget)&&T()},P=()=>{b.contains(document.activeElement)||T()};return b.addEventListener("focusin",S),b.addEventListener("focusout",A),b.addEventListener("pointermove",S),b.addEventListener("pointerleave",P),window.addEventListener("blur",S),window.addEventListener("focus",T),()=>{b.removeEventListener("focusin",S),b.removeEventListener("focusout",A),b.removeEventListener("pointermove",S),b.removeEventListener("pointerleave",P),window.removeEventListener("blur",S),window.removeEventListener("focus",T)}}},[v,l.isClosePausedRef]);const j=k.useCallback(({tabbingDirection:b})=>{const S=o().map(T=>{const A=T.ref.current,P=[A,...p2t(A)];return b==="forwards"?P:P.reverse()});return(b==="forwards"?S.reverse():S).flat()},[o]);return k.useEffect(()=>{const b=m.current;if(b){const N=S=>{var P,D,B;const T=S.altKey||S.ctrlKey||S.metaKey;if(S.key==="Tab"&&!T){const z=document.activeElement,F=S.shiftKey;if(S.target===b&&F){(P=d.current)==null||P.focus();return}const K=j({tabbingDirection:F?"backwards":"forwards"}),Q=K.findIndex(Y=>Y===z);Gve(K.slice(Q+1))?S.preventDefault():F?(D=d.current)==null||D.focus():(B=h.current)==null||B.focus()}};return b.addEventListener("keydown",N),()=>b.removeEventListener("keydown",N)}},[o,j]),e.jsxs(Ujt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",g),tabIndex:-1,style:{pointerEvents:v?void 0:"none"},children:[v&&e.jsx(dje,{ref:d,onFocusFromOutsideViewport:()=>{const b=j({tabbingDirection:"forwards"});Gve(b)}}),e.jsx(h4e.Slot,{scope:r,children:e.jsx(pn.ol,{tabIndex:-1,...i,ref:x})}),v&&e.jsx(dje,{ref:h,onFocusFromOutsideViewport:()=>{const b=j({tabbingDirection:"backwards"});Gve(b)}})]})});QYe.displayName=XYe;var JYe="ToastFocusProxy",dje=k.forwardRef((s,t)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...a}=s,i=qfe(JYe,r);return e.jsx(Ufe,{tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&n()}})});dje.displayName=JYe;var EB="Toast",r2t="toast.swipeStart",n2t="toast.swipeMove",a2t="toast.swipeCancel",i2t="toast.swipeEnd",eZe=k.forwardRef((s,t)=>{const{forceMount:r,open:n,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Lh({prop:n,defaultProp:a??!0,onChange:i,caller:EB});return e.jsx(qd,{present:r||o,children:e.jsx(c2t,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:Ld(s.onPause),onResume:Ld(s.onResume),onSwipeStart:Or(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Or(s.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:Or(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:Or(s.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),c(!1)})})})});eZe.displayName=EB;var[o2t,l2t]=YYe(EB,{onClose(){}}),c2t=k.forwardRef((s,t)=>{const{__scopeToast:r,type:n="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:x,onSwipeEnd:g,...v}=s,j=qfe(EB,r),[b,N]=k.useState(null),S=Qa(t,Y=>N(Y)),T=k.useRef(null),A=k.useRef(null),P=a||j.duration,D=k.useRef(0),B=k.useRef(P),z=k.useRef(0),{onToastAdd:F,onToastRemove:$}=j,X=Ld(()=>{var ne;(b==null?void 0:b.contains(document.activeElement))&&((ne=j.viewport)==null||ne.focus()),l()}),K=k.useCallback(Y=>{!Y||Y===1/0||(window.clearTimeout(z.current),D.current=new Date().getTime(),z.current=window.setTimeout(X,Y))},[X]);k.useEffect(()=>{const Y=j.viewport;if(Y){const ne=()=>{K(B.current),d==null||d()},de=()=>{const ce=new Date().getTime()-D.current;B.current=B.current-ce,window.clearTimeout(z.current),c==null||c()};return Y.addEventListener(lje,de),Y.addEventListener(cje,ne),()=>{Y.removeEventListener(lje,de),Y.removeEventListener(cje,ne)}}},[j.viewport,P,c,d,K]),k.useEffect(()=>{i&&!j.isClosePausedRef.current&&K(P)},[i,P,j.isClosePausedRef,K]),k.useEffect(()=>(F(),()=>$()),[F,$]);const Q=k.useMemo(()=>b?oZe(b):null,[b]);return j.viewport?e.jsxs(e.Fragment,{children:[Q&&e.jsx(d2t,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite",children:Q}),e.jsx(o2t,{scope:r,onClose:X,children:pf.createPortal(e.jsx(h4e.ItemSlot,{scope:r,children:e.jsx($jt,{asChild:!0,onEscapeKeyDown:Or(o,()=>{j.isFocusedToastEscapeKeyDownRef.current||X(),j.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(pn.li,{tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":j.swipeDirection,...v,ref:S,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:Or(s.onKeyDown,Y=>{Y.key==="Escape"&&(o==null||o(Y.nativeEvent),Y.nativeEvent.defaultPrevented||(j.isFocusedToastEscapeKeyDownRef.current=!0,X()))}),onPointerDown:Or(s.onPointerDown,Y=>{Y.button===0&&(T.current={x:Y.clientX,y:Y.clientY})}),onPointerMove:Or(s.onPointerMove,Y=>{if(!T.current)return;const ne=Y.clientX-T.current.x,de=Y.clientY-T.current.y,ce=!!A.current,ae=["left","right"].includes(j.swipeDirection),ie=["left","up"].includes(j.swipeDirection)?Math.min:Math.max,me=ae?ie(0,ne):0,oe=ae?0:ie(0,de),ge=Y.pointerType==="touch"?10:2,be={x:me,y:oe},Oe={originalEvent:Y,delta:be};ce?(A.current=be,F$(n2t,m,Oe,{discrete:!1})):XDe(be,j.swipeDirection,ge)?(A.current=be,F$(r2t,h,Oe,{discrete:!1}),Y.target.setPointerCapture(Y.pointerId)):(Math.abs(ne)>ge||Math.abs(de)>ge)&&(T.current=null)}),onPointerUp:Or(s.onPointerUp,Y=>{const ne=A.current,de=Y.target;if(de.hasPointerCapture(Y.pointerId)&&de.releasePointerCapture(Y.pointerId),A.current=null,T.current=null,ne){const ce=Y.currentTarget,ae={originalEvent:Y,delta:ne};XDe(ne,j.swipeDirection,j.swipeThreshold)?F$(i2t,g,ae,{discrete:!0}):F$(a2t,x,ae,{discrete:!0}),ce.addEventListener("click",ie=>ie.preventDefault(),{once:!0})}})})})}),j.viewport)})]}):null}),d2t=s=>{const{__scopeToast:t,children:r,...n}=s,a=qfe(EB,t),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return m2t(()=>l(!0)),k.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(xP,{asChild:!0,container:a.announcerContainer||void 0,children:e.jsx(Ufe,{...n,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",r]})})})},u2t="ToastTitle",tZe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(pn.div,{...n,ref:t})});tZe.displayName=u2t;var h2t="ToastDescription",sZe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(pn.div,{...n,ref:t})});sZe.displayName=h2t;var rZe="ToastAction",nZe=k.forwardRef((s,t)=>{const{altText:r,...n}=s;return r.trim()?e.jsx(iZe,{altText:r,asChild:!0,children:e.jsx(m4e,{...n,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${rZe}\`. Expected non-empty \`string\`.`),null)});nZe.displayName=rZe;var aZe="ToastClose",m4e=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s,a=l2t(aZe,r);return e.jsx(iZe,{asChild:!0,children:e.jsx(pn.button,{type:"button",...n,ref:t,onClick:Or(s.onClick,a.onClose)})})});m4e.displayName=aZe;var iZe=k.forwardRef((s,t)=>{const{__scopeToast:r,altText:n,...a}=s;return e.jsx(pn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...a,ref:t})});function oZe(s){const t=[];return Array.from(s.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),f2t(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(...oZe(n))}}),t}function F$(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?d4e(a,i):a.dispatchEvent(i)}var XDe=(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 m2t(s=()=>{}){const t=Ld(s);fd(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[t])}function f2t(s){return s.nodeType===s.ELEMENT_NODE}function p2t(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 Gve(s){const t=document.activeElement;return s.some(r=>r===t?!0:(r.focus(),document.activeElement!==t))}var x2t=ZYe,lZe=QYe,cZe=eZe,dZe=tZe,uZe=sZe,hZe=nZe,mZe=m4e;function fZe(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,JDe=Ui,V5=(s,t)=>r=>{var n;if((t==null?void 0:t.variants)==null)return JDe(s,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const h=r==null?void 0:r[d],m=i==null?void 0:i[d];if(h===null)return null;const x=QDe(h)||QDe(m);return a[d][x]}),o=r&&Object.entries(r).reduce((d,h)=>{let[m,x]=h;return x===void 0||(d[m]=x),d},{}),c=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((d,h)=>{let{class:m,className:x,...g}=h;return Object.entries(g).every(v=>{let[j,b]=v;return Array.isArray(b)?b.includes({...i,...o}[j]):{...i,...o}[j]===b})?[...d,m,x]:d},[]);return JDe(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 g2t=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),pZe=(...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 y2t={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 xZe=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,...y2t,width:t,height:t,stroke:s,strokeWidth:n?Number(r)*24/Number(t):r,className:pZe("lucide",a),...o},[...l.map(([d,h])=>k.createElement(d,h)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ee=(s,t)=>{const r=k.forwardRef(({className:n,...a},i)=>k.createElement(xZe,{ref:i,iconNode:t,className:pZe(`lucide-${g2t(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 zq=ee("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 $q=ee("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 Uq=ee("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 qq=ee("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 Ch=ee("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 Vq=ee("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 Hq=ee("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 gk=ee("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 yk=ee("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 Gq=ee("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 vk=ee("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 Wq=ee("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 Kq=ee("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 Yq=ee("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 Zq=ee("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 Xq=ee("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 g3=ee("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 Qq=ee("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 Jq=ee("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 eV=ee("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 tV=ee("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 sV=ee("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 rV=ee("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 nV=ee("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 aV=ee("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 iV=ee("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 oV=ee("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 lV=ee("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 y3=ee("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 v3=ee("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 cV=ee("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 dV=ee("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 uV=ee("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 hV=ee("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 mV=ee("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 fV=ee("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 pV=ee("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 xV=ee("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 gV=ee("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 yV=ee("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 vV=ee("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 bV=ee("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 _V=ee("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 wV=ee("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 jV=ee("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 NV=ee("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 kV=ee("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 SV=ee("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 CV=ee("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 TV=ee("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 EV=ee("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 VR=ee("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 AV=ee("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 ZA=ee("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 MV=ee("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 Uj=ee("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 IV=ee("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 PV=ee("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 LV=ee("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 DV=ee("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 RV=ee("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 OV=ee("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 FV=ee("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 BV=ee("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 zV=ee("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 $V=ee("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 UV=ee("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 bk=ee("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 qV=ee("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 VV=ee("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 HV=ee("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 HR=ee("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 GV=ee("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 WV=ee("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 KV=ee("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 _k=ee("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 wk=ee("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 Ku=ee("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 YV=ee("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 ZV=ee("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 XV=ee("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 wa=ee("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 QV=ee("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 Xb=ee("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 JV=ee("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 Ga=ee("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 eH=ee("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 tH=ee("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 jk=ee("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 Rd=ee("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 sH=ee("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 rH=ee("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 nH=ee("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 Nk=ee("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 GR=ee("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 aH=ee("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 iH=ee("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 kk=ee("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 Fd=ee("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 oH=ee("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 lH=ee("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 cH=ee("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 dH=ee("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 uH=ee("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 hH=ee("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 Xl=ee("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 mH=ee("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 Sk=ee("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 fH=ee("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 pH=ee("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 xH=ee("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 gH=ee("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 Ck=ee("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 yH=ee("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 vH=ee("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 bH=ee("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 _H=ee("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 wH=ee("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 jH=ee("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 NH=ee("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 kH=ee("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 SH=ee("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 CH=ee("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 TH=ee("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 EH=ee("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 AH=ee("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 MH=ee("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 IH=ee("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 WR=ee("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 PH=ee("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 LH=ee("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 DH=ee("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 RH=ee("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 OH=ee("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 fp=ee("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 FH=ee("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 BH=ee("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 zH=ee("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 $H=ee("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 UH=ee("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 qH=ee("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 VH=ee("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 HH=ee("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 GH=ee("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 b3=ee("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 WH=ee("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 e0=ee("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 KH=ee("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 YH=ee("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 ZH=ee("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 XH=ee("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 QH=ee("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 JH=ee("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 Fv=ee("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 eG=ee("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 KR=ee("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 Rm=ee("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 Tk=ee("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 Ek=ee("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 tG=ee("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 sG=ee("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 rG=ee("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 nG=ee("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 aG=ee("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 iG=ee("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 oG=ee("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 lG=ee("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 cG=ee("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 dG=ee("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 uG=ee("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 hG=ee("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 mG=ee("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 fG=ee("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 pG=ee("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 xG=ee("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 qj=ee("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 gG=ee("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 yG=ee("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 vG=ee("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 bG=ee("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 _G=ee("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 wG=ee("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 jG=ee("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 Ak=ee("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 NG=ee("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 kG=ee("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 SG=ee("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 CG=ee("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 TG=ee("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 EG=ee("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 AG=ee("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 MG=ee("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 IG=ee("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 PG=ee("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 Th=ee("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 LG=ee("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 DG=ee("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 RG=ee("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 OG=ee("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 FG=ee("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 BG=ee("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 zG=ee("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 $G=ee("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 UG=ee("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 qG=ee("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 YR=ee("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 VG=ee("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 Bg=ee("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 HG=ee("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 GG=ee("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 WG=ee("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 XA=ee("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 KG=ee("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 YG=ee("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 Mk=ee("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 ZG=ee("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 XG=ee("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 QG=ee("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 ZR=ee("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 JG=ee("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 eW=ee("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 tW=ee("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 sW=ee("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 Yu=ee("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 rW=ee("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 nW=ee("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 aW=ee("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 iW=ee("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 oW=ee("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sa=ee("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 _3=ee("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 lW=ee("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 cW=ee("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 dW=ee("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 uW=ee("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 hW=ee("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 Eh=ee("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 QA=ee("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 mW=ee("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 fW=ee("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 pW=ee("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 xW=ee("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 XR=ee("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 Bv=ee("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 gW=ee("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 pd=ee("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 yW=ee("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 QR=ee("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 vW=ee("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 bW=ee("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 JR=ee("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 _W=ee("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 Ub=ee("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 wW=ee("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 jW=ee("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 NW=ee("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 kW=ee("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 SW=ee("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 rn=ee("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 CW=ee("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 pp=ee("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 TW=ee("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 EW=ee("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 AW=ee("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 MW=ee("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 IW=ee("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 Ik=ee("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 PW=ee("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 LW=ee("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 DW=ee("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 RW=ee("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 OW=ee("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 FW=ee("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 BW=ee("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 zW=ee("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 $W=ee("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 UW=ee("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 qW=ee("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 VW=ee("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 HW=ee("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 Pk=ee("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 Lk=ee("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 GW=ee("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 WW=ee("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 KW=ee("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 Dk=ee("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 Rk=ee("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 Ok=ee("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 YW=ee("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 Fk=ee("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 ZW=ee("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 ao=ee("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 XW=ee("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 Bk=ee("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 QW=ee("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 JW=ee("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 zk=ee("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 $k=ee("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 eK=ee("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 Uk=ee("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 qk=ee("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 Vk=ee("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 tK=ee("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 eO=ee("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 Hn=ee("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 sK=ee("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 rK=ee("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 so=ee("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 nK=ee("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 aK=ee("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 Vo=ee("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 ya=ee("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 xp=ee("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 iK=ee("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 oK=ee("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 lK=ee("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 cK=ee("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 dK=ee("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 uK=ee("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 hK=ee("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 xx=ee("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 mK=ee("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 w3=ee("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 fK=ee("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 pK=ee("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 xK=ee("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 Hi=ee("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 Hk=ee("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 Gk=ee("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 Wk=ee("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 Kk=ee("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 Yk=ee("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 Zk=ee("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 Xk=ee("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 Qk=ee("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 mi=ee("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 Mn=ee("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 Jk=ee("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 eS=ee("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 tS=ee("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 sS=ee("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 gK=ee("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 rS=ee("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 yK=ee("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 vK=ee("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 bK=ee("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 _K=ee("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 wK=ee("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 jK=ee("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 NK=ee("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 nS=ee("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 Ab=ee("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 aS=ee("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 kK=ee("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 iS=ee("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 oS=ee("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 lS=ee("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 cS=ee("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 mf=ee("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 dS=ee("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 uS=ee("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 hS=ee("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 SK=ee("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 mS=ee("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 fS=ee("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 pS=ee("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 Mc=ee("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 Bd=ee("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 CK=ee("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 TK=ee("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 EK=ee("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 JA=ee("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 AK=ee("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 Vj=ee("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 MK=ee("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 IK=ee("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 xS=ee("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 gS=ee("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 PK=ee("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 LK=ee("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 DK=ee("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 RK=ee("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 OK=ee("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 FK=ee("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 BK=ee("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 zK=ee("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 $K=ee("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 UK=ee("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 qK=ee("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 VK=ee("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 HK=ee("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 GK=ee("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 WK=ee("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 KK=ee("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 YK=ee("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 ZK=ee("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 XK=ee("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 cn=ee("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 QK=ee("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 JK=ee("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 yS=ee("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 eY=ee("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 tY=ee("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 sY=ee("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 rY=ee("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 nY=ee("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 aY=ee("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 iY=ee("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 oY=ee("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 lY=ee("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 cY=ee("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 dY=ee("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 uY=ee("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 vS=ee("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 hY=ee("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 mY=ee("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 qb=ee("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 fY=ee("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 Mb=ee("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 j3=ee("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 pY=ee("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 xY=ee("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 N3=ee("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 gY=ee("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 tO=ee("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 bS=ee("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 _S=ee("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 yY=ee("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 vY=ee("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 bY=ee("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 eM=ee("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 _Y=ee("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 wY=ee("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 jY=ee("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 NY=ee("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 kY=ee("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 wS=ee("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 k3=ee("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 SY=ee("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 CY=ee("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 TY=ee("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 EY=ee("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 AY=ee("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 MY=ee("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 IY=ee("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 PY=ee("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 LY=ee("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ra=ee("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 DY=ee("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 RY=ee("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 OY=ee("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 FY=ee("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 BY=ee("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 zY=ee("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 $Y=ee("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 UY=ee("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 qY=ee("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 VY=ee("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 HY=ee("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 GY=ee("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 gx=ee("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 WY=ee("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 KY=ee("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 YY=ee("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 ZY=ee("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 nm=ee("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 XY=ee("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 QY=ee("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 JY=ee("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 eZ=ee("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 tZ=ee("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 sZ=ee("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 rZ=ee("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 sO=ee("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 nZ=ee("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 aZ=ee("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 iZ=ee("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 oZ=ee("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 jS=ee("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 lZ=ee("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 cZ=ee("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 dZ=ee("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 uZ=ee("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 hZ=ee("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 mZ=ee("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 fZ=ee("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 pZ=ee("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 xZ=ee("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 gZ=ee("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 yZ=ee("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 vZ=ee("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 bZ=ee("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 _Z=ee("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 wZ=ee("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 jZ=ee("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 NZ=ee("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 kZ=ee("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 SZ=ee("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 _l=ee("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 CZ=ee("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 TZ=ee("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 zv=ee("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 EZ=ee("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 Xa=ee("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 AZ=ee("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 MZ=ee("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 IZ=ee("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 PZ=ee("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 LZ=ee("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 t0=ee("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 DZ=ee("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 RZ=ee("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 OZ=ee("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 FZ=ee("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 BZ=ee("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 zZ=ee("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 NS=ee("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 $Z=ee("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 UZ=ee("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 qZ=ee("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 tM=ee("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 Eg=ee("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 ix=ee("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 VZ=ee("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 HZ=ee("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 GZ=ee("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 WZ=ee("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 KZ=ee("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 YZ=ee("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 ZZ=ee("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 Yr=ee("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 XZ=ee("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 am=ee("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 jn=ee("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 ku=ee("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 QZ=ee("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 JZ=ee("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 eX=ee("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 tX=ee("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 sX=ee("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 rX=ee("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 nX=ee("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 aX=ee("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 iX=ee("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 oX=ee("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 kS=ee("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 lX=ee("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 cX=ee("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 dX=ee("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 SS=ee("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 CS=ee("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 TS=ee("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 ES=ee("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 uX=ee("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 rO=ee("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 hX=ee("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 mX=ee("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 fX=ee("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 AS=ee("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 pX=ee("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 xX=ee("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 S3=ee("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 gX=ee("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 Qb=ee("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 yX=ee("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 vX=ee("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 bX=ee("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 _X=ee("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 wX=ee("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 jX=ee("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 NX=ee("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 kX=ee("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 SX=ee("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 CX=ee("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 TX=ee("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 MS=ee("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 IS=ee("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 EX=ee("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 AX=ee("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 MX=ee("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 IX=ee("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 PX=ee("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 LX=ee("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 DX=ee("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 Jb=ee("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 nO=ee("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 RX=ee("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 OX=ee("FileTerminal",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ln=ee("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 FX=ee("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 BX=ee("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 zX=ee("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 $X=ee("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 UX=ee("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 aO=ee("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 qX=ee("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 VX=ee("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 HX=ee("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 GX=ee("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 WX=ee("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 sM=ee("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 KX=ee("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 Nh=ee("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 YX=ee("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 s0=ee("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 ZX=ee("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 XX=ee("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 QX=ee("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 JX=ee("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 eQ=ee("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 tQ=ee("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 sQ=ee("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 rQ=ee("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 e_=ee("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 nQ=ee("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 xc=ee("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 aQ=ee("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 iQ=ee("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 oQ=ee("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 Hj=ee("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 lQ=ee("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 cQ=ee("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 iO=ee("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 dQ=ee("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 uQ=ee("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 Yy=ee("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 hQ=ee("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 mQ=ee("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 fQ=ee("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 pQ=ee("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 xQ=ee("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 gQ=ee("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 yQ=ee("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 vQ=ee("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 bQ=ee("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 PS=ee("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 _Q=ee("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 wQ=ee("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 jQ=ee("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 NQ=ee("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 kQ=ee("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 SQ=ee("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 CQ=ee("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 TQ=ee("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 EQ=ee("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 AQ=ee("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 MQ=ee("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 im=ee("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 IQ=ee("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 LS=ee("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 PQ=ee("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 LQ=ee("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 DQ=ee("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 RQ=ee("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 OQ=ee("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 FQ=ee("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 BQ=ee("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 zQ=ee("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 $Q=ee("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 UQ=ee("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 qQ=ee("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 VQ=ee("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 HQ=ee("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 GQ=ee("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 WQ=ee("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 KQ=ee("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 YQ=ee("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 ZQ=ee("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 XQ=ee("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 QQ=ee("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 JQ=ee("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 eJ=ee("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 tJ=ee("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 sJ=ee("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 rJ=ee("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 nJ=ee("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 aJ=ee("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 iJ=ee("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 oJ=ee("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 C3=ee("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 li=ee("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 lJ=ee("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 cJ=ee("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 DS=ee("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 dJ=ee("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 uJ=ee("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 hJ=ee("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 mJ=ee("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 fJ=ee("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 pJ=ee("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 xJ=ee("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 gJ=ee("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 yJ=ee("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 vJ=ee("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 bJ=ee("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 _J=ee("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 wJ=ee("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 jJ=ee("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 NJ=ee("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 kJ=ee("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 SJ=ee("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 gc=ee("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 CJ=ee("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 TJ=ee("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 Od=ee("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 EJ=ee("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 AJ=ee("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 RS=ee("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 MJ=ee("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 OS=ee("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 bg=ee("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 IJ=ee("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 Su=ee("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 PJ=ee("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 LJ=ee("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 DJ=ee("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 RJ=ee("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 oO=ee("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 OJ=ee("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 FJ=ee("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 Hy=ee("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 BJ=ee("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 zJ=ee("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 lO=ee("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 Gj=ee("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 $J=ee("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 UJ=ee("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 cO=ee("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 qJ=ee("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 Wj=ee("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 VJ=ee("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 HJ=ee("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 rM=ee("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 nM=ee("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 dO=ee("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 GJ=ee("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 WJ=ee("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 KJ=ee("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 YJ=ee("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 ZJ=ee("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 XJ=ee("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 QJ=ee("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 JJ=ee("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 eee=ee("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 tee=ee("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 see=ee("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 hi=ee("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 ree=ee("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 nee=ee("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 aee=ee("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 aM=ee("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 iee=ee("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 oee=ee("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 lee=ee("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 cee=ee("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 dee=ee("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 uee=ee("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 hee=ee("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 Cn=ee("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 FS=ee("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 BS=ee("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 mee=ee("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 fee=ee("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 pee=ee("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 xee=ee("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 gee=ee("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 $v=ee("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 yee=ee("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 vee=ee("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 fl=ee("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 bee=ee("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 _ee=ee("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 iM=ee("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 zS=ee("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 $S=ee("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 wee=ee("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 jee=ee("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 T3=ee("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 Nee=ee("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 au=ee("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 Kj=ee("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 kee=ee("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 See=ee("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 Cee=ee("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 Tee=ee("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 Uv=ee("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 E3=ee("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 Eee=ee("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 gp=ee("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 Aee=ee("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 Mee=ee("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 Iee=ee("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 Pee=ee("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 Lee=ee("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 Dee=ee("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 Ree=ee("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 Oee=ee("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 Fee=ee("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 Bee=ee("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 zee=ee("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 $ee=ee("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 Uee=ee("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 US=ee("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 qee=ee("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 Vee=ee("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 Hee=ee("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 Gee=ee("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 Wee=ee("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 Kee=ee("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 uO=ee("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 A3=ee("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 Sf=ee("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 Yee=ee("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 Zee=ee("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 Xee=ee("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 M3=ee("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 Qee=ee("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 Jee=ee("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 ete=ee("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 tte=ee("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 ste=ee("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 I3=ee("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 oM=ee("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 rte=ee("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 nte=ee("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 Yj=ee("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 ate=ee("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 rl=ee("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 xo=ee("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 om=ee("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 ite=ee("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 t_=ee("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 ote=ee("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 lte=ee("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 hO=ee("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 cte=ee("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 dte=ee("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 r0=ee("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 ute=ee("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 hte=ee("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 mte=ee("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 fte=ee("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 pte=ee("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 xte=ee("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 gte=ee("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 lm=ee("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=ee("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 yte=ee("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 vte=ee("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 bte=ee("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 _te=ee("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 lM=ee("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 qS=ee("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 wte=ee("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 VS=ee("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kc=ee("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 P3=ee("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 cM=ee("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 jte=ee("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 Nte=ee("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 kte=ee("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 Ste=ee("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 Cte=ee("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 Tte=ee("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 mO=ee("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 fO=ee("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 Ete=ee("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 Ate=ee("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 Mte=ee("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 dM=ee("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 Qs=ee("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 Ite=ee("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 Pte=ee("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 Lte=ee("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 Dte=ee("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 Rte=ee("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 Ote=ee("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 Fte=ee("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 Bte=ee("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 zte=ee("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 $te=ee("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 Ute=ee("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 qte=ee("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 ja=ee("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 Vte=ee("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 L3=ee("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 Hte=ee("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 Gte=ee("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 pO=ee("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 s_=ee("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 Wte=ee("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 Cu=ee("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 Kte=ee("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 Yte=ee("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 D3=ee("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 Zte=ee("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 Xte=ee("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 Qte=ee("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 uM=ee("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 Jte=ee("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 ese=ee("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 tse=ee("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 xO=ee("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 sse=ee("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 rse=ee("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 nse=ee("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 tc=ee("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 ase=ee("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 ise=ee("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 ose=ee("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 lse=ee("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 cse=ee("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 dse=ee("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 gO=ee("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 use=ee("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 Tv=ee("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 yO=ee("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 hse=ee("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 mse=ee("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 fse=ee("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 pse=ee("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 xse=ee("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 bi=ee("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 gse=ee("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 yse=ee("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 HS=ee("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 R3=ee("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 vse=ee("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 bse=ee("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 _se=ee("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 wse=ee("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 jse=ee("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 Nse=ee("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 kse=ee("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 Sse=ee("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 qv=ee("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 Cse=ee("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 Tse=ee("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 Ese=ee("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 Ase=ee("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 Mse=ee("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 Ise=ee("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 vO=ee("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 Pse=ee("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 Lse=ee("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 Dse=ee("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 O3=ee("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 Rse=ee("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 Zj=ee("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 Ose=ee("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 Fse=ee("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 Bse=ee("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 zse=ee("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 $se=ee("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 Use=ee("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 qse=ee("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 Dd=ee("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 tm=ee("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 Vse=ee("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 GS=ee("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 Hse=ee("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 Gse=ee("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 Wse=ee("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 Kse=ee("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 Yse=ee("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 Zse=ee("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 Xse=ee("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 Qse=ee("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 Jse=ee("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 ere=ee("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 tre=ee("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 sre=ee("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 rre=ee("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 nre=ee("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 are=ee("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 ire=ee("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 ore=ee("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 lre=ee("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 cre=ee("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 dre=ee("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 bO=ee("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 ure=ee("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 Vv=ee("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 hre=ee("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 mre=ee("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 fre=ee("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 pre=ee("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 xre=ee("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 gre=ee("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 yre=ee("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 vre=ee("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 bre=ee("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 Ib=ee("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 _re=ee("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 WS=ee("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 KS=ee("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 wre=ee("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 jre=ee("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 Nre=ee("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 kre=ee("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 Sre=ee("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 Cre=ee("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 Tre=ee("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 Ere=ee("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 Are=ee("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 Mre=ee("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 Ire=ee("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 Pre=ee("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 Pl=ee("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 Lre=ee("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 Dre=ee("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 YS=ee("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 Rre=ee("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pl=ee("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 Ore=ee("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 ZS=ee("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 Fre=ee("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 Bre=ee("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 XS=ee("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 QS=ee("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 JS=ee("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 eC=ee("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 zre=ee("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 tC=ee("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 $re=ee("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 Ure=ee("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 qre=ee("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 sC=ee("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 Vre=ee("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 Hre=ee("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 Gre=ee("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 Wre=ee("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 Pb=ee("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 Xj=ee("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 Kre=ee("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 Yre=ee("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 iu=ee("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 cm=ee("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 Zre=ee("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 Xre=ee("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 vv=ee("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 Qre=ee("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 Qj=ee("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 bv=ee("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 Jre=ee("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 ene=ee("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 tne=ee("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 Ta=ee("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 sne=ee("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 F3=ee("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 rne=ee("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 nne=ee("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 ane=ee("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 ine=ee("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 one=ee("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 lne=ee("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 cne=ee("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 dne=ee("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 Nn=ee("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 une=ee("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 hne=ee("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 mne=ee("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 fne=ee("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 pne=ee("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 xne=ee("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 gne=ee("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 yne=ee("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 vne=ee("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 bne=ee("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 _ne=ee("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 _O=ee("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 Jj=ee("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 wne=ee("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 jne=ee("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 Nne=ee("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 kne=ee("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 wO=ee("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 Ho=ee("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 Sne=ee("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 rC=ee("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 B3=ee("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 Ws=ee("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 Cne=ee("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 Tne=ee("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 Ene=ee("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 Ane=ee("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 Mne=ee("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 Ine=ee("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 Pne=ee("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 Lne=ee("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 Dne=ee("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 jO=ee("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 n0=ee("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 Rne=ee("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 NO=ee("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 One=ee("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 Fne=ee("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 Bne=ee("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 zne=ee("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 Hv=ee("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 z3=ee("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 $ne=ee("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 hM=ee("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 Une=ee("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 qne=ee("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 Vne=ee("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 Hne=ee("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 r_=ee("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 Gne=ee("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 Wne=ee("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 Kne=ee("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 Yne=ee("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 Zne=ee("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 Xne=ee("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 Qne=ee("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 Jne=ee("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 eae=ee("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 tae=ee("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 sae=ee("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 rae=ee("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 nae=ee("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 aae=ee("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 nC=ee("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 iae=ee("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 oae=ee("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 lae=ee("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 cae=ee("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 dae=ee("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 e2=ee("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 uae=ee("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 mM=ee("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 hae=ee("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 Di=ee("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 mae=ee("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 fae=ee("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 pae=ee("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 xae=ee("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 gae=ee("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 kO=ee("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 yae=ee("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 vae=ee("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 bae=ee("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 SO=ee("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 _ae=ee("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 wae=ee("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 Gv=ee("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 jae=ee("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 Nae=ee("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 aC=ee("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 kae=ee("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 Wv=ee("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 Sae=ee("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 $3=ee("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 Cae=ee("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 Tae=ee("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 Eae=ee("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 iC=ee("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 oC=ee("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 Aae=ee("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 Mae=ee("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 U3=ee("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 Iae=ee("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 Pae=ee("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 Lae=ee("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 Dae=ee("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 Rae=ee("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 Oae=ee("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 Fae=ee("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 Bae=ee("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 ql=ee("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 lC=ee("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 CO=ee("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 zae=ee("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 $ae=ee("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 Uae=ee("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 qae=ee("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 Vae=ee("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 Hae=ee("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 Gae=ee("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 Wae=ee("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 Kae=ee("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 Yae=ee("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 Zae=ee("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 Xae=ee("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 Qae=ee("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 Jae=ee("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 eie=ee("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 tie=ee("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 sie=ee("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 rie=ee("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 nie=ee("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 TO=ee("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 fn=ee("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 aie=ee("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 cC=ee("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 iie=ee("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 Zr=ee("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 oie=ee("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 lie=ee("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 cie=ee("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 die=ee("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 uie=ee("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 hie=ee("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 EO=ee("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 lo=ee("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 mie=ee("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 Pc=ee("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 AO=ee("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 fie=ee("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 pie=ee("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 MO=ee("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 xie=ee("ShieldBan",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m4.243 5.21 14.39 12.472",key:"1c9a7c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a0=ee("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 gie=ee("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 yie=ee("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 vie=ee("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 q3=ee("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 bie=ee("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 _ie=ee("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 dC=ee("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 Zu=ee("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 wie=ee("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 jie=ee("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 Nie=ee("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 Kv=ee("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 kie=ee("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 lp=ee("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 Sie=ee("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 Cie=ee("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 Tie=ee("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 Eie=ee("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 V3=ee("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 Aie=ee("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 Mie=ee("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 Iie=ee("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 Pie=ee("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 Lie=ee("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 Die=ee("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 Rie=ee("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 Oie=ee("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 Fie=ee("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 Bie=ee("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 zie=ee("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 $ie=ee("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 Uie=ee("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 qie=ee("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 Vie=ee("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 Hie=ee("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 H3=ee("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 uC=ee("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 Gie=ee("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 Wie=ee("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 zg=ee("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 Kie=ee("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 Yie=ee("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 Zie=ee("Snail",[["path",{d:"M2 13a6 6 0 1 0 12 0 4 4 0 1 0-8 0 2 2 0 0 0 4 0",key:"hneq2s"}],["circle",{cx:"10",cy:"13",r:"8",key:"194lz3"}],["path",{d:"M2 21h12c4.4 0 8-3.6 8-8V7a2 2 0 1 0-4 0v6",key:"ixqyt7"}],["path",{d:"M18 3 19.1 5.2",key:"9tjm43"}],["path",{d:"M22 3 20.9 5.2",key:"j3odrs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ev=ee("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 Xie=ee("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 Qie=ee("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 Jie=ee("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 eoe=ee("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 toe=ee("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jr=ee("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 soe=ee("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 roe=ee("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 noe=ee("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 aoe=ee("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 ioe=ee("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 ooe=ee("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 loe=ee("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 G3=ee("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 hC=ee("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 mC=ee("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 fC=ee("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 pC=ee("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 xC=ee("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 gC=ee("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 yC=ee("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 vC=ee("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 bC=ee("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 _C=ee("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 wC=ee("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 jC=ee("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 NC=ee("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 kC=ee("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 SC=ee("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 ov=ee("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 Lb=ee("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 CC=ee("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 TC=ee("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 EC=ee("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 AC=ee("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 MC=ee("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 IC=ee("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 coe=ee("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 doe=ee("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 PC=ee("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 LC=ee("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 DC=ee("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 RC=ee("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 OC=ee("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 FC=ee("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 BC=ee("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 zC=ee("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 $C=ee("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 UC=ee("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 qC=ee("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 VC=ee("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 HC=ee("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 GC=ee("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 WC=ee("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 nd=ee("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 KC=ee("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 YC=ee("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 ZC=ee("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 XC=ee("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 QC=ee("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 JC=ee("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 uoe=ee("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 e4=ee("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 t4=ee("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 s4=ee("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 r4=ee("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 n4=ee("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 hoe=ee("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 moe=ee("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 a4=ee("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 i4=ee("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 o4=ee("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 l4=ee("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 $g=ee("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 foe=ee("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 poe=ee("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 xoe=ee("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 goe=ee("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 yoe=ee("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 Qn=ee("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 voe=ee("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 boe=ee("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 _oe=ee("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 woe=ee("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 joe=ee("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 Noe=ee("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 koe=ee("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 Soe=ee("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 IO=ee("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 Coe=ee("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 Toe=ee("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 Eoe=ee("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 Aoe=ee("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 Moe=ee("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 n_=ee("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 Ioe=ee("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 Poe=ee("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 Loe=ee("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 Doe=ee("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 Roe=ee("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 Ooe=ee("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 Foe=ee("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 Boe=ee("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 zoe=ee("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 fM=ee("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 $oe=ee("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 Uoe=ee("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 qoe=ee("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 Voe=ee("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 Hoe=ee("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 Goe=ee("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 pM=ee("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 Woe=ee("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 Koe=ee("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 Yoe=ee("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 Ah=ee("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 Zoe=ee("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 Xoe=ee("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 Qoe=ee("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 Joe=ee("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 ele=ee("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 tle=ee("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 sle=ee("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 zd=ee("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 rle=ee("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 nle=ee("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 ale=ee("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 ile=ee("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 c4=ee("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 ole=ee("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 lle=ee("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 cle=ee("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 dle=ee("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 ule=ee("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 hle=ee("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 d4=ee("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 mle=ee("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 fle=ee("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 ple=ee("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 xle=ee("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 gle=ee("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 PO=ee("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 Mh=ee("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 yle=ee("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 vle=ee("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 ble=ee("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 _le=ee("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 wle=ee("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 jle=ee("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 LO=ee("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 Nle=ee("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 kle=ee("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 Sle=ee("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 Cle=ee("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 Tle=ee("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 Ele=ee("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 Ale=ee("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 Mle=ee("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 Ile=ee("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 Ple=ee("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 Lle=ee("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 Dle=ee("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 Rle=ee("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 Ole=ee("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 Fle=ee("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 Ble=ee("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 zle=ee("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 $le=ee("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 Ule=ee("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 u4=ee("TramFront",[["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M12 3v8",key:"1h2ygw"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m18 22-2-3",key:"1p0ohu"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yr=ee("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 qle=ee("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 Vle=ee("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 h4=ee("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 t2=ee("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 Hle=ee("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 Gle=ee("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 a_=ee("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 Wle=ee("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 _o=ee("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 od=ee("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 Kle=ee("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 Yle=ee("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 Zi=ee("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 DO=ee("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 Zle=ee("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 Xle=ee("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 m4=ee("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 Qle=ee("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 Jle=ee("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 ece=ee("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 tce=ee("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 sce=ee("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 rce=ee("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 nce=ee("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 xM=ee("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 ace=ee("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 ice=ee("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 s2=ee("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 oce=ee("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 lce=ee("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 cce=ee("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 f4=ee("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 dce=ee("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 W3=ee("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 uce=ee("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 oa=ee("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 hce=ee("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 Yv=ee("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 RO=ee("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 OO=ee("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 mce=ee("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 nl=ee("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 p4=ee("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 x4=ee("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 g4=ee("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 fce=ee("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 y4=ee("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 pce=ee("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 v4=ee("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 b4=ee("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 xce=ee("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 gce=ee("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 Bi=ee("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 _4=ee("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 fr=ee("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 w4=ee("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 j4=ee("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 yce=ee("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 gM=ee("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 vce=ee("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 bce=ee("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 _ce=ee("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 wce=ee("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 jce=ee("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 Nce=ee("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 sn=ee("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 kce=ee("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 Sce=ee("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 Cce=ee("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 Tce=ee("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 Ece=ee("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 FO=ee("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 Ace=ee("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 BO=ee("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 Mce=ee("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 Ice=ee("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 Pce=ee("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 N4=ee("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 zO=ee("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 Lce=ee("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 Ag=ee("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 Dce=ee("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 Rce=ee("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 Oce=ee("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 Fce=ee("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 Bce=ee("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 zce=ee("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 $ce=ee("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 Uce=ee("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 qce=ee("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 Vce=ee("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 Hce=ee("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 Gce=ee("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 Wce=ee("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 Kce=ee("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 Yce=ee("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 Zce=ee("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 Xce=ee("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 Qce=ee("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 Jce=ee("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 ede=ee("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 tde=ee("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 sde=ee("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 $O=ee("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 rde=ee("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 nde=ee("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 i0=ee("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=ee("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 ade=ee("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 ide=ee("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 Xu=ee("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 r2=ee("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 yM=ee("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 v2t=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:zq,AArrowUp:$q,ALargeSmall:Uq,Accessibility:qq,Activity:Ch,AirVent:Vq,Airplay:Hq,AlarmClock:Wq,AlarmClockCheck:gk,AlarmClockMinus:yk,AlarmClockOff:Gq,AlarmClockPlus:vk,AlarmSmoke:Kq,Album:Yq,AlignCenter:g3,AlignCenterHorizontal:Zq,AlignCenterVertical:Xq,AlignEndHorizontal:Qq,AlignEndVertical:Jq,AlignHorizontalDistributeCenter:eV,AlignHorizontalDistributeEnd:tV,AlignHorizontalDistributeStart:sV,AlignHorizontalJustifyCenter:rV,AlignHorizontalJustifyEnd:nV,AlignHorizontalJustifyStart:aV,AlignHorizontalSpaceAround:iV,AlignHorizontalSpaceBetween:oV,AlignJustify:lV,AlignLeft:y3,AlignRight:v3,AlignStartHorizontal:cV,AlignStartVertical:dV,AlignVerticalDistributeCenter:uV,AlignVerticalDistributeEnd:hV,AlignVerticalDistributeStart:mV,AlignVerticalJustifyCenter:fV,AlignVerticalJustifyEnd:pV,AlignVerticalJustifyStart:xV,AlignVerticalSpaceAround:gV,AlignVerticalSpaceBetween:yV,Ambulance:vV,Ampersand:bV,Ampersands:_V,Amphora:wV,Anchor:jV,Angry:NV,Annoyed:kV,Antenna:SV,Anvil:CV,Aperture:TV,AppWindow:VR,AppWindowMac:EV,Apple:AV,Archive:Uj,ArchiveRestore:ZA,ArchiveX:MV,Armchair:IV,ArrowBigDown:LV,ArrowBigDownDash:PV,ArrowBigLeft:RV,ArrowBigLeftDash:DV,ArrowBigRight:FV,ArrowBigRightDash:OV,ArrowBigUp:zV,ArrowBigUpDash:BV,ArrowDown:Ku,ArrowDown01:$V,ArrowDown10:UV,ArrowDownAZ:bk,ArrowDownFromLine:qV,ArrowDownLeft:VV,ArrowDownNarrowWide:HV,ArrowDownRight:HR,ArrowDownToDot:GV,ArrowDownToLine:WV,ArrowDownUp:KV,ArrowDownWideNarrow:_k,ArrowDownZA:wk,ArrowLeft:wa,ArrowLeftFromLine:YV,ArrowLeftRight:ZV,ArrowLeftToLine:XV,ArrowRight:Ga,ArrowRightFromLine:QV,ArrowRightLeft:Xb,ArrowRightToLine:JV,ArrowUp:Fd,ArrowUp01:eH,ArrowUp10:tH,ArrowUpAZ:jk,ArrowUpDown:Rd,ArrowUpFromDot:sH,ArrowUpFromLine:rH,ArrowUpLeft:nH,ArrowUpNarrowWide:Nk,ArrowUpRight:GR,ArrowUpToLine:aH,ArrowUpWideNarrow:iH,ArrowUpZA:kk,ArrowsUpFromLine:oH,Asterisk:lH,AtSign:cH,Atom:dH,AudioLines:uH,AudioWaveform:hH,Award:Xl,Axe:mH,Axis3d:Sk,Baby:fH,Backpack:pH,Badge:MH,BadgeAlert:xH,BadgeCent:gH,BadgeCheck:Ck,BadgeDollarSign:yH,BadgeEuro:vH,BadgeHelp:bH,BadgeIndianRupee:_H,BadgeInfo:wH,BadgeJapaneseYen:jH,BadgeMinus:NH,BadgePercent:kH,BadgePlus:SH,BadgePoundSterling:CH,BadgeRussianRuble:TH,BadgeSwissFranc:EH,BadgeX:AH,BaggageClaim:IH,Ban:WR,Banana:PH,Bandage:LH,Banknote:DH,Barcode:RH,Baseline:OH,Bath:fp,Battery:qH,BatteryCharging:FH,BatteryFull:BH,BatteryLow:zH,BatteryMedium:$H,BatteryWarning:UH,Beaker:VH,Bean:GH,BeanOff:HH,Bed:e0,BedDouble:b3,BedSingle:WH,Beef:KH,Beer:ZH,BeerOff:YH,Bell:Rm,BellDot:XH,BellElectric:QH,BellMinus:JH,BellOff:Fv,BellPlus:eG,BellRing:KR,BetweenHorizontalEnd:Tk,BetweenHorizontalStart:Ek,BetweenVerticalEnd:tG,BetweenVerticalStart:sG,BicepsFlexed:rG,Bike:nG,Binary:aG,Binoculars:iG,Biohazard:oG,Bird:lG,Bitcoin:cG,Blend:dG,Blinds:uG,Blocks:hG,Bluetooth:xG,BluetoothConnected:mG,BluetoothOff:fG,BluetoothSearching:pG,Bold:qj,Bolt:gG,Bomb:yG,Bone:vG,Book:$G,BookA:bG,BookAudio:_G,BookCheck:wG,BookCopy:jG,BookDashed:Ak,BookDown:NG,BookHeadphones:kG,BookHeart:SG,BookImage:CG,BookKey:TG,BookLock:EG,BookMarked:AG,BookMinus:MG,BookOpen:Th,BookOpenCheck:IG,BookOpenText:PG,BookPlus:LG,BookText:DG,BookType:RG,BookUp:FG,BookUp2:OG,BookUser:BG,BookX:zG,Bookmark:Bg,BookmarkCheck:UG,BookmarkMinus:qG,BookmarkPlus:YR,BookmarkX:VG,BoomBox:HG,Bot:XA,BotMessageSquare:GG,BotOff:WG,Box:KG,Boxes:YG,Braces:Mk,Brackets:ZG,Brain:ZR,BrainCircuit:XG,BrainCog:QG,BrickWall:JG,Briefcase:Yu,BriefcaseBusiness:eW,BriefcaseConveyorBelt:tW,BriefcaseMedical:sW,BringToFront:rW,Brush:nW,Bug:oW,BugOff:aW,BugPlay:iW,Building:_3,Building2:Sa,Bus:cW,BusFront:lW,Cable:uW,CableCar:dW,Cake:Eh,CakeSlice:hW,Calculator:QA,Calendar:rn,Calendar1:mW,CalendarArrowDown:fW,CalendarArrowUp:pW,CalendarCheck:XR,CalendarCheck2:xW,CalendarClock:Bv,CalendarCog:gW,CalendarDays:pd,CalendarFold:yW,CalendarHeart:QR,CalendarMinus:bW,CalendarMinus2:vW,CalendarOff:JR,CalendarPlus:Ub,CalendarPlus2:_W,CalendarRange:wW,CalendarSearch:jW,CalendarSync:NW,CalendarX:SW,CalendarX2:kW,Camera:pp,CameraOff:CW,Candy:AW,CandyCane:TW,CandyOff:EW,Cannabis:MW,Captions:Ik,CaptionsOff:IW,Car:DW,CarFront:PW,CarTaxiFront:LW,Caravan:RW,Carrot:OW,CaseLower:FW,CaseSensitive:BW,CaseUpper:zW,CassetteTape:$W,Cast:UW,Castle:qW,Cat:VW,Cctv:HW,ChartArea:Pk,ChartBar:Dk,ChartBarBig:Lk,ChartBarDecreasing:GW,ChartBarIncreasing:WW,ChartBarStacked:KW,ChartCandlestick:Rk,ChartColumn:ao,ChartColumnBig:Ok,ChartColumnDecreasing:YW,ChartColumnIncreasing:Fk,ChartColumnStacked:ZW,ChartGantt:XW,ChartLine:Bk,ChartNetwork:QW,ChartNoAxesColumn:$k,ChartNoAxesColumnDecreasing:JW,ChartNoAxesColumnIncreasing:zk,ChartNoAxesCombined:eK,ChartNoAxesGantt:Uk,ChartPie:qk,ChartScatter:Vk,ChartSpline:tK,Check:Hn,CheckCheck:eO,ChefHat:sK,Cherry:rK,ChevronDown:so,ChevronFirst:nK,ChevronLast:aK,ChevronLeft:Vo,ChevronRight:ya,ChevronUp:xp,ChevronsDown:oK,ChevronsDownUp:iK,ChevronsLeft:dK,ChevronsLeftRight:cK,ChevronsLeftRightEllipsis:lK,ChevronsRight:hK,ChevronsRightLeft:uK,ChevronsUp:mK,ChevronsUpDown:xx,Chrome:w3,Church:fK,Cigarette:xK,CigaretteOff:pK,Circle:Bd,CircleAlert:Hi,CircleArrowDown:Hk,CircleArrowLeft:Gk,CircleArrowOutDownLeft:Wk,CircleArrowOutDownRight:Kk,CircleArrowOutUpLeft:Yk,CircleArrowOutUpRight:Zk,CircleArrowRight:Xk,CircleArrowUp:Qk,CircleCheck:Mn,CircleCheckBig:mi,CircleChevronDown:Jk,CircleChevronLeft:eS,CircleChevronRight:tS,CircleChevronUp:sS,CircleDashed:gK,CircleDivide:rS,CircleDollarSign:yK,CircleDot:bK,CircleDotDashed:vK,CircleEllipsis:_K,CircleEqual:wK,CircleFadingArrowUp:jK,CircleFadingPlus:NK,CircleGauge:nS,CircleHelp:Ab,CircleMinus:aS,CircleOff:kK,CircleParking:oS,CircleParkingOff:iS,CirclePause:lS,CirclePercent:cS,CirclePlay:mf,CirclePlus:dS,CirclePower:uS,CircleSlash:SK,CircleSlash2:hS,CircleStop:mS,CircleUser:pS,CircleUserRound:fS,CircleX:Mc,CircuitBoard:CK,Citrus:TK,Clapperboard:EK,Clipboard:RK,ClipboardCheck:JA,ClipboardCopy:AK,ClipboardList:Vj,ClipboardMinus:MK,ClipboardPaste:IK,ClipboardPen:gS,ClipboardPenLine:xS,ClipboardPlus:PK,ClipboardType:LK,ClipboardX:DK,Clock:cn,Clock1:OK,Clock10:FK,Clock11:BK,Clock12:zK,Clock2:$K,Clock3:UK,Clock4:qK,Clock5:VK,Clock6:HK,Clock7:GK,Clock8:WK,Clock9:KK,ClockAlert:YK,ClockArrowDown:ZK,ClockArrowUp:XK,Cloud:hY,CloudAlert:QK,CloudCog:JK,CloudDownload:yS,CloudDrizzle:eY,CloudFog:tY,CloudHail:sY,CloudLightning:rY,CloudMoon:aY,CloudMoonRain:nY,CloudOff:iY,CloudRain:lY,CloudRainWind:oY,CloudSnow:cY,CloudSun:uY,CloudSunRain:dY,CloudUpload:vS,Cloudy:mY,Clover:qb,Club:fY,Code:j3,CodeXml:Mb,Codepen:pY,Codesandbox:xY,Coffee:N3,Cog:gY,Coins:tO,Columns2:bS,Columns3:_S,Columns4:yY,Combine:vY,Command:bY,Compass:eM,Component:_Y,Computer:wY,ConciergeBell:jY,Cone:NY,Construction:kY,Contact:k3,ContactRound:wS,Container:SY,Contrast:CY,Cookie:TY,CookingPot:EY,Copy:Ra,CopyCheck:AY,CopyMinus:MY,CopyPlus:IY,CopySlash:PY,CopyX:LY,Copyleft:DY,Copyright:RY,CornerDownLeft:OY,CornerDownRight:FY,CornerLeftDown:BY,CornerLeftUp:zY,CornerRightDown:$Y,CornerRightUp:UY,CornerUpLeft:qY,CornerUpRight:VY,Cpu:HY,CreativeCommons:GY,CreditCard:gx,Croissant:WY,Crop:KY,Cross:YY,Crosshair:ZY,Crown:nm,Cuboid:XY,CupSoda:QY,Currency:JY,Cylinder:eZ,Dam:tZ,Database:sO,DatabaseBackup:sZ,DatabaseZap:rZ,Delete:nZ,Dessert:aZ,Diameter:iZ,Diamond:cZ,DiamondMinus:oZ,DiamondPercent:jS,DiamondPlus:lZ,Dice1:dZ,Dice2:uZ,Dice3:hZ,Dice4:mZ,Dice5:fZ,Dice6:pZ,Dices:xZ,Diff:gZ,Disc:_Z,Disc2:yZ,Disc3:vZ,DiscAlbum:bZ,Divide:wZ,Dna:NZ,DnaOff:jZ,Dock:kZ,Dog:SZ,DollarSign:_l,Donut:CZ,DoorClosed:TZ,DoorOpen:zv,Dot:EZ,Download:Xa,DraftingCompass:AZ,Drama:MZ,Dribbble:IZ,Drill:PZ,Droplet:LZ,Droplets:t0,Drum:DZ,Drumstick:RZ,Dumbbell:OZ,Ear:BZ,EarOff:FZ,Earth:NS,EarthLock:zZ,Eclipse:$Z,Egg:tM,EggFried:UZ,EggOff:qZ,Ellipsis:ix,EllipsisVertical:Eg,Equal:GZ,EqualApproximately:VZ,EqualNot:HZ,Eraser:WZ,EthernetPort:KZ,Euro:YZ,Expand:ZZ,ExternalLink:Yr,Eye:jn,EyeClosed:XZ,EyeOff:am,Facebook:ku,Factory:QZ,Fan:JZ,FastForward:eX,Feather:tX,Fence:sX,FerrisWheel:rX,Figma:nX,File:sM,FileArchive:aX,FileAudio:oX,FileAudio2:iX,FileAxis3d:kS,FileBadge:cX,FileBadge2:lX,FileBox:dX,FileChartColumn:CS,FileChartColumnIncreasing:SS,FileChartLine:TS,FileChartPie:ES,FileCheck:rO,FileCheck2:uX,FileClock:hX,FileCode:fX,FileCode2:mX,FileCog:AS,FileDiff:pX,FileDigit:xX,FileDown:S3,FileHeart:gX,FileImage:Qb,FileInput:yX,FileJson:bX,FileJson2:vX,FileKey:wX,FileKey2:_X,FileLock:NX,FileLock2:jX,FileMinus:SX,FileMinus2:kX,FileMusic:CX,FileOutput:TX,FilePen:IS,FilePenLine:MS,FilePlus:AX,FilePlus2:EX,FileQuestion:MX,FileScan:IX,FileSearch:LX,FileSearch2:PX,FileSliders:DX,FileSpreadsheet:Jb,FileStack:nO,FileSymlink:RX,FileTerminal:OX,FileText:ln,FileType:BX,FileType2:FX,FileUp:zX,FileUser:$X,FileVideo:aO,FileVideo2:UX,FileVolume:VX,FileVolume2:qX,FileWarning:HX,FileX:WX,FileX2:GX,Files:KX,Film:Nh,Filter:s0,FilterX:YX,Fingerprint:ZX,FireExtinguisher:XX,Fish:eQ,FishOff:QX,FishSymbol:JX,Flag:e_,FlagOff:tQ,FlagTriangleLeft:sQ,FlagTriangleRight:rQ,Flame:xc,FlameKindling:nQ,Flashlight:iQ,FlashlightOff:aQ,FlaskConical:Hj,FlaskConicalOff:oQ,FlaskRound:lQ,FlipHorizontal:iO,FlipHorizontal2:cQ,FlipVertical:uQ,FlipVertical2:dQ,Flower:hQ,Flower2:Yy,Focus:mQ,FoldHorizontal:fQ,FoldVertical:pQ,Folder:UQ,FolderArchive:xQ,FolderCheck:gQ,FolderClock:yQ,FolderClosed:vQ,FolderCode:bQ,FolderCog:PS,FolderDot:_Q,FolderDown:wQ,FolderGit:NQ,FolderGit2:jQ,FolderHeart:kQ,FolderInput:SQ,FolderKanban:CQ,FolderKey:TQ,FolderLock:EQ,FolderMinus:AQ,FolderOpen:im,FolderOpenDot:MQ,FolderOutput:IQ,FolderPen:LS,FolderPlus:PQ,FolderRoot:LQ,FolderSearch:RQ,FolderSearch2:DQ,FolderSymlink:OQ,FolderSync:FQ,FolderTree:BQ,FolderUp:zQ,FolderX:$Q,Folders:qQ,Footprints:VQ,Forklift:HQ,Forward:GQ,Frame:WQ,Framer:KQ,Frown:YQ,Fuel:ZQ,Fullscreen:XQ,GalleryHorizontal:JQ,GalleryHorizontalEnd:QQ,GalleryThumbnails:eJ,GalleryVertical:sJ,GalleryVerticalEnd:tJ,Gamepad:nJ,Gamepad2:rJ,Gauge:aJ,Gavel:iJ,Gem:oJ,Ghost:C3,Gift:li,GitBranch:cJ,GitBranchPlus:lJ,GitCommitHorizontal:DS,GitCommitVertical:dJ,GitCompare:hJ,GitCompareArrows:uJ,GitFork:mJ,GitGraph:fJ,GitMerge:pJ,GitPullRequest:_J,GitPullRequestArrow:xJ,GitPullRequestClosed:gJ,GitPullRequestCreate:vJ,GitPullRequestCreateArrow:yJ,GitPullRequestDraft:bJ,Github:wJ,Gitlab:jJ,GlassWater:NJ,Glasses:kJ,Globe:gc,GlobeLock:SJ,Goal:CJ,Grab:TJ,GraduationCap:Od,Grape:EJ,Grid2x2:OS,Grid2x2Check:AJ,Grid2x2Plus:RS,Grid2x2X:MJ,Grid3x3:bg,Grip:PJ,GripHorizontal:IJ,GripVertical:Su,Group:LJ,Guitar:DJ,Ham:RJ,Hammer:oO,Hand:lO,HandCoins:OJ,HandHeart:FJ,HandHelping:Hy,HandMetal:BJ,HandPlatter:zJ,Handshake:Gj,HardDrive:cO,HardDriveDownload:$J,HardDriveUpload:UJ,HardHat:qJ,Hash:Wj,Haze:VJ,HdmiPort:HJ,Heading:YJ,Heading1:rM,Heading2:nM,Heading3:dO,Heading4:GJ,Heading5:WJ,Heading6:KJ,HeadphoneOff:ZJ,Headphones:XJ,Headset:QJ,Heart:hi,HeartCrack:JJ,HeartHandshake:eee,HeartOff:tee,HeartPulse:see,Heater:ree,Hexagon:nee,Highlighter:aee,History:aM,Hop:oee,HopOff:iee,Hospital:lee,Hotel:cee,Hourglass:dee,House:Cn,HousePlug:uee,HousePlus:hee,IceCreamBowl:FS,IceCreamCone:BS,IdCard:mee,Image:fl,ImageDown:fee,ImageMinus:pee,ImageOff:xee,ImagePlay:gee,ImagePlus:$v,ImageUp:yee,ImageUpscale:vee,Images:bee,Import:_ee,Inbox:iM,IndentDecrease:zS,IndentIncrease:$S,IndianRupee:wee,Infinity:jee,Info:T3,InspectionPanel:Nee,Instagram:au,Italic:Kj,IterationCcw:kee,IterationCw:See,JapaneseYen:Cee,Joystick:Tee,Kanban:Uv,Key:gp,KeyRound:E3,KeySquare:Eee,Keyboard:Iee,KeyboardMusic:Aee,KeyboardOff:Mee,Lamp:Fee,LampCeiling:Pee,LampDesk:Lee,LampFloor:Dee,LampWallDown:Ree,LampWallUp:Oee,LandPlot:Bee,Landmark:zee,Languages:$ee,Laptop:qee,LaptopMinimal:US,LaptopMinimalCheck:Uee,Lasso:Hee,LassoSelect:Vee,Laugh:Gee,Layers:uO,Layers2:Wee,Layers3:Kee,LayoutDashboard:A3,LayoutGrid:Sf,LayoutList:Yee,LayoutPanelLeft:Zee,LayoutPanelTop:Xee,LayoutTemplate:M3,Leaf:Qee,LeafyGreen:Jee,Lectern:ete,LetterText:tte,Library:I3,LibraryBig:ste,LifeBuoy:oM,Ligature:rte,Lightbulb:Yj,LightbulbOff:nte,Link:xo,Link2:rl,Link2Off:ate,Linkedin:om,List:lm,ListCheck:ite,ListChecks:t_,ListCollapse:ote,ListEnd:lte,ListFilter:hO,ListMinus:cte,ListMusic:dte,ListOrdered:r0,ListPlus:ute,ListRestart:hte,ListStart:mte,ListTodo:fte,ListTree:pte,ListVideo:xte,ListX:gte,Loader:vte,LoaderCircle:ls,LoaderPinwheel:yte,Locate:lM,LocateFixed:bte,LocateOff:_te,Lock:Kc,LockKeyhole:wte,LockKeyholeOpen:qS,LockOpen:VS,LogIn:P3,LogOut:cM,Logs:jte,Lollipop:Nte,Luggage:kte,Magnet:Ste,Mail:Qs,MailCheck:Cte,MailMinus:Tte,MailOpen:mO,MailPlus:fO,MailQuestion:Ete,MailSearch:Ate,MailWarning:Mte,MailX:dM,Mailbox:Ite,Mails:Pte,Map:L3,MapPin:ja,MapPinCheck:Dte,MapPinCheckInside:Lte,MapPinHouse:Rte,MapPinMinus:Fte,MapPinMinusInside:Ote,MapPinOff:Bte,MapPinPlus:$te,MapPinPlusInside:zte,MapPinX:qte,MapPinXInside:Ute,MapPinned:Vte,Martini:Hte,Maximize:pO,Maximize2:Gte,Medal:s_,Megaphone:Cu,MegaphoneOff:Wte,Meh:Kte,MemoryStick:Yte,Menu:D3,Merge:Zte,MessageCircle:tc,MessageCircleCode:Xte,MessageCircleDashed:Qte,MessageCircleHeart:uM,MessageCircleMore:Jte,MessageCircleOff:ese,MessageCirclePlus:tse,MessageCircleQuestion:xO,MessageCircleReply:sse,MessageCircleWarning:rse,MessageCircleX:nse,MessageSquare:bi,MessageSquareCode:ase,MessageSquareDashed:ise,MessageSquareDiff:ose,MessageSquareDot:lse,MessageSquareHeart:cse,MessageSquareLock:dse,MessageSquareMore:gO,MessageSquareOff:use,MessageSquarePlus:Tv,MessageSquareQuote:yO,MessageSquareReply:hse,MessageSquareShare:mse,MessageSquareText:fse,MessageSquareWarning:pse,MessageSquareX:xse,MessagesSquare:gse,Mic:R3,MicOff:yse,MicVocal:HS,Microchip:vse,Microscope:bse,Microwave:_se,Milestone:wse,Milk:Nse,MilkOff:jse,Minimize:Sse,Minimize2:kse,Minus:qv,Monitor:Zj,MonitorCheck:Cse,MonitorCog:Tse,MonitorDot:Ese,MonitorDown:Ase,MonitorOff:Mse,MonitorPause:Ise,MonitorPlay:vO,MonitorSmartphone:Pse,MonitorSpeaker:Lse,MonitorStop:Dse,MonitorUp:O3,MonitorX:Rse,Moon:Fse,MoonStar:Ose,Mountain:zse,MountainSnow:Bse,Mouse:Vse,MouseOff:$se,MousePointer:tm,MousePointer2:Use,MousePointerBan:qse,MousePointerClick:Dd,Move:rre,Move3d:GS,MoveDiagonal:Gse,MoveDiagonal2:Hse,MoveDown:Yse,MoveDownLeft:Wse,MoveDownRight:Kse,MoveHorizontal:Zse,MoveLeft:Xse,MoveRight:Qse,MoveUp:tre,MoveUpLeft:Jse,MoveUpRight:ere,MoveVertical:sre,Music:ore,Music2:nre,Music3:are,Music4:ire,Navigation:bO,Navigation2:cre,Navigation2Off:lre,NavigationOff:dre,Network:ure,Newspaper:Vv,Nfc:hre,Notebook:xre,NotebookPen:mre,NotebookTabs:fre,NotebookText:pre,NotepadText:yre,NotepadTextDashed:gre,Nut:bre,NutOff:vre,Octagon:wre,OctagonAlert:Ib,OctagonMinus:_re,OctagonPause:WS,OctagonX:KS,Omega:jre,Option:Nre,Orbit:kre,Origami:Sre,Package:Pl,Package2:Cre,PackageCheck:Tre,PackageMinus:Ere,PackageOpen:Are,PackagePlus:Mre,PackageSearch:Ire,PackageX:Pre,PaintBucket:Lre,PaintRoller:Dre,Paintbrush:Rre,PaintbrushVertical:YS,Palette:pl,PanelBottom:Bre,PanelBottomClose:Ore,PanelBottomDashed:ZS,PanelBottomOpen:Fre,PanelLeft:eC,PanelLeftClose:XS,PanelLeftDashed:QS,PanelLeftOpen:JS,PanelRight:Ure,PanelRightClose:zre,PanelRightDashed:tC,PanelRightOpen:$re,PanelTop:Hre,PanelTopClose:qre,PanelTopDashed:sC,PanelTopOpen:Vre,PanelsLeftBottom:Gre,PanelsRightBottom:Wre,PanelsTopLeft:Pb,Paperclip:Xj,Parentheses:Kre,ParkingMeter:Yre,PartyPopper:iu,Pause:cm,PawPrint:Zre,PcCase:Xre,Pen:bv,PenLine:vv,PenOff:Qre,PenTool:Qj,Pencil:Ta,PencilLine:Jre,PencilOff:ene,PencilRuler:tne,Pentagon:sne,Percent:F3,PersonStanding:rne,PhilippinePeso:nne,Phone:Nn,PhoneCall:ane,PhoneForwarded:ine,PhoneIncoming:one,PhoneMissed:lne,PhoneOff:cne,PhoneOutgoing:dne,Pi:une,Piano:hne,Pickaxe:mne,PictureInPicture:pne,PictureInPicture2:fne,PiggyBank:xne,Pilcrow:vne,PilcrowLeft:gne,PilcrowRight:yne,Pill:_ne,PillBottle:bne,Pin:Jj,PinOff:_O,Pipette:wne,Pizza:jne,Plane:wO,PlaneLanding:Nne,PlaneTakeoff:kne,Play:Ho,Plug:B3,Plug2:Sne,PlugZap:rC,Plus:Ws,Pocket:Tne,PocketKnife:Cne,Podcast:Ene,Pointer:Mne,PointerOff:Ane,Popcorn:Ine,Popsicle:Pne,PoundSterling:Lne,Power:jO,PowerOff:Dne,Presentation:n0,Printer:NO,PrinterCheck:Rne,Projector:One,Proportions:Fne,Puzzle:Bne,Pyramid:zne,QrCode:Hv,Quote:z3,Rabbit:$ne,Radar:hM,Radiation:Une,Radical:qne,Radio:r_,RadioReceiver:Vne,RadioTower:Hne,Radius:Gne,RailSymbol:Wne,Rainbow:Kne,Rat:Yne,Ratio:Zne,Receipt:aae,ReceiptCent:Xne,ReceiptEuro:Qne,ReceiptIndianRupee:Jne,ReceiptJapaneseYen:eae,ReceiptPoundSterling:tae,ReceiptRussianRuble:sae,ReceiptSwissFranc:rae,ReceiptText:nae,RectangleEllipsis:nC,RectangleHorizontal:iae,RectangleVertical:oae,Recycle:lae,Redo:e2,Redo2:cae,RedoDot:dae,RefreshCcw:mM,RefreshCcwDot:uae,RefreshCw:Di,RefreshCwOff:hae,Refrigerator:mae,Regex:fae,RemoveFormatting:pae,Repeat:kO,Repeat1:xae,Repeat2:gae,Replace:vae,ReplaceAll:yae,Reply:SO,ReplyAll:bae,Rewind:_ae,Ribbon:wae,Rocket:Gv,RockingChair:jae,RollerCoaster:Nae,Rotate3d:aC,RotateCcw:Wv,RotateCcwSquare:kae,RotateCw:$3,RotateCwSquare:Sae,Route:Tae,RouteOff:Cae,Router:Eae,Rows2:iC,Rows3:oC,Rows4:Aae,Rss:Mae,Ruler:U3,RussianRuble:Iae,Sailboat:Pae,Salad:Lae,Sandwich:Dae,Satellite:Oae,SatelliteDish:Rae,Save:ql,SaveAll:Fae,SaveOff:Bae,Scale:CO,Scale3d:lC,Scaling:zae,Scan:Kae,ScanBarcode:$ae,ScanEye:Uae,ScanFace:qae,ScanLine:Vae,ScanQrCode:Hae,ScanSearch:Gae,ScanText:Wae,School:Yae,Scissors:Xae,ScissorsLineDashed:Zae,ScreenShare:Jae,ScreenShareOff:Qae,Scroll:tie,ScrollText:eie,Search:fn,SearchCheck:sie,SearchCode:rie,SearchSlash:nie,SearchX:TO,Section:aie,Send:Zr,SendHorizontal:cC,SendToBack:iie,SeparatorHorizontal:oie,SeparatorVertical:lie,Server:hie,ServerCog:cie,ServerCrash:die,ServerOff:uie,Settings:lo,Settings2:EO,Shapes:mie,Share:AO,Share2:Pc,Sheet:fie,Shell:pie,Shield:Zu,ShieldAlert:MO,ShieldBan:xie,ShieldCheck:a0,ShieldEllipsis:gie,ShieldHalf:yie,ShieldMinus:vie,ShieldOff:q3,ShieldPlus:bie,ShieldQuestion:_ie,ShieldX:dC,Ship:jie,ShipWheel:wie,Shirt:Nie,ShoppingBag:Kv,ShoppingBasket:kie,ShoppingCart:lp,Shovel:Sie,ShowerHead:Cie,Shrink:Tie,Shrub:Eie,Shuffle:V3,Sigma:Aie,Signal:Die,SignalHigh:Mie,SignalLow:Iie,SignalMedium:Pie,SignalZero:Lie,Signature:Rie,Signpost:Fie,SignpostBig:Oie,Siren:Bie,SkipBack:zie,SkipForward:$ie,Skull:Uie,Slack:qie,Slash:Vie,Slice:Hie,SlidersHorizontal:H3,SlidersVertical:uC,Smartphone:zg,SmartphoneCharging:Gie,SmartphoneNfc:Wie,Smile:Yie,SmilePlus:Kie,Snail:Zie,Snowflake:Ev,Sofa:Xie,Soup:Qie,Space:Jie,Spade:eoe,Sparkle:toe,Sparkles:jr,Speaker:soe,Speech:roe,SpellCheck:aoe,SpellCheck2:noe,Spline:ioe,Split:ooe,SprayCan:loe,Sprout:G3,Square:$g,SquareActivity:hC,SquareArrowDown:pC,SquareArrowDownLeft:mC,SquareArrowDownRight:fC,SquareArrowLeft:xC,SquareArrowOutDownLeft:gC,SquareArrowOutDownRight:yC,SquareArrowOutUpLeft:vC,SquareArrowOutUpRight:bC,SquareArrowRight:_C,SquareArrowUp:NC,SquareArrowUpLeft:wC,SquareArrowUpRight:jC,SquareAsterisk:kC,SquareBottomDashedScissors:SC,SquareChartGantt:ov,SquareCheck:CC,SquareCheckBig:Lb,SquareChevronDown:TC,SquareChevronLeft:EC,SquareChevronRight:AC,SquareChevronUp:MC,SquareCode:IC,SquareDashed:DC,SquareDashedBottom:doe,SquareDashedBottomCode:coe,SquareDashedKanban:PC,SquareDashedMousePointer:LC,SquareDivide:RC,SquareDot:OC,SquareEqual:FC,SquareFunction:BC,SquareKanban:zC,SquareLibrary:$C,SquareM:UC,SquareMenu:qC,SquareMinus:VC,SquareMousePointer:HC,SquareParking:WC,SquareParkingOff:GC,SquarePen:nd,SquarePercent:KC,SquarePi:YC,SquarePilcrow:ZC,SquarePlay:XC,SquarePlus:QC,SquarePower:JC,SquareRadical:uoe,SquareScissors:e4,SquareSigma:t4,SquareSlash:s4,SquareSplitHorizontal:r4,SquareSplitVertical:n4,SquareSquare:hoe,SquareStack:moe,SquareTerminal:a4,SquareUser:o4,SquareUserRound:i4,SquareX:l4,Squircle:foe,Squirrel:poe,Stamp:xoe,Star:Qn,StarHalf:goe,StarOff:yoe,StepBack:voe,StepForward:boe,Stethoscope:_oe,Sticker:woe,StickyNote:joe,Store:Noe,StretchHorizontal:koe,StretchVertical:Soe,Strikethrough:IO,Subscript:Coe,Sun:n_,SunDim:Toe,SunMedium:Eoe,SunMoon:Aoe,SunSnow:Moe,Sunrise:Ioe,Sunset:Poe,Superscript:Loe,SwatchBook:Doe,SwissFranc:Roe,SwitchCamera:Ooe,Sword:Foe,Swords:Boe,Syringe:zoe,Table:pM,Table2:fM,TableCellsMerge:$oe,TableCellsSplit:Uoe,TableColumnsSplit:qoe,TableOfContents:Voe,TableProperties:Hoe,TableRowsSplit:Goe,Tablet:Koe,TabletSmartphone:Woe,Tablets:Yoe,Tag:Ah,Tags:Zoe,Tally1:Xoe,Tally2:Qoe,Tally3:Joe,Tally4:ele,Tally5:tle,Tangent:sle,Target:zd,Telescope:rle,Tent:ale,TentTree:nle,Terminal:ile,TestTube:ole,TestTubeDiagonal:c4,TestTubes:lle,Text:mle,TextCursor:dle,TextCursorInput:cle,TextQuote:ule,TextSearch:hle,TextSelect:d4,Theater:fle,Thermometer:gle,ThermometerSnowflake:ple,ThermometerSun:xle,ThumbsDown:PO,ThumbsUp:Mh,Ticket:LO,TicketCheck:yle,TicketMinus:vle,TicketPercent:ble,TicketPlus:_le,TicketSlash:wle,TicketX:jle,Tickets:kle,TicketsPlane:Nle,Timer:Tle,TimerOff:Sle,TimerReset:Cle,ToggleLeft:Ele,ToggleRight:Ale,Toilet:Mle,Tornado:Ile,Torus:Ple,Touchpad:Dle,TouchpadOff:Lle,TowerControl:Rle,ToyBrick:Ole,Tractor:Fle,TrafficCone:Ble,TrainFront:$le,TrainFrontTunnel:zle,TrainTrack:Ule,TramFront:u4,Trash:qle,Trash2:yr,TreeDeciduous:Vle,TreePalm:h4,TreePine:t2,Trees:Hle,Trello:Gle,TrendingDown:a_,TrendingUp:_o,TrendingUpDown:Wle,Triangle:Yle,TriangleAlert:od,TriangleRight:Kle,Trophy:Zi,Truck:DO,Turtle:Zle,Tv:Qle,TvMinimal:m4,TvMinimalPlay:Xle,Twitch:Jle,Twitter:ece,Type:sce,TypeOutline:tce,Umbrella:nce,UmbrellaOff:rce,Underline:xM,Undo:s2,Undo2:ace,UndoDot:ice,UnfoldHorizontal:oce,UnfoldVertical:lce,Ungroup:cce,University:f4,Unlink:W3,Unlink2:dce,Unplug:uce,Upload:oa,Usb:hce,User:Bi,UserCheck:Yv,UserCog:RO,UserMinus:OO,UserPen:mce,UserPlus:nl,UserRound:b4,UserRoundCheck:p4,UserRoundCog:x4,UserRoundMinus:g4,UserRoundPen:fce,UserRoundPlus:y4,UserRoundSearch:pce,UserRoundX:v4,UserSearch:xce,UserX:gce,Users:fr,UsersRound:_4,Utensils:j4,UtensilsCrossed:w4,UtilityPole:yce,Variable:gM,Vault:vce,Vegan:bce,VenetianMask:_ce,Vibrate:jce,VibrateOff:wce,Video:sn,VideoOff:Nce,Videotape:kce,View:Sce,Voicemail:Cce,Volleyball:Tce,Volume:Mce,Volume1:Ece,Volume2:FO,VolumeOff:Ace,VolumeX:BO,Vote:Ice,Wallet:zO,WalletCards:Pce,WalletMinimal:N4,Wallpaper:Lce,Wand:Dce,WandSparkles:Ag,Warehouse:Rce,WashingMachine:Oce,Watch:Fce,Waves:Bce,Waypoints:zce,Webcam:$ce,Webhook:qce,WebhookOff:Uce,Weight:Vce,Wheat:Gce,WheatOff:Hce,WholeWord:Wce,Wifi:Qce,WifiHigh:Kce,WifiLow:Yce,WifiOff:Zce,WifiZero:Xce,Wind:ede,WindArrowDown:Jce,Wine:sde,WineOff:tde,Workflow:$O,Worm:rde,WrapText:nde,Wrench:i0,X:_r,Youtube:ade,Zap:Xu,ZapOff:ide,ZoomIn:r2,ZoomOut:yM},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 Vfe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:zq,AArrowDownIcon:zq,AArrowUp:$q,AArrowUpIcon:$q,ALargeSmall:Uq,ALargeSmallIcon:Uq,Accessibility:qq,AccessibilityIcon:qq,Activity:Ch,ActivityIcon:Ch,ActivitySquare:hC,ActivitySquareIcon:hC,AirVent:Vq,AirVentIcon:Vq,Airplay:Hq,AirplayIcon:Hq,AlarmCheck:gk,AlarmCheckIcon:gk,AlarmClock:Wq,AlarmClockCheck:gk,AlarmClockCheckIcon:gk,AlarmClockIcon:Wq,AlarmClockMinus:yk,AlarmClockMinusIcon:yk,AlarmClockOff:Gq,AlarmClockOffIcon:Gq,AlarmClockPlus:vk,AlarmClockPlusIcon:vk,AlarmMinus:yk,AlarmMinusIcon:yk,AlarmPlus:vk,AlarmPlusIcon:vk,AlarmSmoke:Kq,AlarmSmokeIcon:Kq,Album:Yq,AlbumIcon:Yq,AlertCircle:Hi,AlertCircleIcon:Hi,AlertOctagon:Ib,AlertOctagonIcon:Ib,AlertTriangle:od,AlertTriangleIcon:od,AlignCenter:g3,AlignCenterHorizontal:Zq,AlignCenterHorizontalIcon:Zq,AlignCenterIcon:g3,AlignCenterVertical:Xq,AlignCenterVerticalIcon:Xq,AlignEndHorizontal:Qq,AlignEndHorizontalIcon:Qq,AlignEndVertical:Jq,AlignEndVerticalIcon:Jq,AlignHorizontalDistributeCenter:eV,AlignHorizontalDistributeCenterIcon:eV,AlignHorizontalDistributeEnd:tV,AlignHorizontalDistributeEndIcon:tV,AlignHorizontalDistributeStart:sV,AlignHorizontalDistributeStartIcon:sV,AlignHorizontalJustifyCenter:rV,AlignHorizontalJustifyCenterIcon:rV,AlignHorizontalJustifyEnd:nV,AlignHorizontalJustifyEndIcon:nV,AlignHorizontalJustifyStart:aV,AlignHorizontalJustifyStartIcon:aV,AlignHorizontalSpaceAround:iV,AlignHorizontalSpaceAroundIcon:iV,AlignHorizontalSpaceBetween:oV,AlignHorizontalSpaceBetweenIcon:oV,AlignJustify:lV,AlignJustifyIcon:lV,AlignLeft:y3,AlignLeftIcon:y3,AlignRight:v3,AlignRightIcon:v3,AlignStartHorizontal:cV,AlignStartHorizontalIcon:cV,AlignStartVertical:dV,AlignStartVerticalIcon:dV,AlignVerticalDistributeCenter:uV,AlignVerticalDistributeCenterIcon:uV,AlignVerticalDistributeEnd:hV,AlignVerticalDistributeEndIcon:hV,AlignVerticalDistributeStart:mV,AlignVerticalDistributeStartIcon:mV,AlignVerticalJustifyCenter:fV,AlignVerticalJustifyCenterIcon:fV,AlignVerticalJustifyEnd:pV,AlignVerticalJustifyEndIcon:pV,AlignVerticalJustifyStart:xV,AlignVerticalJustifyStartIcon:xV,AlignVerticalSpaceAround:gV,AlignVerticalSpaceAroundIcon:gV,AlignVerticalSpaceBetween:yV,AlignVerticalSpaceBetweenIcon:yV,Ambulance:vV,AmbulanceIcon:vV,Ampersand:bV,AmpersandIcon:bV,Ampersands:_V,AmpersandsIcon:_V,Amphora:wV,AmphoraIcon:wV,Anchor:jV,AnchorIcon:jV,Angry:NV,AngryIcon:NV,Annoyed:kV,AnnoyedIcon:kV,Antenna:SV,AntennaIcon:SV,Anvil:CV,AnvilIcon:CV,Aperture:TV,ApertureIcon:TV,AppWindow:VR,AppWindowIcon:VR,AppWindowMac:EV,AppWindowMacIcon:EV,Apple:AV,AppleIcon:AV,Archive:Uj,ArchiveIcon:Uj,ArchiveRestore:ZA,ArchiveRestoreIcon:ZA,ArchiveX:MV,ArchiveXIcon:MV,AreaChart:Pk,AreaChartIcon:Pk,Armchair:IV,ArmchairIcon:IV,ArrowBigDown:LV,ArrowBigDownDash:PV,ArrowBigDownDashIcon:PV,ArrowBigDownIcon:LV,ArrowBigLeft:RV,ArrowBigLeftDash:DV,ArrowBigLeftDashIcon:DV,ArrowBigLeftIcon:RV,ArrowBigRight:FV,ArrowBigRightDash:OV,ArrowBigRightDashIcon:OV,ArrowBigRightIcon:FV,ArrowBigUp:zV,ArrowBigUpDash:BV,ArrowBigUpDashIcon:BV,ArrowBigUpIcon:zV,ArrowDown:Ku,ArrowDown01:$V,ArrowDown01Icon:$V,ArrowDown10:UV,ArrowDown10Icon:UV,ArrowDownAZ:bk,ArrowDownAZIcon:bk,ArrowDownAz:bk,ArrowDownAzIcon:bk,ArrowDownCircle:Hk,ArrowDownCircleIcon:Hk,ArrowDownFromLine:qV,ArrowDownFromLineIcon:qV,ArrowDownIcon:Ku,ArrowDownLeft:VV,ArrowDownLeftFromCircle:Wk,ArrowDownLeftFromCircleIcon:Wk,ArrowDownLeftFromSquare:gC,ArrowDownLeftFromSquareIcon:gC,ArrowDownLeftIcon:VV,ArrowDownLeftSquare:mC,ArrowDownLeftSquareIcon:mC,ArrowDownNarrowWide:HV,ArrowDownNarrowWideIcon:HV,ArrowDownRight:HR,ArrowDownRightFromCircle:Kk,ArrowDownRightFromCircleIcon:Kk,ArrowDownRightFromSquare:yC,ArrowDownRightFromSquareIcon:yC,ArrowDownRightIcon:HR,ArrowDownRightSquare:fC,ArrowDownRightSquareIcon:fC,ArrowDownSquare:pC,ArrowDownSquareIcon:pC,ArrowDownToDot:GV,ArrowDownToDotIcon:GV,ArrowDownToLine:WV,ArrowDownToLineIcon:WV,ArrowDownUp:KV,ArrowDownUpIcon:KV,ArrowDownWideNarrow:_k,ArrowDownWideNarrowIcon:_k,ArrowDownZA:wk,ArrowDownZAIcon:wk,ArrowDownZa:wk,ArrowDownZaIcon:wk,ArrowLeft:wa,ArrowLeftCircle:Gk,ArrowLeftCircleIcon:Gk,ArrowLeftFromLine:YV,ArrowLeftFromLineIcon:YV,ArrowLeftIcon:wa,ArrowLeftRight:ZV,ArrowLeftRightIcon:ZV,ArrowLeftSquare:xC,ArrowLeftSquareIcon:xC,ArrowLeftToLine:XV,ArrowLeftToLineIcon:XV,ArrowRight:Ga,ArrowRightCircle:Xk,ArrowRightCircleIcon:Xk,ArrowRightFromLine:QV,ArrowRightFromLineIcon:QV,ArrowRightIcon:Ga,ArrowRightLeft:Xb,ArrowRightLeftIcon:Xb,ArrowRightSquare:_C,ArrowRightSquareIcon:_C,ArrowRightToLine:JV,ArrowRightToLineIcon:JV,ArrowUp:Fd,ArrowUp01:eH,ArrowUp01Icon:eH,ArrowUp10:tH,ArrowUp10Icon:tH,ArrowUpAZ:jk,ArrowUpAZIcon:jk,ArrowUpAz:jk,ArrowUpAzIcon:jk,ArrowUpCircle:Qk,ArrowUpCircleIcon:Qk,ArrowUpDown:Rd,ArrowUpDownIcon:Rd,ArrowUpFromDot:sH,ArrowUpFromDotIcon:sH,ArrowUpFromLine:rH,ArrowUpFromLineIcon:rH,ArrowUpIcon:Fd,ArrowUpLeft:nH,ArrowUpLeftFromCircle:Yk,ArrowUpLeftFromCircleIcon:Yk,ArrowUpLeftFromSquare:vC,ArrowUpLeftFromSquareIcon:vC,ArrowUpLeftIcon:nH,ArrowUpLeftSquare:wC,ArrowUpLeftSquareIcon:wC,ArrowUpNarrowWide:Nk,ArrowUpNarrowWideIcon:Nk,ArrowUpRight:GR,ArrowUpRightFromCircle:Zk,ArrowUpRightFromCircleIcon:Zk,ArrowUpRightFromSquare:bC,ArrowUpRightFromSquareIcon:bC,ArrowUpRightIcon:GR,ArrowUpRightSquare:jC,ArrowUpRightSquareIcon:jC,ArrowUpSquare:NC,ArrowUpSquareIcon:NC,ArrowUpToLine:aH,ArrowUpToLineIcon:aH,ArrowUpWideNarrow:iH,ArrowUpWideNarrowIcon:iH,ArrowUpZA:kk,ArrowUpZAIcon:kk,ArrowUpZa:kk,ArrowUpZaIcon:kk,ArrowsUpFromLine:oH,ArrowsUpFromLineIcon:oH,Asterisk:lH,AsteriskIcon:lH,AsteriskSquare:kC,AsteriskSquareIcon:kC,AtSign:cH,AtSignIcon:cH,Atom:dH,AtomIcon:dH,AudioLines:uH,AudioLinesIcon:uH,AudioWaveform:hH,AudioWaveformIcon:hH,Award:Xl,AwardIcon:Xl,Axe:mH,AxeIcon:mH,Axis3D:Sk,Axis3DIcon:Sk,Axis3d:Sk,Axis3dIcon:Sk,Baby:fH,BabyIcon:fH,Backpack:pH,BackpackIcon:pH,Badge:MH,BadgeAlert:xH,BadgeAlertIcon:xH,BadgeCent:gH,BadgeCentIcon:gH,BadgeCheck:Ck,BadgeCheckIcon:Ck,BadgeDollarSign:yH,BadgeDollarSignIcon:yH,BadgeEuro:vH,BadgeEuroIcon:vH,BadgeHelp:bH,BadgeHelpIcon:bH,BadgeIcon:MH,BadgeIndianRupee:_H,BadgeIndianRupeeIcon:_H,BadgeInfo:wH,BadgeInfoIcon:wH,BadgeJapaneseYen:jH,BadgeJapaneseYenIcon:jH,BadgeMinus:NH,BadgeMinusIcon:NH,BadgePercent:kH,BadgePercentIcon:kH,BadgePlus:SH,BadgePlusIcon:SH,BadgePoundSterling:CH,BadgePoundSterlingIcon:CH,BadgeRussianRuble:TH,BadgeRussianRubleIcon:TH,BadgeSwissFranc:EH,BadgeSwissFrancIcon:EH,BadgeX:AH,BadgeXIcon:AH,BaggageClaim:IH,BaggageClaimIcon:IH,Ban:WR,BanIcon:WR,Banana:PH,BananaIcon:PH,Bandage:LH,BandageIcon:LH,Banknote:DH,BanknoteIcon:DH,BarChart:zk,BarChart2:$k,BarChart2Icon:$k,BarChart3:ao,BarChart3Icon:ao,BarChart4:Fk,BarChart4Icon:Fk,BarChartBig:Ok,BarChartBigIcon:Ok,BarChartHorizontal:Dk,BarChartHorizontalBig:Lk,BarChartHorizontalBigIcon:Lk,BarChartHorizontalIcon:Dk,BarChartIcon:zk,Barcode:RH,BarcodeIcon:RH,Baseline:OH,BaselineIcon:OH,Bath:fp,BathIcon:fp,Battery:qH,BatteryCharging:FH,BatteryChargingIcon:FH,BatteryFull:BH,BatteryFullIcon:BH,BatteryIcon:qH,BatteryLow:zH,BatteryLowIcon:zH,BatteryMedium:$H,BatteryMediumIcon:$H,BatteryWarning:UH,BatteryWarningIcon:UH,Beaker:VH,BeakerIcon:VH,Bean:GH,BeanIcon:GH,BeanOff:HH,BeanOffIcon:HH,Bed:e0,BedDouble:b3,BedDoubleIcon:b3,BedIcon:e0,BedSingle:WH,BedSingleIcon:WH,Beef:KH,BeefIcon:KH,Beer:ZH,BeerIcon:ZH,BeerOff:YH,BeerOffIcon:YH,Bell:Rm,BellDot:XH,BellDotIcon:XH,BellElectric:QH,BellElectricIcon:QH,BellIcon:Rm,BellMinus:JH,BellMinusIcon:JH,BellOff:Fv,BellOffIcon:Fv,BellPlus:eG,BellPlusIcon:eG,BellRing:KR,BellRingIcon:KR,BetweenHorizonalEnd:Tk,BetweenHorizonalEndIcon:Tk,BetweenHorizonalStart:Ek,BetweenHorizonalStartIcon:Ek,BetweenHorizontalEnd:Tk,BetweenHorizontalEndIcon:Tk,BetweenHorizontalStart:Ek,BetweenHorizontalStartIcon:Ek,BetweenVerticalEnd:tG,BetweenVerticalEndIcon:tG,BetweenVerticalStart:sG,BetweenVerticalStartIcon:sG,BicepsFlexed:rG,BicepsFlexedIcon:rG,Bike:nG,BikeIcon:nG,Binary:aG,BinaryIcon:aG,Binoculars:iG,BinocularsIcon:iG,Biohazard:oG,BiohazardIcon:oG,Bird:lG,BirdIcon:lG,Bitcoin:cG,BitcoinIcon:cG,Blend:dG,BlendIcon:dG,Blinds:uG,BlindsIcon:uG,Blocks:hG,BlocksIcon:hG,Bluetooth:xG,BluetoothConnected:mG,BluetoothConnectedIcon:mG,BluetoothIcon:xG,BluetoothOff:fG,BluetoothOffIcon:fG,BluetoothSearching:pG,BluetoothSearchingIcon:pG,Bold:qj,BoldIcon:qj,Bolt:gG,BoltIcon:gG,Bomb:yG,BombIcon:yG,Bone:vG,BoneIcon:vG,Book:$G,BookA:bG,BookAIcon:bG,BookAudio:_G,BookAudioIcon:_G,BookCheck:wG,BookCheckIcon:wG,BookCopy:jG,BookCopyIcon:jG,BookDashed:Ak,BookDashedIcon:Ak,BookDown:NG,BookDownIcon:NG,BookHeadphones:kG,BookHeadphonesIcon:kG,BookHeart:SG,BookHeartIcon:SG,BookIcon:$G,BookImage:CG,BookImageIcon:CG,BookKey:TG,BookKeyIcon:TG,BookLock:EG,BookLockIcon:EG,BookMarked:AG,BookMarkedIcon:AG,BookMinus:MG,BookMinusIcon:MG,BookOpen:Th,BookOpenCheck:IG,BookOpenCheckIcon:IG,BookOpenIcon:Th,BookOpenText:PG,BookOpenTextIcon:PG,BookPlus:LG,BookPlusIcon:LG,BookTemplate:Ak,BookTemplateIcon:Ak,BookText:DG,BookTextIcon:DG,BookType:RG,BookTypeIcon:RG,BookUp:FG,BookUp2:OG,BookUp2Icon:OG,BookUpIcon:FG,BookUser:BG,BookUserIcon:BG,BookX:zG,BookXIcon:zG,Bookmark:Bg,BookmarkCheck:UG,BookmarkCheckIcon:UG,BookmarkIcon:Bg,BookmarkMinus:qG,BookmarkMinusIcon:qG,BookmarkPlus:YR,BookmarkPlusIcon:YR,BookmarkX:VG,BookmarkXIcon:VG,BoomBox:HG,BoomBoxIcon:HG,Bot:XA,BotIcon:XA,BotMessageSquare:GG,BotMessageSquareIcon:GG,BotOff:WG,BotOffIcon:WG,Box:KG,BoxIcon:KG,BoxSelect:DC,BoxSelectIcon:DC,Boxes:YG,BoxesIcon:YG,Braces:Mk,BracesIcon:Mk,Brackets:ZG,BracketsIcon:ZG,Brain:ZR,BrainCircuit:XG,BrainCircuitIcon:XG,BrainCog:QG,BrainCogIcon:QG,BrainIcon:ZR,BrickWall:JG,BrickWallIcon:JG,Briefcase:Yu,BriefcaseBusiness:eW,BriefcaseBusinessIcon:eW,BriefcaseConveyorBelt:tW,BriefcaseConveyorBeltIcon:tW,BriefcaseIcon:Yu,BriefcaseMedical:sW,BriefcaseMedicalIcon:sW,BringToFront:rW,BringToFrontIcon:rW,Brush:nW,BrushIcon:nW,Bug:oW,BugIcon:oW,BugOff:aW,BugOffIcon:aW,BugPlay:iW,BugPlayIcon:iW,Building:_3,Building2:Sa,Building2Icon:Sa,BuildingIcon:_3,Bus:cW,BusFront:lW,BusFrontIcon:lW,BusIcon:cW,Cable:uW,CableCar:dW,CableCarIcon:dW,CableIcon:uW,Cake:Eh,CakeIcon:Eh,CakeSlice:hW,CakeSliceIcon:hW,Calculator:QA,CalculatorIcon:QA,Calendar:rn,Calendar1:mW,Calendar1Icon:mW,CalendarArrowDown:fW,CalendarArrowDownIcon:fW,CalendarArrowUp:pW,CalendarArrowUpIcon:pW,CalendarCheck:XR,CalendarCheck2:xW,CalendarCheck2Icon:xW,CalendarCheckIcon:XR,CalendarClock:Bv,CalendarClockIcon:Bv,CalendarCog:gW,CalendarCogIcon:gW,CalendarDays:pd,CalendarDaysIcon:pd,CalendarFold:yW,CalendarFoldIcon:yW,CalendarHeart:QR,CalendarHeartIcon:QR,CalendarIcon:rn,CalendarMinus:bW,CalendarMinus2:vW,CalendarMinus2Icon:vW,CalendarMinusIcon:bW,CalendarOff:JR,CalendarOffIcon:JR,CalendarPlus:Ub,CalendarPlus2:_W,CalendarPlus2Icon:_W,CalendarPlusIcon:Ub,CalendarRange:wW,CalendarRangeIcon:wW,CalendarSearch:jW,CalendarSearchIcon:jW,CalendarSync:NW,CalendarSyncIcon:NW,CalendarX:SW,CalendarX2:kW,CalendarX2Icon:kW,CalendarXIcon:SW,Camera:pp,CameraIcon:pp,CameraOff:CW,CameraOffIcon:CW,CandlestickChart:Rk,CandlestickChartIcon:Rk,Candy:AW,CandyCane:TW,CandyCaneIcon:TW,CandyIcon:AW,CandyOff:EW,CandyOffIcon:EW,Cannabis:MW,CannabisIcon:MW,Captions:Ik,CaptionsIcon:Ik,CaptionsOff:IW,CaptionsOffIcon:IW,Car:DW,CarFront:PW,CarFrontIcon:PW,CarIcon:DW,CarTaxiFront:LW,CarTaxiFrontIcon:LW,Caravan:RW,CaravanIcon:RW,Carrot:OW,CarrotIcon:OW,CaseLower:FW,CaseLowerIcon:FW,CaseSensitive:BW,CaseSensitiveIcon:BW,CaseUpper:zW,CaseUpperIcon:zW,CassetteTape:$W,CassetteTapeIcon:$W,Cast:UW,CastIcon:UW,Castle:qW,CastleIcon:qW,Cat:VW,CatIcon:VW,Cctv:HW,CctvIcon:HW,ChartArea:Pk,ChartAreaIcon:Pk,ChartBar:Dk,ChartBarBig:Lk,ChartBarBigIcon:Lk,ChartBarDecreasing:GW,ChartBarDecreasingIcon:GW,ChartBarIcon:Dk,ChartBarIncreasing:WW,ChartBarIncreasingIcon:WW,ChartBarStacked:KW,ChartBarStackedIcon:KW,ChartCandlestick:Rk,ChartCandlestickIcon:Rk,ChartColumn:ao,ChartColumnBig:Ok,ChartColumnBigIcon:Ok,ChartColumnDecreasing:YW,ChartColumnDecreasingIcon:YW,ChartColumnIcon:ao,ChartColumnIncreasing:Fk,ChartColumnIncreasingIcon:Fk,ChartColumnStacked:ZW,ChartColumnStackedIcon:ZW,ChartGantt:XW,ChartGanttIcon:XW,ChartLine:Bk,ChartLineIcon:Bk,ChartNetwork:QW,ChartNetworkIcon:QW,ChartNoAxesColumn:$k,ChartNoAxesColumnDecreasing:JW,ChartNoAxesColumnDecreasingIcon:JW,ChartNoAxesColumnIcon:$k,ChartNoAxesColumnIncreasing:zk,ChartNoAxesColumnIncreasingIcon:zk,ChartNoAxesCombined:eK,ChartNoAxesCombinedIcon:eK,ChartNoAxesGantt:Uk,ChartNoAxesGanttIcon:Uk,ChartPie:qk,ChartPieIcon:qk,ChartScatter:Vk,ChartScatterIcon:Vk,ChartSpline:tK,ChartSplineIcon:tK,Check:Hn,CheckCheck:eO,CheckCheckIcon:eO,CheckCircle:mi,CheckCircle2:Mn,CheckCircle2Icon:Mn,CheckCircleIcon:mi,CheckIcon:Hn,CheckSquare:Lb,CheckSquare2:CC,CheckSquare2Icon:CC,CheckSquareIcon:Lb,ChefHat:sK,ChefHatIcon:sK,Cherry:rK,CherryIcon:rK,ChevronDown:so,ChevronDownCircle:Jk,ChevronDownCircleIcon:Jk,ChevronDownIcon:so,ChevronDownSquare:TC,ChevronDownSquareIcon:TC,ChevronFirst:nK,ChevronFirstIcon:nK,ChevronLast:aK,ChevronLastIcon:aK,ChevronLeft:Vo,ChevronLeftCircle:eS,ChevronLeftCircleIcon:eS,ChevronLeftIcon:Vo,ChevronLeftSquare:EC,ChevronLeftSquareIcon:EC,ChevronRight:ya,ChevronRightCircle:tS,ChevronRightCircleIcon:tS,ChevronRightIcon:ya,ChevronRightSquare:AC,ChevronRightSquareIcon:AC,ChevronUp:xp,ChevronUpCircle:sS,ChevronUpCircleIcon:sS,ChevronUpIcon:xp,ChevronUpSquare:MC,ChevronUpSquareIcon:MC,ChevronsDown:oK,ChevronsDownIcon:oK,ChevronsDownUp:iK,ChevronsDownUpIcon:iK,ChevronsLeft:dK,ChevronsLeftIcon:dK,ChevronsLeftRight:cK,ChevronsLeftRightEllipsis:lK,ChevronsLeftRightEllipsisIcon:lK,ChevronsLeftRightIcon:cK,ChevronsRight:hK,ChevronsRightIcon:hK,ChevronsRightLeft:uK,ChevronsRightLeftIcon:uK,ChevronsUp:mK,ChevronsUpDown:xx,ChevronsUpDownIcon:xx,ChevronsUpIcon:mK,Chrome:w3,ChromeIcon:w3,Church:fK,ChurchIcon:fK,Cigarette:xK,CigaretteIcon:xK,CigaretteOff:pK,CigaretteOffIcon:pK,Circle:Bd,CircleAlert:Hi,CircleAlertIcon:Hi,CircleArrowDown:Hk,CircleArrowDownIcon:Hk,CircleArrowLeft:Gk,CircleArrowLeftIcon:Gk,CircleArrowOutDownLeft:Wk,CircleArrowOutDownLeftIcon:Wk,CircleArrowOutDownRight:Kk,CircleArrowOutDownRightIcon:Kk,CircleArrowOutUpLeft:Yk,CircleArrowOutUpLeftIcon:Yk,CircleArrowOutUpRight:Zk,CircleArrowOutUpRightIcon:Zk,CircleArrowRight:Xk,CircleArrowRightIcon:Xk,CircleArrowUp:Qk,CircleArrowUpIcon:Qk,CircleCheck:Mn,CircleCheckBig:mi,CircleCheckBigIcon:mi,CircleCheckIcon:Mn,CircleChevronDown:Jk,CircleChevronDownIcon:Jk,CircleChevronLeft:eS,CircleChevronLeftIcon:eS,CircleChevronRight:tS,CircleChevronRightIcon:tS,CircleChevronUp:sS,CircleChevronUpIcon:sS,CircleDashed:gK,CircleDashedIcon:gK,CircleDivide:rS,CircleDivideIcon:rS,CircleDollarSign:yK,CircleDollarSignIcon:yK,CircleDot:bK,CircleDotDashed:vK,CircleDotDashedIcon:vK,CircleDotIcon:bK,CircleEllipsis:_K,CircleEllipsisIcon:_K,CircleEqual:wK,CircleEqualIcon:wK,CircleFadingArrowUp:jK,CircleFadingArrowUpIcon:jK,CircleFadingPlus:NK,CircleFadingPlusIcon:NK,CircleGauge:nS,CircleGaugeIcon:nS,CircleHelp:Ab,CircleHelpIcon:Ab,CircleIcon:Bd,CircleMinus:aS,CircleMinusIcon:aS,CircleOff:kK,CircleOffIcon:kK,CircleParking:oS,CircleParkingIcon:oS,CircleParkingOff:iS,CircleParkingOffIcon:iS,CirclePause:lS,CirclePauseIcon:lS,CirclePercent:cS,CirclePercentIcon:cS,CirclePlay:mf,CirclePlayIcon:mf,CirclePlus:dS,CirclePlusIcon:dS,CirclePower:uS,CirclePowerIcon:uS,CircleSlash:SK,CircleSlash2:hS,CircleSlash2Icon:hS,CircleSlashIcon:SK,CircleSlashed:hS,CircleSlashedIcon:hS,CircleStop:mS,CircleStopIcon:mS,CircleUser:pS,CircleUserIcon:pS,CircleUserRound:fS,CircleUserRoundIcon:fS,CircleX:Mc,CircleXIcon:Mc,CircuitBoard:CK,CircuitBoardIcon:CK,Citrus:TK,CitrusIcon:TK,Clapperboard:EK,ClapperboardIcon:EK,Clipboard:RK,ClipboardCheck:JA,ClipboardCheckIcon:JA,ClipboardCopy:AK,ClipboardCopyIcon:AK,ClipboardEdit:gS,ClipboardEditIcon:gS,ClipboardIcon:RK,ClipboardList:Vj,ClipboardListIcon:Vj,ClipboardMinus:MK,ClipboardMinusIcon:MK,ClipboardPaste:IK,ClipboardPasteIcon:IK,ClipboardPen:gS,ClipboardPenIcon:gS,ClipboardPenLine:xS,ClipboardPenLineIcon:xS,ClipboardPlus:PK,ClipboardPlusIcon:PK,ClipboardSignature:xS,ClipboardSignatureIcon:xS,ClipboardType:LK,ClipboardTypeIcon:LK,ClipboardX:DK,ClipboardXIcon:DK,Clock:cn,Clock1:OK,Clock10:FK,Clock10Icon:FK,Clock11:BK,Clock11Icon:BK,Clock12:zK,Clock12Icon:zK,Clock1Icon:OK,Clock2:$K,Clock2Icon:$K,Clock3:UK,Clock3Icon:UK,Clock4:qK,Clock4Icon:qK,Clock5:VK,Clock5Icon:VK,Clock6:HK,Clock6Icon:HK,Clock7:GK,Clock7Icon:GK,Clock8:WK,Clock8Icon:WK,Clock9:KK,Clock9Icon:KK,ClockAlert:YK,ClockAlertIcon:YK,ClockArrowDown:ZK,ClockArrowDownIcon:ZK,ClockArrowUp:XK,ClockArrowUpIcon:XK,ClockIcon:cn,Cloud:hY,CloudAlert:QK,CloudAlertIcon:QK,CloudCog:JK,CloudCogIcon:JK,CloudDownload:yS,CloudDownloadIcon:yS,CloudDrizzle:eY,CloudDrizzleIcon:eY,CloudFog:tY,CloudFogIcon:tY,CloudHail:sY,CloudHailIcon:sY,CloudIcon:hY,CloudLightning:rY,CloudLightningIcon:rY,CloudMoon:aY,CloudMoonIcon:aY,CloudMoonRain:nY,CloudMoonRainIcon:nY,CloudOff:iY,CloudOffIcon:iY,CloudRain:lY,CloudRainIcon:lY,CloudRainWind:oY,CloudRainWindIcon:oY,CloudSnow:cY,CloudSnowIcon:cY,CloudSun:uY,CloudSunIcon:uY,CloudSunRain:dY,CloudSunRainIcon:dY,CloudUpload:vS,CloudUploadIcon:vS,Cloudy:mY,CloudyIcon:mY,Clover:qb,CloverIcon:qb,Club:fY,ClubIcon:fY,Code:j3,Code2:Mb,Code2Icon:Mb,CodeIcon:j3,CodeSquare:IC,CodeSquareIcon:IC,CodeXml:Mb,CodeXmlIcon:Mb,Codepen:pY,CodepenIcon:pY,Codesandbox:xY,CodesandboxIcon:xY,Coffee:N3,CoffeeIcon:N3,Cog:gY,CogIcon:gY,Coins:tO,CoinsIcon:tO,Columns:bS,Columns2:bS,Columns2Icon:bS,Columns3:_S,Columns3Icon:_S,Columns4:yY,Columns4Icon:yY,ColumnsIcon:bS,Combine:vY,CombineIcon:vY,Command:bY,CommandIcon:bY,Compass:eM,CompassIcon:eM,Component:_Y,ComponentIcon:_Y,Computer:wY,ComputerIcon:wY,ConciergeBell:jY,ConciergeBellIcon:jY,Cone:NY,ConeIcon:NY,Construction:kY,ConstructionIcon:kY,Contact:k3,Contact2:wS,Contact2Icon:wS,ContactIcon:k3,ContactRound:wS,ContactRoundIcon:wS,Container:SY,ContainerIcon:SY,Contrast:CY,ContrastIcon:CY,Cookie:TY,CookieIcon:TY,CookingPot:EY,CookingPotIcon:EY,Copy:Ra,CopyCheck:AY,CopyCheckIcon:AY,CopyIcon:Ra,CopyMinus:MY,CopyMinusIcon:MY,CopyPlus:IY,CopyPlusIcon:IY,CopySlash:PY,CopySlashIcon:PY,CopyX:LY,CopyXIcon:LY,Copyleft:DY,CopyleftIcon:DY,Copyright:RY,CopyrightIcon:RY,CornerDownLeft:OY,CornerDownLeftIcon:OY,CornerDownRight:FY,CornerDownRightIcon:FY,CornerLeftDown:BY,CornerLeftDownIcon:BY,CornerLeftUp:zY,CornerLeftUpIcon:zY,CornerRightDown:$Y,CornerRightDownIcon:$Y,CornerRightUp:UY,CornerRightUpIcon:UY,CornerUpLeft:qY,CornerUpLeftIcon:qY,CornerUpRight:VY,CornerUpRightIcon:VY,Cpu:HY,CpuIcon:HY,CreativeCommons:GY,CreativeCommonsIcon:GY,CreditCard:gx,CreditCardIcon:gx,Croissant:WY,CroissantIcon:WY,Crop:KY,CropIcon:KY,Cross:YY,CrossIcon:YY,Crosshair:ZY,CrosshairIcon:ZY,Crown:nm,CrownIcon:nm,Cuboid:XY,CuboidIcon:XY,CupSoda:QY,CupSodaIcon:QY,CurlyBraces:Mk,CurlyBracesIcon:Mk,Currency:JY,CurrencyIcon:JY,Cylinder:eZ,CylinderIcon:eZ,Dam:tZ,DamIcon:tZ,Database:sO,DatabaseBackup:sZ,DatabaseBackupIcon:sZ,DatabaseIcon:sO,DatabaseZap:rZ,DatabaseZapIcon:rZ,Delete:nZ,DeleteIcon:nZ,Dessert:aZ,DessertIcon:aZ,Diameter:iZ,DiameterIcon:iZ,Diamond:cZ,DiamondIcon:cZ,DiamondMinus:oZ,DiamondMinusIcon:oZ,DiamondPercent:jS,DiamondPercentIcon:jS,DiamondPlus:lZ,DiamondPlusIcon:lZ,Dice1:dZ,Dice1Icon:dZ,Dice2:uZ,Dice2Icon:uZ,Dice3:hZ,Dice3Icon:hZ,Dice4:mZ,Dice4Icon:mZ,Dice5:fZ,Dice5Icon:fZ,Dice6:pZ,Dice6Icon:pZ,Dices:xZ,DicesIcon:xZ,Diff:gZ,DiffIcon:gZ,Disc:_Z,Disc2:yZ,Disc2Icon:yZ,Disc3:vZ,Disc3Icon:vZ,DiscAlbum:bZ,DiscAlbumIcon:bZ,DiscIcon:_Z,Divide:wZ,DivideCircle:rS,DivideCircleIcon:rS,DivideIcon:wZ,DivideSquare:RC,DivideSquareIcon:RC,Dna:NZ,DnaIcon:NZ,DnaOff:jZ,DnaOffIcon:jZ,Dock:kZ,DockIcon:kZ,Dog:SZ,DogIcon:SZ,DollarSign:_l,DollarSignIcon:_l,Donut:CZ,DonutIcon:CZ,DoorClosed:TZ,DoorClosedIcon:TZ,DoorOpen:zv,DoorOpenIcon:zv,Dot:EZ,DotIcon:EZ,DotSquare:OC,DotSquareIcon:OC,Download:Xa,DownloadCloud:yS,DownloadCloudIcon:yS,DownloadIcon:Xa,DraftingCompass:AZ,DraftingCompassIcon:AZ,Drama:MZ,DramaIcon:MZ,Dribbble:IZ,DribbbleIcon:IZ,Drill:PZ,DrillIcon:PZ,Droplet:LZ,DropletIcon:LZ,Droplets:t0,DropletsIcon:t0,Drum:DZ,DrumIcon:DZ,Drumstick:RZ,DrumstickIcon:RZ,Dumbbell:OZ,DumbbellIcon:OZ,Ear:BZ,EarIcon:BZ,EarOff:FZ,EarOffIcon:FZ,Earth:NS,EarthIcon:NS,EarthLock:zZ,EarthLockIcon:zZ,Eclipse:$Z,EclipseIcon:$Z,Edit:nd,Edit2:bv,Edit2Icon:bv,Edit3:vv,Edit3Icon:vv,EditIcon:nd,Egg:tM,EggFried:UZ,EggFriedIcon:UZ,EggIcon:tM,EggOff:qZ,EggOffIcon:qZ,Ellipsis:ix,EllipsisIcon:ix,EllipsisVertical:Eg,EllipsisVerticalIcon:Eg,Equal:GZ,EqualApproximately:VZ,EqualApproximatelyIcon:VZ,EqualIcon:GZ,EqualNot:HZ,EqualNotIcon:HZ,EqualSquare:FC,EqualSquareIcon:FC,Eraser:WZ,EraserIcon:WZ,EthernetPort:KZ,EthernetPortIcon:KZ,Euro:YZ,EuroIcon:YZ,Expand:ZZ,ExpandIcon:ZZ,ExternalLink:Yr,ExternalLinkIcon:Yr,Eye:jn,EyeClosed:XZ,EyeClosedIcon:XZ,EyeIcon:jn,EyeOff:am,EyeOffIcon:am,Facebook:ku,FacebookIcon:ku,Factory:QZ,FactoryIcon:QZ,Fan:JZ,FanIcon:JZ,FastForward:eX,FastForwardIcon:eX,Feather:tX,FeatherIcon:tX,Fence:sX,FenceIcon:sX,FerrisWheel:rX,FerrisWheelIcon:rX,Figma:nX,FigmaIcon:nX,File:sM,FileArchive:aX,FileArchiveIcon:aX,FileAudio:oX,FileAudio2:iX,FileAudio2Icon:iX,FileAudioIcon:oX,FileAxis3D:kS,FileAxis3DIcon:kS,FileAxis3d:kS,FileAxis3dIcon:kS,FileBadge:cX,FileBadge2:lX,FileBadge2Icon:lX,FileBadgeIcon:cX,FileBarChart:SS,FileBarChart2:CS,FileBarChart2Icon:CS,FileBarChartIcon:SS,FileBox:dX,FileBoxIcon:dX,FileChartColumn:CS,FileChartColumnIcon:CS,FileChartColumnIncreasing:SS,FileChartColumnIncreasingIcon:SS,FileChartLine:TS,FileChartLineIcon:TS,FileChartPie:ES,FileChartPieIcon:ES,FileCheck:rO,FileCheck2:uX,FileCheck2Icon:uX,FileCheckIcon:rO,FileClock:hX,FileClockIcon:hX,FileCode:fX,FileCode2:mX,FileCode2Icon:mX,FileCodeIcon:fX,FileCog:AS,FileCog2:AS,FileCog2Icon:AS,FileCogIcon:AS,FileDiff:pX,FileDiffIcon:pX,FileDigit:xX,FileDigitIcon:xX,FileDown:S3,FileDownIcon:S3,FileEdit:IS,FileEditIcon:IS,FileHeart:gX,FileHeartIcon:gX,FileIcon:sM,FileImage:Qb,FileImageIcon:Qb,FileInput:yX,FileInputIcon:yX,FileJson:bX,FileJson2:vX,FileJson2Icon:vX,FileJsonIcon:bX,FileKey:wX,FileKey2:_X,FileKey2Icon:_X,FileKeyIcon:wX,FileLineChart:TS,FileLineChartIcon:TS,FileLock:NX,FileLock2:jX,FileLock2Icon:jX,FileLockIcon:NX,FileMinus:SX,FileMinus2:kX,FileMinus2Icon:kX,FileMinusIcon:SX,FileMusic:CX,FileMusicIcon:CX,FileOutput:TX,FileOutputIcon:TX,FilePen:IS,FilePenIcon:IS,FilePenLine:MS,FilePenLineIcon:MS,FilePieChart:ES,FilePieChartIcon:ES,FilePlus:AX,FilePlus2:EX,FilePlus2Icon:EX,FilePlusIcon:AX,FileQuestion:MX,FileQuestionIcon:MX,FileScan:IX,FileScanIcon:IX,FileSearch:LX,FileSearch2:PX,FileSearch2Icon:PX,FileSearchIcon:LX,FileSignature:MS,FileSignatureIcon:MS,FileSliders:DX,FileSlidersIcon:DX,FileSpreadsheet:Jb,FileSpreadsheetIcon:Jb,FileStack:nO,FileStackIcon:nO,FileSymlink:RX,FileSymlinkIcon:RX,FileTerminal:OX,FileTerminalIcon:OX,FileText:ln,FileTextIcon:ln,FileType:BX,FileType2:FX,FileType2Icon:FX,FileTypeIcon:BX,FileUp:zX,FileUpIcon:zX,FileUser:$X,FileUserIcon:$X,FileVideo:aO,FileVideo2:UX,FileVideo2Icon:UX,FileVideoIcon:aO,FileVolume:VX,FileVolume2:qX,FileVolume2Icon:qX,FileVolumeIcon:VX,FileWarning:HX,FileWarningIcon:HX,FileX:WX,FileX2:GX,FileX2Icon:GX,FileXIcon:WX,Files:KX,FilesIcon:KX,Film:Nh,FilmIcon:Nh,Filter:s0,FilterIcon:s0,FilterX:YX,FilterXIcon:YX,Fingerprint:ZX,FingerprintIcon:ZX,FireExtinguisher:XX,FireExtinguisherIcon:XX,Fish:eQ,FishIcon:eQ,FishOff:QX,FishOffIcon:QX,FishSymbol:JX,FishSymbolIcon:JX,Flag:e_,FlagIcon:e_,FlagOff:tQ,FlagOffIcon:tQ,FlagTriangleLeft:sQ,FlagTriangleLeftIcon:sQ,FlagTriangleRight:rQ,FlagTriangleRightIcon:rQ,Flame:xc,FlameIcon:xc,FlameKindling:nQ,FlameKindlingIcon:nQ,Flashlight:iQ,FlashlightIcon:iQ,FlashlightOff:aQ,FlashlightOffIcon:aQ,FlaskConical:Hj,FlaskConicalIcon:Hj,FlaskConicalOff:oQ,FlaskConicalOffIcon:oQ,FlaskRound:lQ,FlaskRoundIcon:lQ,FlipHorizontal:iO,FlipHorizontal2:cQ,FlipHorizontal2Icon:cQ,FlipHorizontalIcon:iO,FlipVertical:uQ,FlipVertical2:dQ,FlipVertical2Icon:dQ,FlipVerticalIcon:uQ,Flower:hQ,Flower2:Yy,Flower2Icon:Yy,FlowerIcon:hQ,Focus:mQ,FocusIcon:mQ,FoldHorizontal:fQ,FoldHorizontalIcon:fQ,FoldVertical:pQ,FoldVerticalIcon:pQ,Folder:UQ,FolderArchive:xQ,FolderArchiveIcon:xQ,FolderCheck:gQ,FolderCheckIcon:gQ,FolderClock:yQ,FolderClockIcon:yQ,FolderClosed:vQ,FolderClosedIcon:vQ,FolderCode:bQ,FolderCodeIcon:bQ,FolderCog:PS,FolderCog2:PS,FolderCog2Icon:PS,FolderCogIcon:PS,FolderDot:_Q,FolderDotIcon:_Q,FolderDown:wQ,FolderDownIcon:wQ,FolderEdit:LS,FolderEditIcon:LS,FolderGit:NQ,FolderGit2:jQ,FolderGit2Icon:jQ,FolderGitIcon:NQ,FolderHeart:kQ,FolderHeartIcon:kQ,FolderIcon:UQ,FolderInput:SQ,FolderInputIcon:SQ,FolderKanban:CQ,FolderKanbanIcon:CQ,FolderKey:TQ,FolderKeyIcon:TQ,FolderLock:EQ,FolderLockIcon:EQ,FolderMinus:AQ,FolderMinusIcon:AQ,FolderOpen:im,FolderOpenDot:MQ,FolderOpenDotIcon:MQ,FolderOpenIcon:im,FolderOutput:IQ,FolderOutputIcon:IQ,FolderPen:LS,FolderPenIcon:LS,FolderPlus:PQ,FolderPlusIcon:PQ,FolderRoot:LQ,FolderRootIcon:LQ,FolderSearch:RQ,FolderSearch2:DQ,FolderSearch2Icon:DQ,FolderSearchIcon:RQ,FolderSymlink:OQ,FolderSymlinkIcon:OQ,FolderSync:FQ,FolderSyncIcon:FQ,FolderTree:BQ,FolderTreeIcon:BQ,FolderUp:zQ,FolderUpIcon:zQ,FolderX:$Q,FolderXIcon:$Q,Folders:qQ,FoldersIcon:qQ,Footprints:VQ,FootprintsIcon:VQ,ForkKnife:j4,ForkKnifeCrossed:w4,ForkKnifeCrossedIcon:w4,ForkKnifeIcon:j4,Forklift:HQ,ForkliftIcon:HQ,FormInput:nC,FormInputIcon:nC,Forward:GQ,ForwardIcon:GQ,Frame:WQ,FrameIcon:WQ,Framer:KQ,FramerIcon:KQ,Frown:YQ,FrownIcon:YQ,Fuel:ZQ,FuelIcon:ZQ,Fullscreen:XQ,FullscreenIcon:XQ,FunctionSquare:BC,FunctionSquareIcon:BC,GalleryHorizontal:JQ,GalleryHorizontalEnd:QQ,GalleryHorizontalEndIcon:QQ,GalleryHorizontalIcon:JQ,GalleryThumbnails:eJ,GalleryThumbnailsIcon:eJ,GalleryVertical:sJ,GalleryVerticalEnd:tJ,GalleryVerticalEndIcon:tJ,GalleryVerticalIcon:sJ,Gamepad:nJ,Gamepad2:rJ,Gamepad2Icon:rJ,GamepadIcon:nJ,GanttChart:Uk,GanttChartIcon:Uk,GanttChartSquare:ov,GanttChartSquareIcon:ov,Gauge:aJ,GaugeCircle:nS,GaugeCircleIcon:nS,GaugeIcon:aJ,Gavel:iJ,GavelIcon:iJ,Gem:oJ,GemIcon:oJ,Ghost:C3,GhostIcon:C3,Gift:li,GiftIcon:li,GitBranch:cJ,GitBranchIcon:cJ,GitBranchPlus:lJ,GitBranchPlusIcon:lJ,GitCommit:DS,GitCommitHorizontal:DS,GitCommitHorizontalIcon:DS,GitCommitIcon:DS,GitCommitVertical:dJ,GitCommitVerticalIcon:dJ,GitCompare:hJ,GitCompareArrows:uJ,GitCompareArrowsIcon:uJ,GitCompareIcon:hJ,GitFork:mJ,GitForkIcon:mJ,GitGraph:fJ,GitGraphIcon:fJ,GitMerge:pJ,GitMergeIcon:pJ,GitPullRequest:_J,GitPullRequestArrow:xJ,GitPullRequestArrowIcon:xJ,GitPullRequestClosed:gJ,GitPullRequestClosedIcon:gJ,GitPullRequestCreate:vJ,GitPullRequestCreateArrow:yJ,GitPullRequestCreateArrowIcon:yJ,GitPullRequestCreateIcon:vJ,GitPullRequestDraft:bJ,GitPullRequestDraftIcon:bJ,GitPullRequestIcon:_J,Github:wJ,GithubIcon:wJ,Gitlab:jJ,GitlabIcon:jJ,GlassWater:NJ,GlassWaterIcon:NJ,Glasses:kJ,GlassesIcon:kJ,Globe:gc,Globe2:NS,Globe2Icon:NS,GlobeIcon:gc,GlobeLock:SJ,GlobeLockIcon:SJ,Goal:CJ,GoalIcon:CJ,Grab:TJ,GrabIcon:TJ,GraduationCap:Od,GraduationCapIcon:Od,Grape:EJ,GrapeIcon:EJ,Grid:bg,Grid2X2:OS,Grid2X2Icon:OS,Grid2X2Plus:RS,Grid2X2PlusIcon:RS,Grid2x2:OS,Grid2x2Check:AJ,Grid2x2CheckIcon:AJ,Grid2x2Icon:OS,Grid2x2Plus:RS,Grid2x2PlusIcon:RS,Grid2x2X:MJ,Grid2x2XIcon:MJ,Grid3X3:bg,Grid3X3Icon:bg,Grid3x3:bg,Grid3x3Icon:bg,GridIcon:bg,Grip:PJ,GripHorizontal:IJ,GripHorizontalIcon:IJ,GripIcon:PJ,GripVertical:Su,GripVerticalIcon:Su,Group:LJ,GroupIcon:LJ,Guitar:DJ,GuitarIcon:DJ,Ham:RJ,HamIcon:RJ,Hammer:oO,HammerIcon:oO,Hand:lO,HandCoins:OJ,HandCoinsIcon:OJ,HandHeart:FJ,HandHeartIcon:FJ,HandHelping:Hy,HandHelpingIcon:Hy,HandIcon:lO,HandMetal:BJ,HandMetalIcon:BJ,HandPlatter:zJ,HandPlatterIcon:zJ,Handshake:Gj,HandshakeIcon:Gj,HardDrive:cO,HardDriveDownload:$J,HardDriveDownloadIcon:$J,HardDriveIcon:cO,HardDriveUpload:UJ,HardDriveUploadIcon:UJ,HardHat:qJ,HardHatIcon:qJ,Hash:Wj,HashIcon:Wj,Haze:VJ,HazeIcon:VJ,HdmiPort:HJ,HdmiPortIcon:HJ,Heading:YJ,Heading1:rM,Heading1Icon:rM,Heading2:nM,Heading2Icon:nM,Heading3:dO,Heading3Icon:dO,Heading4:GJ,Heading4Icon:GJ,Heading5:WJ,Heading5Icon:WJ,Heading6:KJ,Heading6Icon:KJ,HeadingIcon:YJ,HeadphoneOff:ZJ,HeadphoneOffIcon:ZJ,Headphones:XJ,HeadphonesIcon:XJ,Headset:QJ,HeadsetIcon:QJ,Heart:hi,HeartCrack:JJ,HeartCrackIcon:JJ,HeartHandshake:eee,HeartHandshakeIcon:eee,HeartIcon:hi,HeartOff:tee,HeartOffIcon:tee,HeartPulse:see,HeartPulseIcon:see,Heater:ree,HeaterIcon:ree,HelpCircle:Ab,HelpCircleIcon:Ab,HelpingHand:Hy,HelpingHandIcon:Hy,Hexagon:nee,HexagonIcon:nee,Highlighter:aee,HighlighterIcon:aee,History:aM,HistoryIcon:aM,Home:Cn,HomeIcon:Cn,Hop:oee,HopIcon:oee,HopOff:iee,HopOffIcon:iee,Hospital:lee,HospitalIcon:lee,Hotel:cee,HotelIcon:cee,Hourglass:dee,HourglassIcon:dee,House:Cn,HouseIcon:Cn,HousePlug:uee,HousePlugIcon:uee,HousePlus:hee,HousePlusIcon:hee,IceCream:BS,IceCream2:FS,IceCream2Icon:FS,IceCreamBowl:FS,IceCreamBowlIcon:FS,IceCreamCone:BS,IceCreamConeIcon:BS,IceCreamIcon:BS,Icon:xZe,IdCard:mee,IdCardIcon:mee,Image:fl,ImageDown:fee,ImageDownIcon:fee,ImageIcon:fl,ImageMinus:pee,ImageMinusIcon:pee,ImageOff:xee,ImageOffIcon:xee,ImagePlay:gee,ImagePlayIcon:gee,ImagePlus:$v,ImagePlusIcon:$v,ImageUp:yee,ImageUpIcon:yee,ImageUpscale:vee,ImageUpscaleIcon:vee,Images:bee,ImagesIcon:bee,Import:_ee,ImportIcon:_ee,Inbox:iM,InboxIcon:iM,Indent:$S,IndentDecrease:zS,IndentDecreaseIcon:zS,IndentIcon:$S,IndentIncrease:$S,IndentIncreaseIcon:$S,IndianRupee:wee,IndianRupeeIcon:wee,Infinity:jee,InfinityIcon:jee,Info:T3,InfoIcon:T3,Inspect:HC,InspectIcon:HC,InspectionPanel:Nee,InspectionPanelIcon:Nee,Instagram:au,InstagramIcon:au,Italic:Kj,ItalicIcon:Kj,IterationCcw:kee,IterationCcwIcon:kee,IterationCw:See,IterationCwIcon:See,JapaneseYen:Cee,JapaneseYenIcon:Cee,Joystick:Tee,JoystickIcon:Tee,Kanban:Uv,KanbanIcon:Uv,KanbanSquare:zC,KanbanSquareDashed:PC,KanbanSquareDashedIcon:PC,KanbanSquareIcon:zC,Key:gp,KeyIcon:gp,KeyRound:E3,KeyRoundIcon:E3,KeySquare:Eee,KeySquareIcon:Eee,Keyboard:Iee,KeyboardIcon:Iee,KeyboardMusic:Aee,KeyboardMusicIcon:Aee,KeyboardOff:Mee,KeyboardOffIcon:Mee,Lamp:Fee,LampCeiling:Pee,LampCeilingIcon:Pee,LampDesk:Lee,LampDeskIcon:Lee,LampFloor:Dee,LampFloorIcon:Dee,LampIcon:Fee,LampWallDown:Ree,LampWallDownIcon:Ree,LampWallUp:Oee,LampWallUpIcon:Oee,LandPlot:Bee,LandPlotIcon:Bee,Landmark:zee,LandmarkIcon:zee,Languages:$ee,LanguagesIcon:$ee,Laptop:qee,Laptop2:US,Laptop2Icon:US,LaptopIcon:qee,LaptopMinimal:US,LaptopMinimalCheck:Uee,LaptopMinimalCheckIcon:Uee,LaptopMinimalIcon:US,Lasso:Hee,LassoIcon:Hee,LassoSelect:Vee,LassoSelectIcon:Vee,Laugh:Gee,LaughIcon:Gee,Layers:uO,Layers2:Wee,Layers2Icon:Wee,Layers3:Kee,Layers3Icon:Kee,LayersIcon:uO,Layout:Pb,LayoutDashboard:A3,LayoutDashboardIcon:A3,LayoutGrid:Sf,LayoutGridIcon:Sf,LayoutIcon:Pb,LayoutList:Yee,LayoutListIcon:Yee,LayoutPanelLeft:Zee,LayoutPanelLeftIcon:Zee,LayoutPanelTop:Xee,LayoutPanelTopIcon:Xee,LayoutTemplate:M3,LayoutTemplateIcon:M3,Leaf:Qee,LeafIcon:Qee,LeafyGreen:Jee,LeafyGreenIcon:Jee,Lectern:ete,LecternIcon:ete,LetterText:tte,LetterTextIcon:tte,Library:I3,LibraryBig:ste,LibraryBigIcon:ste,LibraryIcon:I3,LibrarySquare:$C,LibrarySquareIcon:$C,LifeBuoy:oM,LifeBuoyIcon:oM,Ligature:rte,LigatureIcon:rte,Lightbulb:Yj,LightbulbIcon:Yj,LightbulbOff:nte,LightbulbOffIcon:nte,LineChart:Bk,LineChartIcon:Bk,Link:xo,Link2:rl,Link2Icon:rl,Link2Off:ate,Link2OffIcon:ate,LinkIcon:xo,Linkedin:om,LinkedinIcon:om,List:lm,ListCheck:ite,ListCheckIcon:ite,ListChecks:t_,ListChecksIcon:t_,ListCollapse:ote,ListCollapseIcon:ote,ListEnd:lte,ListEndIcon:lte,ListFilter:hO,ListFilterIcon:hO,ListIcon:lm,ListMinus:cte,ListMinusIcon:cte,ListMusic:dte,ListMusicIcon:dte,ListOrdered:r0,ListOrderedIcon:r0,ListPlus:ute,ListPlusIcon:ute,ListRestart:hte,ListRestartIcon:hte,ListStart:mte,ListStartIcon:mte,ListTodo:fte,ListTodoIcon:fte,ListTree:pte,ListTreeIcon:pte,ListVideo:xte,ListVideoIcon:xte,ListX:gte,ListXIcon:gte,Loader:vte,Loader2:ls,Loader2Icon:ls,LoaderCircle:ls,LoaderCircleIcon:ls,LoaderIcon:vte,LoaderPinwheel:yte,LoaderPinwheelIcon:yte,Locate:lM,LocateFixed:bte,LocateFixedIcon:bte,LocateIcon:lM,LocateOff:_te,LocateOffIcon:_te,Lock:Kc,LockIcon:Kc,LockKeyhole:wte,LockKeyholeIcon:wte,LockKeyholeOpen:qS,LockKeyholeOpenIcon:qS,LockOpen:VS,LockOpenIcon:VS,LogIn:P3,LogInIcon:P3,LogOut:cM,LogOutIcon:cM,Logs:jte,LogsIcon:jte,Lollipop:Nte,LollipopIcon:Nte,LucideAArrowDown:zq,LucideAArrowUp:$q,LucideALargeSmall:Uq,LucideAccessibility:qq,LucideActivity:Ch,LucideActivitySquare:hC,LucideAirVent:Vq,LucideAirplay:Hq,LucideAlarmCheck:gk,LucideAlarmClock:Wq,LucideAlarmClockCheck:gk,LucideAlarmClockMinus:yk,LucideAlarmClockOff:Gq,LucideAlarmClockPlus:vk,LucideAlarmMinus:yk,LucideAlarmPlus:vk,LucideAlarmSmoke:Kq,LucideAlbum:Yq,LucideAlertCircle:Hi,LucideAlertOctagon:Ib,LucideAlertTriangle:od,LucideAlignCenter:g3,LucideAlignCenterHorizontal:Zq,LucideAlignCenterVertical:Xq,LucideAlignEndHorizontal:Qq,LucideAlignEndVertical:Jq,LucideAlignHorizontalDistributeCenter:eV,LucideAlignHorizontalDistributeEnd:tV,LucideAlignHorizontalDistributeStart:sV,LucideAlignHorizontalJustifyCenter:rV,LucideAlignHorizontalJustifyEnd:nV,LucideAlignHorizontalJustifyStart:aV,LucideAlignHorizontalSpaceAround:iV,LucideAlignHorizontalSpaceBetween:oV,LucideAlignJustify:lV,LucideAlignLeft:y3,LucideAlignRight:v3,LucideAlignStartHorizontal:cV,LucideAlignStartVertical:dV,LucideAlignVerticalDistributeCenter:uV,LucideAlignVerticalDistributeEnd:hV,LucideAlignVerticalDistributeStart:mV,LucideAlignVerticalJustifyCenter:fV,LucideAlignVerticalJustifyEnd:pV,LucideAlignVerticalJustifyStart:xV,LucideAlignVerticalSpaceAround:gV,LucideAlignVerticalSpaceBetween:yV,LucideAmbulance:vV,LucideAmpersand:bV,LucideAmpersands:_V,LucideAmphora:wV,LucideAnchor:jV,LucideAngry:NV,LucideAnnoyed:kV,LucideAntenna:SV,LucideAnvil:CV,LucideAperture:TV,LucideAppWindow:VR,LucideAppWindowMac:EV,LucideApple:AV,LucideArchive:Uj,LucideArchiveRestore:ZA,LucideArchiveX:MV,LucideAreaChart:Pk,LucideArmchair:IV,LucideArrowBigDown:LV,LucideArrowBigDownDash:PV,LucideArrowBigLeft:RV,LucideArrowBigLeftDash:DV,LucideArrowBigRight:FV,LucideArrowBigRightDash:OV,LucideArrowBigUp:zV,LucideArrowBigUpDash:BV,LucideArrowDown:Ku,LucideArrowDown01:$V,LucideArrowDown10:UV,LucideArrowDownAZ:bk,LucideArrowDownAz:bk,LucideArrowDownCircle:Hk,LucideArrowDownFromLine:qV,LucideArrowDownLeft:VV,LucideArrowDownLeftFromCircle:Wk,LucideArrowDownLeftFromSquare:gC,LucideArrowDownLeftSquare:mC,LucideArrowDownNarrowWide:HV,LucideArrowDownRight:HR,LucideArrowDownRightFromCircle:Kk,LucideArrowDownRightFromSquare:yC,LucideArrowDownRightSquare:fC,LucideArrowDownSquare:pC,LucideArrowDownToDot:GV,LucideArrowDownToLine:WV,LucideArrowDownUp:KV,LucideArrowDownWideNarrow:_k,LucideArrowDownZA:wk,LucideArrowDownZa:wk,LucideArrowLeft:wa,LucideArrowLeftCircle:Gk,LucideArrowLeftFromLine:YV,LucideArrowLeftRight:ZV,LucideArrowLeftSquare:xC,LucideArrowLeftToLine:XV,LucideArrowRight:Ga,LucideArrowRightCircle:Xk,LucideArrowRightFromLine:QV,LucideArrowRightLeft:Xb,LucideArrowRightSquare:_C,LucideArrowRightToLine:JV,LucideArrowUp:Fd,LucideArrowUp01:eH,LucideArrowUp10:tH,LucideArrowUpAZ:jk,LucideArrowUpAz:jk,LucideArrowUpCircle:Qk,LucideArrowUpDown:Rd,LucideArrowUpFromDot:sH,LucideArrowUpFromLine:rH,LucideArrowUpLeft:nH,LucideArrowUpLeftFromCircle:Yk,LucideArrowUpLeftFromSquare:vC,LucideArrowUpLeftSquare:wC,LucideArrowUpNarrowWide:Nk,LucideArrowUpRight:GR,LucideArrowUpRightFromCircle:Zk,LucideArrowUpRightFromSquare:bC,LucideArrowUpRightSquare:jC,LucideArrowUpSquare:NC,LucideArrowUpToLine:aH,LucideArrowUpWideNarrow:iH,LucideArrowUpZA:kk,LucideArrowUpZa:kk,LucideArrowsUpFromLine:oH,LucideAsterisk:lH,LucideAsteriskSquare:kC,LucideAtSign:cH,LucideAtom:dH,LucideAudioLines:uH,LucideAudioWaveform:hH,LucideAward:Xl,LucideAxe:mH,LucideAxis3D:Sk,LucideAxis3d:Sk,LucideBaby:fH,LucideBackpack:pH,LucideBadge:MH,LucideBadgeAlert:xH,LucideBadgeCent:gH,LucideBadgeCheck:Ck,LucideBadgeDollarSign:yH,LucideBadgeEuro:vH,LucideBadgeHelp:bH,LucideBadgeIndianRupee:_H,LucideBadgeInfo:wH,LucideBadgeJapaneseYen:jH,LucideBadgeMinus:NH,LucideBadgePercent:kH,LucideBadgePlus:SH,LucideBadgePoundSterling:CH,LucideBadgeRussianRuble:TH,LucideBadgeSwissFranc:EH,LucideBadgeX:AH,LucideBaggageClaim:IH,LucideBan:WR,LucideBanana:PH,LucideBandage:LH,LucideBanknote:DH,LucideBarChart:zk,LucideBarChart2:$k,LucideBarChart3:ao,LucideBarChart4:Fk,LucideBarChartBig:Ok,LucideBarChartHorizontal:Dk,LucideBarChartHorizontalBig:Lk,LucideBarcode:RH,LucideBaseline:OH,LucideBath:fp,LucideBattery:qH,LucideBatteryCharging:FH,LucideBatteryFull:BH,LucideBatteryLow:zH,LucideBatteryMedium:$H,LucideBatteryWarning:UH,LucideBeaker:VH,LucideBean:GH,LucideBeanOff:HH,LucideBed:e0,LucideBedDouble:b3,LucideBedSingle:WH,LucideBeef:KH,LucideBeer:ZH,LucideBeerOff:YH,LucideBell:Rm,LucideBellDot:XH,LucideBellElectric:QH,LucideBellMinus:JH,LucideBellOff:Fv,LucideBellPlus:eG,LucideBellRing:KR,LucideBetweenHorizonalEnd:Tk,LucideBetweenHorizonalStart:Ek,LucideBetweenHorizontalEnd:Tk,LucideBetweenHorizontalStart:Ek,LucideBetweenVerticalEnd:tG,LucideBetweenVerticalStart:sG,LucideBicepsFlexed:rG,LucideBike:nG,LucideBinary:aG,LucideBinoculars:iG,LucideBiohazard:oG,LucideBird:lG,LucideBitcoin:cG,LucideBlend:dG,LucideBlinds:uG,LucideBlocks:hG,LucideBluetooth:xG,LucideBluetoothConnected:mG,LucideBluetoothOff:fG,LucideBluetoothSearching:pG,LucideBold:qj,LucideBolt:gG,LucideBomb:yG,LucideBone:vG,LucideBook:$G,LucideBookA:bG,LucideBookAudio:_G,LucideBookCheck:wG,LucideBookCopy:jG,LucideBookDashed:Ak,LucideBookDown:NG,LucideBookHeadphones:kG,LucideBookHeart:SG,LucideBookImage:CG,LucideBookKey:TG,LucideBookLock:EG,LucideBookMarked:AG,LucideBookMinus:MG,LucideBookOpen:Th,LucideBookOpenCheck:IG,LucideBookOpenText:PG,LucideBookPlus:LG,LucideBookTemplate:Ak,LucideBookText:DG,LucideBookType:RG,LucideBookUp:FG,LucideBookUp2:OG,LucideBookUser:BG,LucideBookX:zG,LucideBookmark:Bg,LucideBookmarkCheck:UG,LucideBookmarkMinus:qG,LucideBookmarkPlus:YR,LucideBookmarkX:VG,LucideBoomBox:HG,LucideBot:XA,LucideBotMessageSquare:GG,LucideBotOff:WG,LucideBox:KG,LucideBoxSelect:DC,LucideBoxes:YG,LucideBraces:Mk,LucideBrackets:ZG,LucideBrain:ZR,LucideBrainCircuit:XG,LucideBrainCog:QG,LucideBrickWall:JG,LucideBriefcase:Yu,LucideBriefcaseBusiness:eW,LucideBriefcaseConveyorBelt:tW,LucideBriefcaseMedical:sW,LucideBringToFront:rW,LucideBrush:nW,LucideBug:oW,LucideBugOff:aW,LucideBugPlay:iW,LucideBuilding:_3,LucideBuilding2:Sa,LucideBus:cW,LucideBusFront:lW,LucideCable:uW,LucideCableCar:dW,LucideCake:Eh,LucideCakeSlice:hW,LucideCalculator:QA,LucideCalendar:rn,LucideCalendar1:mW,LucideCalendarArrowDown:fW,LucideCalendarArrowUp:pW,LucideCalendarCheck:XR,LucideCalendarCheck2:xW,LucideCalendarClock:Bv,LucideCalendarCog:gW,LucideCalendarDays:pd,LucideCalendarFold:yW,LucideCalendarHeart:QR,LucideCalendarMinus:bW,LucideCalendarMinus2:vW,LucideCalendarOff:JR,LucideCalendarPlus:Ub,LucideCalendarPlus2:_W,LucideCalendarRange:wW,LucideCalendarSearch:jW,LucideCalendarSync:NW,LucideCalendarX:SW,LucideCalendarX2:kW,LucideCamera:pp,LucideCameraOff:CW,LucideCandlestickChart:Rk,LucideCandy:AW,LucideCandyCane:TW,LucideCandyOff:EW,LucideCannabis:MW,LucideCaptions:Ik,LucideCaptionsOff:IW,LucideCar:DW,LucideCarFront:PW,LucideCarTaxiFront:LW,LucideCaravan:RW,LucideCarrot:OW,LucideCaseLower:FW,LucideCaseSensitive:BW,LucideCaseUpper:zW,LucideCassetteTape:$W,LucideCast:UW,LucideCastle:qW,LucideCat:VW,LucideCctv:HW,LucideChartArea:Pk,LucideChartBar:Dk,LucideChartBarBig:Lk,LucideChartBarDecreasing:GW,LucideChartBarIncreasing:WW,LucideChartBarStacked:KW,LucideChartCandlestick:Rk,LucideChartColumn:ao,LucideChartColumnBig:Ok,LucideChartColumnDecreasing:YW,LucideChartColumnIncreasing:Fk,LucideChartColumnStacked:ZW,LucideChartGantt:XW,LucideChartLine:Bk,LucideChartNetwork:QW,LucideChartNoAxesColumn:$k,LucideChartNoAxesColumnDecreasing:JW,LucideChartNoAxesColumnIncreasing:zk,LucideChartNoAxesCombined:eK,LucideChartNoAxesGantt:Uk,LucideChartPie:qk,LucideChartScatter:Vk,LucideChartSpline:tK,LucideCheck:Hn,LucideCheckCheck:eO,LucideCheckCircle:mi,LucideCheckCircle2:Mn,LucideCheckSquare:Lb,LucideCheckSquare2:CC,LucideChefHat:sK,LucideCherry:rK,LucideChevronDown:so,LucideChevronDownCircle:Jk,LucideChevronDownSquare:TC,LucideChevronFirst:nK,LucideChevronLast:aK,LucideChevronLeft:Vo,LucideChevronLeftCircle:eS,LucideChevronLeftSquare:EC,LucideChevronRight:ya,LucideChevronRightCircle:tS,LucideChevronRightSquare:AC,LucideChevronUp:xp,LucideChevronUpCircle:sS,LucideChevronUpSquare:MC,LucideChevronsDown:oK,LucideChevronsDownUp:iK,LucideChevronsLeft:dK,LucideChevronsLeftRight:cK,LucideChevronsLeftRightEllipsis:lK,LucideChevronsRight:hK,LucideChevronsRightLeft:uK,LucideChevronsUp:mK,LucideChevronsUpDown:xx,LucideChrome:w3,LucideChurch:fK,LucideCigarette:xK,LucideCigaretteOff:pK,LucideCircle:Bd,LucideCircleAlert:Hi,LucideCircleArrowDown:Hk,LucideCircleArrowLeft:Gk,LucideCircleArrowOutDownLeft:Wk,LucideCircleArrowOutDownRight:Kk,LucideCircleArrowOutUpLeft:Yk,LucideCircleArrowOutUpRight:Zk,LucideCircleArrowRight:Xk,LucideCircleArrowUp:Qk,LucideCircleCheck:Mn,LucideCircleCheckBig:mi,LucideCircleChevronDown:Jk,LucideCircleChevronLeft:eS,LucideCircleChevronRight:tS,LucideCircleChevronUp:sS,LucideCircleDashed:gK,LucideCircleDivide:rS,LucideCircleDollarSign:yK,LucideCircleDot:bK,LucideCircleDotDashed:vK,LucideCircleEllipsis:_K,LucideCircleEqual:wK,LucideCircleFadingArrowUp:jK,LucideCircleFadingPlus:NK,LucideCircleGauge:nS,LucideCircleHelp:Ab,LucideCircleMinus:aS,LucideCircleOff:kK,LucideCircleParking:oS,LucideCircleParkingOff:iS,LucideCirclePause:lS,LucideCirclePercent:cS,LucideCirclePlay:mf,LucideCirclePlus:dS,LucideCirclePower:uS,LucideCircleSlash:SK,LucideCircleSlash2:hS,LucideCircleSlashed:hS,LucideCircleStop:mS,LucideCircleUser:pS,LucideCircleUserRound:fS,LucideCircleX:Mc,LucideCircuitBoard:CK,LucideCitrus:TK,LucideClapperboard:EK,LucideClipboard:RK,LucideClipboardCheck:JA,LucideClipboardCopy:AK,LucideClipboardEdit:gS,LucideClipboardList:Vj,LucideClipboardMinus:MK,LucideClipboardPaste:IK,LucideClipboardPen:gS,LucideClipboardPenLine:xS,LucideClipboardPlus:PK,LucideClipboardSignature:xS,LucideClipboardType:LK,LucideClipboardX:DK,LucideClock:cn,LucideClock1:OK,LucideClock10:FK,LucideClock11:BK,LucideClock12:zK,LucideClock2:$K,LucideClock3:UK,LucideClock4:qK,LucideClock5:VK,LucideClock6:HK,LucideClock7:GK,LucideClock8:WK,LucideClock9:KK,LucideClockAlert:YK,LucideClockArrowDown:ZK,LucideClockArrowUp:XK,LucideCloud:hY,LucideCloudAlert:QK,LucideCloudCog:JK,LucideCloudDownload:yS,LucideCloudDrizzle:eY,LucideCloudFog:tY,LucideCloudHail:sY,LucideCloudLightning:rY,LucideCloudMoon:aY,LucideCloudMoonRain:nY,LucideCloudOff:iY,LucideCloudRain:lY,LucideCloudRainWind:oY,LucideCloudSnow:cY,LucideCloudSun:uY,LucideCloudSunRain:dY,LucideCloudUpload:vS,LucideCloudy:mY,LucideClover:qb,LucideClub:fY,LucideCode:j3,LucideCode2:Mb,LucideCodeSquare:IC,LucideCodeXml:Mb,LucideCodepen:pY,LucideCodesandbox:xY,LucideCoffee:N3,LucideCog:gY,LucideCoins:tO,LucideColumns:bS,LucideColumns2:bS,LucideColumns3:_S,LucideColumns4:yY,LucideCombine:vY,LucideCommand:bY,LucideCompass:eM,LucideComponent:_Y,LucideComputer:wY,LucideConciergeBell:jY,LucideCone:NY,LucideConstruction:kY,LucideContact:k3,LucideContact2:wS,LucideContactRound:wS,LucideContainer:SY,LucideContrast:CY,LucideCookie:TY,LucideCookingPot:EY,LucideCopy:Ra,LucideCopyCheck:AY,LucideCopyMinus:MY,LucideCopyPlus:IY,LucideCopySlash:PY,LucideCopyX:LY,LucideCopyleft:DY,LucideCopyright:RY,LucideCornerDownLeft:OY,LucideCornerDownRight:FY,LucideCornerLeftDown:BY,LucideCornerLeftUp:zY,LucideCornerRightDown:$Y,LucideCornerRightUp:UY,LucideCornerUpLeft:qY,LucideCornerUpRight:VY,LucideCpu:HY,LucideCreativeCommons:GY,LucideCreditCard:gx,LucideCroissant:WY,LucideCrop:KY,LucideCross:YY,LucideCrosshair:ZY,LucideCrown:nm,LucideCuboid:XY,LucideCupSoda:QY,LucideCurlyBraces:Mk,LucideCurrency:JY,LucideCylinder:eZ,LucideDam:tZ,LucideDatabase:sO,LucideDatabaseBackup:sZ,LucideDatabaseZap:rZ,LucideDelete:nZ,LucideDessert:aZ,LucideDiameter:iZ,LucideDiamond:cZ,LucideDiamondMinus:oZ,LucideDiamondPercent:jS,LucideDiamondPlus:lZ,LucideDice1:dZ,LucideDice2:uZ,LucideDice3:hZ,LucideDice4:mZ,LucideDice5:fZ,LucideDice6:pZ,LucideDices:xZ,LucideDiff:gZ,LucideDisc:_Z,LucideDisc2:yZ,LucideDisc3:vZ,LucideDiscAlbum:bZ,LucideDivide:wZ,LucideDivideCircle:rS,LucideDivideSquare:RC,LucideDna:NZ,LucideDnaOff:jZ,LucideDock:kZ,LucideDog:SZ,LucideDollarSign:_l,LucideDonut:CZ,LucideDoorClosed:TZ,LucideDoorOpen:zv,LucideDot:EZ,LucideDotSquare:OC,LucideDownload:Xa,LucideDownloadCloud:yS,LucideDraftingCompass:AZ,LucideDrama:MZ,LucideDribbble:IZ,LucideDrill:PZ,LucideDroplet:LZ,LucideDroplets:t0,LucideDrum:DZ,LucideDrumstick:RZ,LucideDumbbell:OZ,LucideEar:BZ,LucideEarOff:FZ,LucideEarth:NS,LucideEarthLock:zZ,LucideEclipse:$Z,LucideEdit:nd,LucideEdit2:bv,LucideEdit3:vv,LucideEgg:tM,LucideEggFried:UZ,LucideEggOff:qZ,LucideEllipsis:ix,LucideEllipsisVertical:Eg,LucideEqual:GZ,LucideEqualApproximately:VZ,LucideEqualNot:HZ,LucideEqualSquare:FC,LucideEraser:WZ,LucideEthernetPort:KZ,LucideEuro:YZ,LucideExpand:ZZ,LucideExternalLink:Yr,LucideEye:jn,LucideEyeClosed:XZ,LucideEyeOff:am,LucideFacebook:ku,LucideFactory:QZ,LucideFan:JZ,LucideFastForward:eX,LucideFeather:tX,LucideFence:sX,LucideFerrisWheel:rX,LucideFigma:nX,LucideFile:sM,LucideFileArchive:aX,LucideFileAudio:oX,LucideFileAudio2:iX,LucideFileAxis3D:kS,LucideFileAxis3d:kS,LucideFileBadge:cX,LucideFileBadge2:lX,LucideFileBarChart:SS,LucideFileBarChart2:CS,LucideFileBox:dX,LucideFileChartColumn:CS,LucideFileChartColumnIncreasing:SS,LucideFileChartLine:TS,LucideFileChartPie:ES,LucideFileCheck:rO,LucideFileCheck2:uX,LucideFileClock:hX,LucideFileCode:fX,LucideFileCode2:mX,LucideFileCog:AS,LucideFileCog2:AS,LucideFileDiff:pX,LucideFileDigit:xX,LucideFileDown:S3,LucideFileEdit:IS,LucideFileHeart:gX,LucideFileImage:Qb,LucideFileInput:yX,LucideFileJson:bX,LucideFileJson2:vX,LucideFileKey:wX,LucideFileKey2:_X,LucideFileLineChart:TS,LucideFileLock:NX,LucideFileLock2:jX,LucideFileMinus:SX,LucideFileMinus2:kX,LucideFileMusic:CX,LucideFileOutput:TX,LucideFilePen:IS,LucideFilePenLine:MS,LucideFilePieChart:ES,LucideFilePlus:AX,LucideFilePlus2:EX,LucideFileQuestion:MX,LucideFileScan:IX,LucideFileSearch:LX,LucideFileSearch2:PX,LucideFileSignature:MS,LucideFileSliders:DX,LucideFileSpreadsheet:Jb,LucideFileStack:nO,LucideFileSymlink:RX,LucideFileTerminal:OX,LucideFileText:ln,LucideFileType:BX,LucideFileType2:FX,LucideFileUp:zX,LucideFileUser:$X,LucideFileVideo:aO,LucideFileVideo2:UX,LucideFileVolume:VX,LucideFileVolume2:qX,LucideFileWarning:HX,LucideFileX:WX,LucideFileX2:GX,LucideFiles:KX,LucideFilm:Nh,LucideFilter:s0,LucideFilterX:YX,LucideFingerprint:ZX,LucideFireExtinguisher:XX,LucideFish:eQ,LucideFishOff:QX,LucideFishSymbol:JX,LucideFlag:e_,LucideFlagOff:tQ,LucideFlagTriangleLeft:sQ,LucideFlagTriangleRight:rQ,LucideFlame:xc,LucideFlameKindling:nQ,LucideFlashlight:iQ,LucideFlashlightOff:aQ,LucideFlaskConical:Hj,LucideFlaskConicalOff:oQ,LucideFlaskRound:lQ,LucideFlipHorizontal:iO,LucideFlipHorizontal2:cQ,LucideFlipVertical:uQ,LucideFlipVertical2:dQ,LucideFlower:hQ,LucideFlower2:Yy,LucideFocus:mQ,LucideFoldHorizontal:fQ,LucideFoldVertical:pQ,LucideFolder:UQ,LucideFolderArchive:xQ,LucideFolderCheck:gQ,LucideFolderClock:yQ,LucideFolderClosed:vQ,LucideFolderCode:bQ,LucideFolderCog:PS,LucideFolderCog2:PS,LucideFolderDot:_Q,LucideFolderDown:wQ,LucideFolderEdit:LS,LucideFolderGit:NQ,LucideFolderGit2:jQ,LucideFolderHeart:kQ,LucideFolderInput:SQ,LucideFolderKanban:CQ,LucideFolderKey:TQ,LucideFolderLock:EQ,LucideFolderMinus:AQ,LucideFolderOpen:im,LucideFolderOpenDot:MQ,LucideFolderOutput:IQ,LucideFolderPen:LS,LucideFolderPlus:PQ,LucideFolderRoot:LQ,LucideFolderSearch:RQ,LucideFolderSearch2:DQ,LucideFolderSymlink:OQ,LucideFolderSync:FQ,LucideFolderTree:BQ,LucideFolderUp:zQ,LucideFolderX:$Q,LucideFolders:qQ,LucideFootprints:VQ,LucideForkKnife:j4,LucideForkKnifeCrossed:w4,LucideForklift:HQ,LucideFormInput:nC,LucideForward:GQ,LucideFrame:WQ,LucideFramer:KQ,LucideFrown:YQ,LucideFuel:ZQ,LucideFullscreen:XQ,LucideFunctionSquare:BC,LucideGalleryHorizontal:JQ,LucideGalleryHorizontalEnd:QQ,LucideGalleryThumbnails:eJ,LucideGalleryVertical:sJ,LucideGalleryVerticalEnd:tJ,LucideGamepad:nJ,LucideGamepad2:rJ,LucideGanttChart:Uk,LucideGanttChartSquare:ov,LucideGauge:aJ,LucideGaugeCircle:nS,LucideGavel:iJ,LucideGem:oJ,LucideGhost:C3,LucideGift:li,LucideGitBranch:cJ,LucideGitBranchPlus:lJ,LucideGitCommit:DS,LucideGitCommitHorizontal:DS,LucideGitCommitVertical:dJ,LucideGitCompare:hJ,LucideGitCompareArrows:uJ,LucideGitFork:mJ,LucideGitGraph:fJ,LucideGitMerge:pJ,LucideGitPullRequest:_J,LucideGitPullRequestArrow:xJ,LucideGitPullRequestClosed:gJ,LucideGitPullRequestCreate:vJ,LucideGitPullRequestCreateArrow:yJ,LucideGitPullRequestDraft:bJ,LucideGithub:wJ,LucideGitlab:jJ,LucideGlassWater:NJ,LucideGlasses:kJ,LucideGlobe:gc,LucideGlobe2:NS,LucideGlobeLock:SJ,LucideGoal:CJ,LucideGrab:TJ,LucideGraduationCap:Od,LucideGrape:EJ,LucideGrid:bg,LucideGrid2X2:OS,LucideGrid2X2Plus:RS,LucideGrid2x2:OS,LucideGrid2x2Check:AJ,LucideGrid2x2Plus:RS,LucideGrid2x2X:MJ,LucideGrid3X3:bg,LucideGrid3x3:bg,LucideGrip:PJ,LucideGripHorizontal:IJ,LucideGripVertical:Su,LucideGroup:LJ,LucideGuitar:DJ,LucideHam:RJ,LucideHammer:oO,LucideHand:lO,LucideHandCoins:OJ,LucideHandHeart:FJ,LucideHandHelping:Hy,LucideHandMetal:BJ,LucideHandPlatter:zJ,LucideHandshake:Gj,LucideHardDrive:cO,LucideHardDriveDownload:$J,LucideHardDriveUpload:UJ,LucideHardHat:qJ,LucideHash:Wj,LucideHaze:VJ,LucideHdmiPort:HJ,LucideHeading:YJ,LucideHeading1:rM,LucideHeading2:nM,LucideHeading3:dO,LucideHeading4:GJ,LucideHeading5:WJ,LucideHeading6:KJ,LucideHeadphoneOff:ZJ,LucideHeadphones:XJ,LucideHeadset:QJ,LucideHeart:hi,LucideHeartCrack:JJ,LucideHeartHandshake:eee,LucideHeartOff:tee,LucideHeartPulse:see,LucideHeater:ree,LucideHelpCircle:Ab,LucideHelpingHand:Hy,LucideHexagon:nee,LucideHighlighter:aee,LucideHistory:aM,LucideHome:Cn,LucideHop:oee,LucideHopOff:iee,LucideHospital:lee,LucideHotel:cee,LucideHourglass:dee,LucideHouse:Cn,LucideHousePlug:uee,LucideHousePlus:hee,LucideIceCream:BS,LucideIceCream2:FS,LucideIceCreamBowl:FS,LucideIceCreamCone:BS,LucideIdCard:mee,LucideImage:fl,LucideImageDown:fee,LucideImageMinus:pee,LucideImageOff:xee,LucideImagePlay:gee,LucideImagePlus:$v,LucideImageUp:yee,LucideImageUpscale:vee,LucideImages:bee,LucideImport:_ee,LucideInbox:iM,LucideIndent:$S,LucideIndentDecrease:zS,LucideIndentIncrease:$S,LucideIndianRupee:wee,LucideInfinity:jee,LucideInfo:T3,LucideInspect:HC,LucideInspectionPanel:Nee,LucideInstagram:au,LucideItalic:Kj,LucideIterationCcw:kee,LucideIterationCw:See,LucideJapaneseYen:Cee,LucideJoystick:Tee,LucideKanban:Uv,LucideKanbanSquare:zC,LucideKanbanSquareDashed:PC,LucideKey:gp,LucideKeyRound:E3,LucideKeySquare:Eee,LucideKeyboard:Iee,LucideKeyboardMusic:Aee,LucideKeyboardOff:Mee,LucideLamp:Fee,LucideLampCeiling:Pee,LucideLampDesk:Lee,LucideLampFloor:Dee,LucideLampWallDown:Ree,LucideLampWallUp:Oee,LucideLandPlot:Bee,LucideLandmark:zee,LucideLanguages:$ee,LucideLaptop:qee,LucideLaptop2:US,LucideLaptopMinimal:US,LucideLaptopMinimalCheck:Uee,LucideLasso:Hee,LucideLassoSelect:Vee,LucideLaugh:Gee,LucideLayers:uO,LucideLayers2:Wee,LucideLayers3:Kee,LucideLayout:Pb,LucideLayoutDashboard:A3,LucideLayoutGrid:Sf,LucideLayoutList:Yee,LucideLayoutPanelLeft:Zee,LucideLayoutPanelTop:Xee,LucideLayoutTemplate:M3,LucideLeaf:Qee,LucideLeafyGreen:Jee,LucideLectern:ete,LucideLetterText:tte,LucideLibrary:I3,LucideLibraryBig:ste,LucideLibrarySquare:$C,LucideLifeBuoy:oM,LucideLigature:rte,LucideLightbulb:Yj,LucideLightbulbOff:nte,LucideLineChart:Bk,LucideLink:xo,LucideLink2:rl,LucideLink2Off:ate,LucideLinkedin:om,LucideList:lm,LucideListCheck:ite,LucideListChecks:t_,LucideListCollapse:ote,LucideListEnd:lte,LucideListFilter:hO,LucideListMinus:cte,LucideListMusic:dte,LucideListOrdered:r0,LucideListPlus:ute,LucideListRestart:hte,LucideListStart:mte,LucideListTodo:fte,LucideListTree:pte,LucideListVideo:xte,LucideListX:gte,LucideLoader:vte,LucideLoader2:ls,LucideLoaderCircle:ls,LucideLoaderPinwheel:yte,LucideLocate:lM,LucideLocateFixed:bte,LucideLocateOff:_te,LucideLock:Kc,LucideLockKeyhole:wte,LucideLockKeyholeOpen:qS,LucideLockOpen:VS,LucideLogIn:P3,LucideLogOut:cM,LucideLogs:jte,LucideLollipop:Nte,LucideLuggage:kte,LucideMSquare:UC,LucideMagnet:Ste,LucideMail:Qs,LucideMailCheck:Cte,LucideMailMinus:Tte,LucideMailOpen:mO,LucideMailPlus:fO,LucideMailQuestion:Ete,LucideMailSearch:Ate,LucideMailWarning:Mte,LucideMailX:dM,LucideMailbox:Ite,LucideMails:Pte,LucideMap:L3,LucideMapPin:ja,LucideMapPinCheck:Dte,LucideMapPinCheckInside:Lte,LucideMapPinHouse:Rte,LucideMapPinMinus:Fte,LucideMapPinMinusInside:Ote,LucideMapPinOff:Bte,LucideMapPinPlus:$te,LucideMapPinPlusInside:zte,LucideMapPinX:qte,LucideMapPinXInside:Ute,LucideMapPinned:Vte,LucideMartini:Hte,LucideMaximize:pO,LucideMaximize2:Gte,LucideMedal:s_,LucideMegaphone:Cu,LucideMegaphoneOff:Wte,LucideMeh:Kte,LucideMemoryStick:Yte,LucideMenu:D3,LucideMenuSquare:qC,LucideMerge:Zte,LucideMessageCircle:tc,LucideMessageCircleCode:Xte,LucideMessageCircleDashed:Qte,LucideMessageCircleHeart:uM,LucideMessageCircleMore:Jte,LucideMessageCircleOff:ese,LucideMessageCirclePlus:tse,LucideMessageCircleQuestion:xO,LucideMessageCircleReply:sse,LucideMessageCircleWarning:rse,LucideMessageCircleX:nse,LucideMessageSquare:bi,LucideMessageSquareCode:ase,LucideMessageSquareDashed:ise,LucideMessageSquareDiff:ose,LucideMessageSquareDot:lse,LucideMessageSquareHeart:cse,LucideMessageSquareLock:dse,LucideMessageSquareMore:gO,LucideMessageSquareOff:use,LucideMessageSquarePlus:Tv,LucideMessageSquareQuote:yO,LucideMessageSquareReply:hse,LucideMessageSquareShare:mse,LucideMessageSquareText:fse,LucideMessageSquareWarning:pse,LucideMessageSquareX:xse,LucideMessagesSquare:gse,LucideMic:R3,LucideMic2:HS,LucideMicOff:yse,LucideMicVocal:HS,LucideMicrochip:vse,LucideMicroscope:bse,LucideMicrowave:_se,LucideMilestone:wse,LucideMilk:Nse,LucideMilkOff:jse,LucideMinimize:Sse,LucideMinimize2:kse,LucideMinus:qv,LucideMinusCircle:aS,LucideMinusSquare:VC,LucideMonitor:Zj,LucideMonitorCheck:Cse,LucideMonitorCog:Tse,LucideMonitorDot:Ese,LucideMonitorDown:Ase,LucideMonitorOff:Mse,LucideMonitorPause:Ise,LucideMonitorPlay:vO,LucideMonitorSmartphone:Pse,LucideMonitorSpeaker:Lse,LucideMonitorStop:Dse,LucideMonitorUp:O3,LucideMonitorX:Rse,LucideMoon:Fse,LucideMoonStar:Ose,LucideMoreHorizontal:ix,LucideMoreVertical:Eg,LucideMountain:zse,LucideMountainSnow:Bse,LucideMouse:Vse,LucideMouseOff:$se,LucideMousePointer:tm,LucideMousePointer2:Use,LucideMousePointerBan:qse,LucideMousePointerClick:Dd,LucideMousePointerSquareDashed:LC,LucideMove:rre,LucideMove3D:GS,LucideMove3d:GS,LucideMoveDiagonal:Gse,LucideMoveDiagonal2:Hse,LucideMoveDown:Yse,LucideMoveDownLeft:Wse,LucideMoveDownRight:Kse,LucideMoveHorizontal:Zse,LucideMoveLeft:Xse,LucideMoveRight:Qse,LucideMoveUp:tre,LucideMoveUpLeft:Jse,LucideMoveUpRight:ere,LucideMoveVertical:sre,LucideMusic:ore,LucideMusic2:nre,LucideMusic3:are,LucideMusic4:ire,LucideNavigation:bO,LucideNavigation2:cre,LucideNavigation2Off:lre,LucideNavigationOff:dre,LucideNetwork:ure,LucideNewspaper:Vv,LucideNfc:hre,LucideNotebook:xre,LucideNotebookPen:mre,LucideNotebookTabs:fre,LucideNotebookText:pre,LucideNotepadText:yre,LucideNotepadTextDashed:gre,LucideNut:bre,LucideNutOff:vre,LucideOctagon:wre,LucideOctagonAlert:Ib,LucideOctagonMinus:_re,LucideOctagonPause:WS,LucideOctagonX:KS,LucideOmega:jre,LucideOption:Nre,LucideOrbit:kre,LucideOrigami:Sre,LucideOutdent:zS,LucidePackage:Pl,LucidePackage2:Cre,LucidePackageCheck:Tre,LucidePackageMinus:Ere,LucidePackageOpen:Are,LucidePackagePlus:Mre,LucidePackageSearch:Ire,LucidePackageX:Pre,LucidePaintBucket:Lre,LucidePaintRoller:Dre,LucidePaintbrush:Rre,LucidePaintbrush2:YS,LucidePaintbrushVertical:YS,LucidePalette:pl,LucidePalmtree:h4,LucidePanelBottom:Bre,LucidePanelBottomClose:Ore,LucidePanelBottomDashed:ZS,LucidePanelBottomInactive:ZS,LucidePanelBottomOpen:Fre,LucidePanelLeft:eC,LucidePanelLeftClose:XS,LucidePanelLeftDashed:QS,LucidePanelLeftInactive:QS,LucidePanelLeftOpen:JS,LucidePanelRight:Ure,LucidePanelRightClose:zre,LucidePanelRightDashed:tC,LucidePanelRightInactive:tC,LucidePanelRightOpen:$re,LucidePanelTop:Hre,LucidePanelTopClose:qre,LucidePanelTopDashed:sC,LucidePanelTopInactive:sC,LucidePanelTopOpen:Vre,LucidePanelsLeftBottom:Gre,LucidePanelsLeftRight:_S,LucidePanelsRightBottom:Wre,LucidePanelsTopBottom:oC,LucidePanelsTopLeft:Pb,LucidePaperclip:Xj,LucideParentheses:Kre,LucideParkingCircle:oS,LucideParkingCircleOff:iS,LucideParkingMeter:Yre,LucideParkingSquare:WC,LucideParkingSquareOff:GC,LucidePartyPopper:iu,LucidePause:cm,LucidePauseCircle:lS,LucidePauseOctagon:WS,LucidePawPrint:Zre,LucidePcCase:Xre,LucidePen:bv,LucidePenBox:nd,LucidePenLine:vv,LucidePenOff:Qre,LucidePenSquare:nd,LucidePenTool:Qj,LucidePencil:Ta,LucidePencilLine:Jre,LucidePencilOff:ene,LucidePencilRuler:tne,LucidePentagon:sne,LucidePercent:F3,LucidePercentCircle:cS,LucidePercentDiamond:jS,LucidePercentSquare:KC,LucidePersonStanding:rne,LucidePhilippinePeso:nne,LucidePhone:Nn,LucidePhoneCall:ane,LucidePhoneForwarded:ine,LucidePhoneIncoming:one,LucidePhoneMissed:lne,LucidePhoneOff:cne,LucidePhoneOutgoing:dne,LucidePi:une,LucidePiSquare:YC,LucidePiano:hne,LucidePickaxe:mne,LucidePictureInPicture:pne,LucidePictureInPicture2:fne,LucidePieChart:qk,LucidePiggyBank:xne,LucidePilcrow:vne,LucidePilcrowLeft:gne,LucidePilcrowRight:yne,LucidePilcrowSquare:ZC,LucidePill:_ne,LucidePillBottle:bne,LucidePin:Jj,LucidePinOff:_O,LucidePipette:wne,LucidePizza:jne,LucidePlane:wO,LucidePlaneLanding:Nne,LucidePlaneTakeoff:kne,LucidePlay:Ho,LucidePlayCircle:mf,LucidePlaySquare:XC,LucidePlug:B3,LucidePlug2:Sne,LucidePlugZap:rC,LucidePlugZap2:rC,LucidePlus:Ws,LucidePlusCircle:dS,LucidePlusSquare:QC,LucidePocket:Tne,LucidePocketKnife:Cne,LucidePodcast:Ene,LucidePointer:Mne,LucidePointerOff:Ane,LucidePopcorn:Ine,LucidePopsicle:Pne,LucidePoundSterling:Lne,LucidePower:jO,LucidePowerCircle:uS,LucidePowerOff:Dne,LucidePowerSquare:JC,LucidePresentation:n0,LucidePrinter:NO,LucidePrinterCheck:Rne,LucideProjector:One,LucideProportions:Fne,LucidePuzzle:Bne,LucidePyramid:zne,LucideQrCode:Hv,LucideQuote:z3,LucideRabbit:$ne,LucideRadar:hM,LucideRadiation:Une,LucideRadical:qne,LucideRadio:r_,LucideRadioReceiver:Vne,LucideRadioTower:Hne,LucideRadius:Gne,LucideRailSymbol:Wne,LucideRainbow:Kne,LucideRat:Yne,LucideRatio:Zne,LucideReceipt:aae,LucideReceiptCent:Xne,LucideReceiptEuro:Qne,LucideReceiptIndianRupee:Jne,LucideReceiptJapaneseYen:eae,LucideReceiptPoundSterling:tae,LucideReceiptRussianRuble:sae,LucideReceiptSwissFranc:rae,LucideReceiptText:nae,LucideRectangleEllipsis:nC,LucideRectangleHorizontal:iae,LucideRectangleVertical:oae,LucideRecycle:lae,LucideRedo:e2,LucideRedo2:cae,LucideRedoDot:dae,LucideRefreshCcw:mM,LucideRefreshCcwDot:uae,LucideRefreshCw:Di,LucideRefreshCwOff:hae,LucideRefrigerator:mae,LucideRegex:fae,LucideRemoveFormatting:pae,LucideRepeat:kO,LucideRepeat1:xae,LucideRepeat2:gae,LucideReplace:vae,LucideReplaceAll:yae,LucideReply:SO,LucideReplyAll:bae,LucideRewind:_ae,LucideRibbon:wae,LucideRocket:Gv,LucideRockingChair:jae,LucideRollerCoaster:Nae,LucideRotate3D:aC,LucideRotate3d:aC,LucideRotateCcw:Wv,LucideRotateCcwSquare:kae,LucideRotateCw:$3,LucideRotateCwSquare:Sae,LucideRoute:Tae,LucideRouteOff:Cae,LucideRouter:Eae,LucideRows:iC,LucideRows2:iC,LucideRows3:oC,LucideRows4:Aae,LucideRss:Mae,LucideRuler:U3,LucideRussianRuble:Iae,LucideSailboat:Pae,LucideSalad:Lae,LucideSandwich:Dae,LucideSatellite:Oae,LucideSatelliteDish:Rae,LucideSave:ql,LucideSaveAll:Fae,LucideSaveOff:Bae,LucideScale:CO,LucideScale3D:lC,LucideScale3d:lC,LucideScaling:zae,LucideScan:Kae,LucideScanBarcode:$ae,LucideScanEye:Uae,LucideScanFace:qae,LucideScanLine:Vae,LucideScanQrCode:Hae,LucideScanSearch:Gae,LucideScanText:Wae,LucideScatterChart:Vk,LucideSchool:Yae,LucideSchool2:f4,LucideScissors:Xae,LucideScissorsLineDashed:Zae,LucideScissorsSquare:e4,LucideScissorsSquareDashedBottom:SC,LucideScreenShare:Jae,LucideScreenShareOff:Qae,LucideScroll:tie,LucideScrollText:eie,LucideSearch:fn,LucideSearchCheck:sie,LucideSearchCode:rie,LucideSearchSlash:nie,LucideSearchX:TO,LucideSection:aie,LucideSend:Zr,LucideSendHorizonal:cC,LucideSendHorizontal:cC,LucideSendToBack:iie,LucideSeparatorHorizontal:oie,LucideSeparatorVertical:lie,LucideServer:hie,LucideServerCog:cie,LucideServerCrash:die,LucideServerOff:uie,LucideSettings:lo,LucideSettings2:EO,LucideShapes:mie,LucideShare:AO,LucideShare2:Pc,LucideSheet:fie,LucideShell:pie,LucideShield:Zu,LucideShieldAlert:MO,LucideShieldBan:xie,LucideShieldCheck:a0,LucideShieldClose:dC,LucideShieldEllipsis:gie,LucideShieldHalf:yie,LucideShieldMinus:vie,LucideShieldOff:q3,LucideShieldPlus:bie,LucideShieldQuestion:_ie,LucideShieldX:dC,LucideShip:jie,LucideShipWheel:wie,LucideShirt:Nie,LucideShoppingBag:Kv,LucideShoppingBasket:kie,LucideShoppingCart:lp,LucideShovel:Sie,LucideShowerHead:Cie,LucideShrink:Tie,LucideShrub:Eie,LucideShuffle:V3,LucideSidebar:eC,LucideSidebarClose:XS,LucideSidebarOpen:JS,LucideSigma:Aie,LucideSigmaSquare:t4,LucideSignal:Die,LucideSignalHigh:Mie,LucideSignalLow:Iie,LucideSignalMedium:Pie,LucideSignalZero:Lie,LucideSignature:Rie,LucideSignpost:Fie,LucideSignpostBig:Oie,LucideSiren:Bie,LucideSkipBack:zie,LucideSkipForward:$ie,LucideSkull:Uie,LucideSlack:qie,LucideSlash:Vie,LucideSlashSquare:s4,LucideSlice:Hie,LucideSliders:uC,LucideSlidersHorizontal:H3,LucideSlidersVertical:uC,LucideSmartphone:zg,LucideSmartphoneCharging:Gie,LucideSmartphoneNfc:Wie,LucideSmile:Yie,LucideSmilePlus:Kie,LucideSnail:Zie,LucideSnowflake:Ev,LucideSofa:Xie,LucideSortAsc:Nk,LucideSortDesc:_k,LucideSoup:Qie,LucideSpace:Jie,LucideSpade:eoe,LucideSparkle:toe,LucideSparkles:jr,LucideSpeaker:soe,LucideSpeech:roe,LucideSpellCheck:aoe,LucideSpellCheck2:noe,LucideSpline:ioe,LucideSplit:ooe,LucideSplitSquareHorizontal:r4,LucideSplitSquareVertical:n4,LucideSprayCan:loe,LucideSprout:G3,LucideSquare:$g,LucideSquareActivity:hC,LucideSquareArrowDown:pC,LucideSquareArrowDownLeft:mC,LucideSquareArrowDownRight:fC,LucideSquareArrowLeft:xC,LucideSquareArrowOutDownLeft:gC,LucideSquareArrowOutDownRight:yC,LucideSquareArrowOutUpLeft:vC,LucideSquareArrowOutUpRight:bC,LucideSquareArrowRight:_C,LucideSquareArrowUp:NC,LucideSquareArrowUpLeft:wC,LucideSquareArrowUpRight:jC,LucideSquareAsterisk:kC,LucideSquareBottomDashedScissors:SC,LucideSquareChartGantt:ov,LucideSquareCheck:CC,LucideSquareCheckBig:Lb,LucideSquareChevronDown:TC,LucideSquareChevronLeft:EC,LucideSquareChevronRight:AC,LucideSquareChevronUp:MC,LucideSquareCode:IC,LucideSquareDashed:DC,LucideSquareDashedBottom:doe,LucideSquareDashedBottomCode:coe,LucideSquareDashedKanban:PC,LucideSquareDashedMousePointer:LC,LucideSquareDivide:RC,LucideSquareDot:OC,LucideSquareEqual:FC,LucideSquareFunction:BC,LucideSquareGanttChart:ov,LucideSquareKanban:zC,LucideSquareLibrary:$C,LucideSquareM:UC,LucideSquareMenu:qC,LucideSquareMinus:VC,LucideSquareMousePointer:HC,LucideSquareParking:WC,LucideSquareParkingOff:GC,LucideSquarePen:nd,LucideSquarePercent:KC,LucideSquarePi:YC,LucideSquarePilcrow:ZC,LucideSquarePlay:XC,LucideSquarePlus:QC,LucideSquarePower:JC,LucideSquareRadical:uoe,LucideSquareScissors:e4,LucideSquareSigma:t4,LucideSquareSlash:s4,LucideSquareSplitHorizontal:r4,LucideSquareSplitVertical:n4,LucideSquareSquare:hoe,LucideSquareStack:moe,LucideSquareTerminal:a4,LucideSquareUser:o4,LucideSquareUserRound:i4,LucideSquareX:l4,LucideSquircle:foe,LucideSquirrel:poe,LucideStamp:xoe,LucideStar:Qn,LucideStarHalf:goe,LucideStarOff:yoe,LucideStars:jr,LucideStepBack:voe,LucideStepForward:boe,LucideStethoscope:_oe,LucideSticker:woe,LucideStickyNote:joe,LucideStopCircle:mS,LucideStore:Noe,LucideStretchHorizontal:koe,LucideStretchVertical:Soe,LucideStrikethrough:IO,LucideSubscript:Coe,LucideSubtitles:Ik,LucideSun:n_,LucideSunDim:Toe,LucideSunMedium:Eoe,LucideSunMoon:Aoe,LucideSunSnow:Moe,LucideSunrise:Ioe,LucideSunset:Poe,LucideSuperscript:Loe,LucideSwatchBook:Doe,LucideSwissFranc:Roe,LucideSwitchCamera:Ooe,LucideSword:Foe,LucideSwords:Boe,LucideSyringe:zoe,LucideTable:pM,LucideTable2:fM,LucideTableCellsMerge:$oe,LucideTableCellsSplit:Uoe,LucideTableColumnsSplit:qoe,LucideTableOfContents:Voe,LucideTableProperties:Hoe,LucideTableRowsSplit:Goe,LucideTablet:Koe,LucideTabletSmartphone:Woe,LucideTablets:Yoe,LucideTag:Ah,LucideTags:Zoe,LucideTally1:Xoe,LucideTally2:Qoe,LucideTally3:Joe,LucideTally4:ele,LucideTally5:tle,LucideTangent:sle,LucideTarget:zd,LucideTelescope:rle,LucideTent:ale,LucideTentTree:nle,LucideTerminal:ile,LucideTerminalSquare:a4,LucideTestTube:ole,LucideTestTube2:c4,LucideTestTubeDiagonal:c4,LucideTestTubes:lle,LucideText:mle,LucideTextCursor:dle,LucideTextCursorInput:cle,LucideTextQuote:ule,LucideTextSearch:hle,LucideTextSelect:d4,LucideTextSelection:d4,LucideTheater:fle,LucideThermometer:gle,LucideThermometerSnowflake:ple,LucideThermometerSun:xle,LucideThumbsDown:PO,LucideThumbsUp:Mh,LucideTicket:LO,LucideTicketCheck:yle,LucideTicketMinus:vle,LucideTicketPercent:ble,LucideTicketPlus:_le,LucideTicketSlash:wle,LucideTicketX:jle,LucideTickets:kle,LucideTicketsPlane:Nle,LucideTimer:Tle,LucideTimerOff:Sle,LucideTimerReset:Cle,LucideToggleLeft:Ele,LucideToggleRight:Ale,LucideToilet:Mle,LucideTornado:Ile,LucideTorus:Ple,LucideTouchpad:Dle,LucideTouchpadOff:Lle,LucideTowerControl:Rle,LucideToyBrick:Ole,LucideTractor:Fle,LucideTrafficCone:Ble,LucideTrain:u4,LucideTrainFront:$le,LucideTrainFrontTunnel:zle,LucideTrainTrack:Ule,LucideTramFront:u4,LucideTrash:qle,LucideTrash2:yr,LucideTreeDeciduous:Vle,LucideTreePalm:h4,LucideTreePine:t2,LucideTrees:Hle,LucideTrello:Gle,LucideTrendingDown:a_,LucideTrendingUp:_o,LucideTrendingUpDown:Wle,LucideTriangle:Yle,LucideTriangleAlert:od,LucideTriangleRight:Kle,LucideTrophy:Zi,LucideTruck:DO,LucideTurtle:Zle,LucideTv:Qle,LucideTv2:m4,LucideTvMinimal:m4,LucideTvMinimalPlay:Xle,LucideTwitch:Jle,LucideTwitter:ece,LucideType:sce,LucideTypeOutline:tce,LucideUmbrella:nce,LucideUmbrellaOff:rce,LucideUnderline:xM,LucideUndo:s2,LucideUndo2:ace,LucideUndoDot:ice,LucideUnfoldHorizontal:oce,LucideUnfoldVertical:lce,LucideUngroup:cce,LucideUniversity:f4,LucideUnlink:W3,LucideUnlink2:dce,LucideUnlock:VS,LucideUnlockKeyhole:qS,LucideUnplug:uce,LucideUpload:oa,LucideUploadCloud:vS,LucideUsb:hce,LucideUser:Bi,LucideUser2:b4,LucideUserCheck:Yv,LucideUserCheck2:p4,LucideUserCircle:pS,LucideUserCircle2:fS,LucideUserCog:RO,LucideUserCog2:x4,LucideUserMinus:OO,LucideUserMinus2:g4,LucideUserPen:mce,LucideUserPlus:nl,LucideUserPlus2:y4,LucideUserRound:b4,LucideUserRoundCheck:p4,LucideUserRoundCog:x4,LucideUserRoundMinus:g4,LucideUserRoundPen:fce,LucideUserRoundPlus:y4,LucideUserRoundSearch:pce,LucideUserRoundX:v4,LucideUserSearch:xce,LucideUserSquare:o4,LucideUserSquare2:i4,LucideUserX:gce,LucideUserX2:v4,LucideUsers:fr,LucideUsers2:_4,LucideUsersRound:_4,LucideUtensils:j4,LucideUtensilsCrossed:w4,LucideUtilityPole:yce,LucideVariable:gM,LucideVault:vce,LucideVegan:bce,LucideVenetianMask:_ce,LucideVerified:Ck,LucideVibrate:jce,LucideVibrateOff:wce,LucideVideo:sn,LucideVideoOff:Nce,LucideVideotape:kce,LucideView:Sce,LucideVoicemail:Cce,LucideVolleyball:Tce,LucideVolume:Mce,LucideVolume1:Ece,LucideVolume2:FO,LucideVolumeOff:Ace,LucideVolumeX:BO,LucideVote:Ice,LucideWallet:zO,LucideWallet2:N4,LucideWalletCards:Pce,LucideWalletMinimal:N4,LucideWallpaper:Lce,LucideWand:Dce,LucideWand2:Ag,LucideWandSparkles:Ag,LucideWarehouse:Rce,LucideWashingMachine:Oce,LucideWatch:Fce,LucideWaves:Bce,LucideWaypoints:zce,LucideWebcam:$ce,LucideWebhook:qce,LucideWebhookOff:Uce,LucideWeight:Vce,LucideWheat:Gce,LucideWheatOff:Hce,LucideWholeWord:Wce,LucideWifi:Qce,LucideWifiHigh:Kce,LucideWifiLow:Yce,LucideWifiOff:Zce,LucideWifiZero:Xce,LucideWind:ede,LucideWindArrowDown:Jce,LucideWine:sde,LucideWineOff:tde,LucideWorkflow:$O,LucideWorm:rde,LucideWrapText:nde,LucideWrench:i0,LucideX:_r,LucideXCircle:Mc,LucideXOctagon:KS,LucideXSquare:l4,LucideYoutube:ade,LucideZap:Xu,LucideZapOff:ide,LucideZoomIn:r2,LucideZoomOut:yM,Luggage:kte,LuggageIcon:kte,MSquare:UC,MSquareIcon:UC,Magnet:Ste,MagnetIcon:Ste,Mail:Qs,MailCheck:Cte,MailCheckIcon:Cte,MailIcon:Qs,MailMinus:Tte,MailMinusIcon:Tte,MailOpen:mO,MailOpenIcon:mO,MailPlus:fO,MailPlusIcon:fO,MailQuestion:Ete,MailQuestionIcon:Ete,MailSearch:Ate,MailSearchIcon:Ate,MailWarning:Mte,MailWarningIcon:Mte,MailX:dM,MailXIcon:dM,Mailbox:Ite,MailboxIcon:Ite,Mails:Pte,MailsIcon:Pte,Map:L3,MapIcon:L3,MapPin:ja,MapPinCheck:Dte,MapPinCheckIcon:Dte,MapPinCheckInside:Lte,MapPinCheckInsideIcon:Lte,MapPinHouse:Rte,MapPinHouseIcon:Rte,MapPinIcon:ja,MapPinMinus:Fte,MapPinMinusIcon:Fte,MapPinMinusInside:Ote,MapPinMinusInsideIcon:Ote,MapPinOff:Bte,MapPinOffIcon:Bte,MapPinPlus:$te,MapPinPlusIcon:$te,MapPinPlusInside:zte,MapPinPlusInsideIcon:zte,MapPinX:qte,MapPinXIcon:qte,MapPinXInside:Ute,MapPinXInsideIcon:Ute,MapPinned:Vte,MapPinnedIcon:Vte,Martini:Hte,MartiniIcon:Hte,Maximize:pO,Maximize2:Gte,Maximize2Icon:Gte,MaximizeIcon:pO,Medal:s_,MedalIcon:s_,Megaphone:Cu,MegaphoneIcon:Cu,MegaphoneOff:Wte,MegaphoneOffIcon:Wte,Meh:Kte,MehIcon:Kte,MemoryStick:Yte,MemoryStickIcon:Yte,Menu:D3,MenuIcon:D3,MenuSquare:qC,MenuSquareIcon:qC,Merge:Zte,MergeIcon:Zte,MessageCircle:tc,MessageCircleCode:Xte,MessageCircleCodeIcon:Xte,MessageCircleDashed:Qte,MessageCircleDashedIcon:Qte,MessageCircleHeart:uM,MessageCircleHeartIcon:uM,MessageCircleIcon:tc,MessageCircleMore:Jte,MessageCircleMoreIcon:Jte,MessageCircleOff:ese,MessageCircleOffIcon:ese,MessageCirclePlus:tse,MessageCirclePlusIcon:tse,MessageCircleQuestion:xO,MessageCircleQuestionIcon:xO,MessageCircleReply:sse,MessageCircleReplyIcon:sse,MessageCircleWarning:rse,MessageCircleWarningIcon:rse,MessageCircleX:nse,MessageCircleXIcon:nse,MessageSquare:bi,MessageSquareCode:ase,MessageSquareCodeIcon:ase,MessageSquareDashed:ise,MessageSquareDashedIcon:ise,MessageSquareDiff:ose,MessageSquareDiffIcon:ose,MessageSquareDot:lse,MessageSquareDotIcon:lse,MessageSquareHeart:cse,MessageSquareHeartIcon:cse,MessageSquareIcon:bi,MessageSquareLock:dse,MessageSquareLockIcon:dse,MessageSquareMore:gO,MessageSquareMoreIcon:gO,MessageSquareOff:use,MessageSquareOffIcon:use,MessageSquarePlus:Tv,MessageSquarePlusIcon:Tv,MessageSquareQuote:yO,MessageSquareQuoteIcon:yO,MessageSquareReply:hse,MessageSquareReplyIcon:hse,MessageSquareShare:mse,MessageSquareShareIcon:mse,MessageSquareText:fse,MessageSquareTextIcon:fse,MessageSquareWarning:pse,MessageSquareWarningIcon:pse,MessageSquareX:xse,MessageSquareXIcon:xse,MessagesSquare:gse,MessagesSquareIcon:gse,Mic:R3,Mic2:HS,Mic2Icon:HS,MicIcon:R3,MicOff:yse,MicOffIcon:yse,MicVocal:HS,MicVocalIcon:HS,Microchip:vse,MicrochipIcon:vse,Microscope:bse,MicroscopeIcon:bse,Microwave:_se,MicrowaveIcon:_se,Milestone:wse,MilestoneIcon:wse,Milk:Nse,MilkIcon:Nse,MilkOff:jse,MilkOffIcon:jse,Minimize:Sse,Minimize2:kse,Minimize2Icon:kse,MinimizeIcon:Sse,Minus:qv,MinusCircle:aS,MinusCircleIcon:aS,MinusIcon:qv,MinusSquare:VC,MinusSquareIcon:VC,Monitor:Zj,MonitorCheck:Cse,MonitorCheckIcon:Cse,MonitorCog:Tse,MonitorCogIcon:Tse,MonitorDot:Ese,MonitorDotIcon:Ese,MonitorDown:Ase,MonitorDownIcon:Ase,MonitorIcon:Zj,MonitorOff:Mse,MonitorOffIcon:Mse,MonitorPause:Ise,MonitorPauseIcon:Ise,MonitorPlay:vO,MonitorPlayIcon:vO,MonitorSmartphone:Pse,MonitorSmartphoneIcon:Pse,MonitorSpeaker:Lse,MonitorSpeakerIcon:Lse,MonitorStop:Dse,MonitorStopIcon:Dse,MonitorUp:O3,MonitorUpIcon:O3,MonitorX:Rse,MonitorXIcon:Rse,Moon:Fse,MoonIcon:Fse,MoonStar:Ose,MoonStarIcon:Ose,MoreHorizontal:ix,MoreHorizontalIcon:ix,MoreVertical:Eg,MoreVerticalIcon:Eg,Mountain:zse,MountainIcon:zse,MountainSnow:Bse,MountainSnowIcon:Bse,Mouse:Vse,MouseIcon:Vse,MouseOff:$se,MouseOffIcon:$se,MousePointer:tm,MousePointer2:Use,MousePointer2Icon:Use,MousePointerBan:qse,MousePointerBanIcon:qse,MousePointerClick:Dd,MousePointerClickIcon:Dd,MousePointerIcon:tm,MousePointerSquareDashed:LC,MousePointerSquareDashedIcon:LC,Move:rre,Move3D:GS,Move3DIcon:GS,Move3d:GS,Move3dIcon:GS,MoveDiagonal:Gse,MoveDiagonal2:Hse,MoveDiagonal2Icon:Hse,MoveDiagonalIcon:Gse,MoveDown:Yse,MoveDownIcon:Yse,MoveDownLeft:Wse,MoveDownLeftIcon:Wse,MoveDownRight:Kse,MoveDownRightIcon:Kse,MoveHorizontal:Zse,MoveHorizontalIcon:Zse,MoveIcon:rre,MoveLeft:Xse,MoveLeftIcon:Xse,MoveRight:Qse,MoveRightIcon:Qse,MoveUp:tre,MoveUpIcon:tre,MoveUpLeft:Jse,MoveUpLeftIcon:Jse,MoveUpRight:ere,MoveUpRightIcon:ere,MoveVertical:sre,MoveVerticalIcon:sre,Music:ore,Music2:nre,Music2Icon:nre,Music3:are,Music3Icon:are,Music4:ire,Music4Icon:ire,MusicIcon:ore,Navigation:bO,Navigation2:cre,Navigation2Icon:cre,Navigation2Off:lre,Navigation2OffIcon:lre,NavigationIcon:bO,NavigationOff:dre,NavigationOffIcon:dre,Network:ure,NetworkIcon:ure,Newspaper:Vv,NewspaperIcon:Vv,Nfc:hre,NfcIcon:hre,Notebook:xre,NotebookIcon:xre,NotebookPen:mre,NotebookPenIcon:mre,NotebookTabs:fre,NotebookTabsIcon:fre,NotebookText:pre,NotebookTextIcon:pre,NotepadText:yre,NotepadTextDashed:gre,NotepadTextDashedIcon:gre,NotepadTextIcon:yre,Nut:bre,NutIcon:bre,NutOff:vre,NutOffIcon:vre,Octagon:wre,OctagonAlert:Ib,OctagonAlertIcon:Ib,OctagonIcon:wre,OctagonMinus:_re,OctagonMinusIcon:_re,OctagonPause:WS,OctagonPauseIcon:WS,OctagonX:KS,OctagonXIcon:KS,Omega:jre,OmegaIcon:jre,Option:Nre,OptionIcon:Nre,Orbit:kre,OrbitIcon:kre,Origami:Sre,OrigamiIcon:Sre,Outdent:zS,OutdentIcon:zS,Package:Pl,Package2:Cre,Package2Icon:Cre,PackageCheck:Tre,PackageCheckIcon:Tre,PackageIcon:Pl,PackageMinus:Ere,PackageMinusIcon:Ere,PackageOpen:Are,PackageOpenIcon:Are,PackagePlus:Mre,PackagePlusIcon:Mre,PackageSearch:Ire,PackageSearchIcon:Ire,PackageX:Pre,PackageXIcon:Pre,PaintBucket:Lre,PaintBucketIcon:Lre,PaintRoller:Dre,PaintRollerIcon:Dre,Paintbrush:Rre,Paintbrush2:YS,Paintbrush2Icon:YS,PaintbrushIcon:Rre,PaintbrushVertical:YS,PaintbrushVerticalIcon:YS,Palette:pl,PaletteIcon:pl,Palmtree:h4,PalmtreeIcon:h4,PanelBottom:Bre,PanelBottomClose:Ore,PanelBottomCloseIcon:Ore,PanelBottomDashed:ZS,PanelBottomDashedIcon:ZS,PanelBottomIcon:Bre,PanelBottomInactive:ZS,PanelBottomInactiveIcon:ZS,PanelBottomOpen:Fre,PanelBottomOpenIcon:Fre,PanelLeft:eC,PanelLeftClose:XS,PanelLeftCloseIcon:XS,PanelLeftDashed:QS,PanelLeftDashedIcon:QS,PanelLeftIcon:eC,PanelLeftInactive:QS,PanelLeftInactiveIcon:QS,PanelLeftOpen:JS,PanelLeftOpenIcon:JS,PanelRight:Ure,PanelRightClose:zre,PanelRightCloseIcon:zre,PanelRightDashed:tC,PanelRightDashedIcon:tC,PanelRightIcon:Ure,PanelRightInactive:tC,PanelRightInactiveIcon:tC,PanelRightOpen:$re,PanelRightOpenIcon:$re,PanelTop:Hre,PanelTopClose:qre,PanelTopCloseIcon:qre,PanelTopDashed:sC,PanelTopDashedIcon:sC,PanelTopIcon:Hre,PanelTopInactive:sC,PanelTopInactiveIcon:sC,PanelTopOpen:Vre,PanelTopOpenIcon:Vre,PanelsLeftBottom:Gre,PanelsLeftBottomIcon:Gre,PanelsLeftRight:_S,PanelsLeftRightIcon:_S,PanelsRightBottom:Wre,PanelsRightBottomIcon:Wre,PanelsTopBottom:oC,PanelsTopBottomIcon:oC,PanelsTopLeft:Pb,PanelsTopLeftIcon:Pb,Paperclip:Xj,PaperclipIcon:Xj,Parentheses:Kre,ParenthesesIcon:Kre,ParkingCircle:oS,ParkingCircleIcon:oS,ParkingCircleOff:iS,ParkingCircleOffIcon:iS,ParkingMeter:Yre,ParkingMeterIcon:Yre,ParkingSquare:WC,ParkingSquareIcon:WC,ParkingSquareOff:GC,ParkingSquareOffIcon:GC,PartyPopper:iu,PartyPopperIcon:iu,Pause:cm,PauseCircle:lS,PauseCircleIcon:lS,PauseIcon:cm,PauseOctagon:WS,PauseOctagonIcon:WS,PawPrint:Zre,PawPrintIcon:Zre,PcCase:Xre,PcCaseIcon:Xre,Pen:bv,PenBox:nd,PenBoxIcon:nd,PenIcon:bv,PenLine:vv,PenLineIcon:vv,PenOff:Qre,PenOffIcon:Qre,PenSquare:nd,PenSquareIcon:nd,PenTool:Qj,PenToolIcon:Qj,Pencil:Ta,PencilIcon:Ta,PencilLine:Jre,PencilLineIcon:Jre,PencilOff:ene,PencilOffIcon:ene,PencilRuler:tne,PencilRulerIcon:tne,Pentagon:sne,PentagonIcon:sne,Percent:F3,PercentCircle:cS,PercentCircleIcon:cS,PercentDiamond:jS,PercentDiamondIcon:jS,PercentIcon:F3,PercentSquare:KC,PercentSquareIcon:KC,PersonStanding:rne,PersonStandingIcon:rne,PhilippinePeso:nne,PhilippinePesoIcon:nne,Phone:Nn,PhoneCall:ane,PhoneCallIcon:ane,PhoneForwarded:ine,PhoneForwardedIcon:ine,PhoneIcon:Nn,PhoneIncoming:one,PhoneIncomingIcon:one,PhoneMissed:lne,PhoneMissedIcon:lne,PhoneOff:cne,PhoneOffIcon:cne,PhoneOutgoing:dne,PhoneOutgoingIcon:dne,Pi:une,PiIcon:une,PiSquare:YC,PiSquareIcon:YC,Piano:hne,PianoIcon:hne,Pickaxe:mne,PickaxeIcon:mne,PictureInPicture:pne,PictureInPicture2:fne,PictureInPicture2Icon:fne,PictureInPictureIcon:pne,PieChart:qk,PieChartIcon:qk,PiggyBank:xne,PiggyBankIcon:xne,Pilcrow:vne,PilcrowIcon:vne,PilcrowLeft:gne,PilcrowLeftIcon:gne,PilcrowRight:yne,PilcrowRightIcon:yne,PilcrowSquare:ZC,PilcrowSquareIcon:ZC,Pill:_ne,PillBottle:bne,PillBottleIcon:bne,PillIcon:_ne,Pin:Jj,PinIcon:Jj,PinOff:_O,PinOffIcon:_O,Pipette:wne,PipetteIcon:wne,Pizza:jne,PizzaIcon:jne,Plane:wO,PlaneIcon:wO,PlaneLanding:Nne,PlaneLandingIcon:Nne,PlaneTakeoff:kne,PlaneTakeoffIcon:kne,Play:Ho,PlayCircle:mf,PlayCircleIcon:mf,PlayIcon:Ho,PlaySquare:XC,PlaySquareIcon:XC,Plug:B3,Plug2:Sne,Plug2Icon:Sne,PlugIcon:B3,PlugZap:rC,PlugZap2:rC,PlugZap2Icon:rC,PlugZapIcon:rC,Plus:Ws,PlusCircle:dS,PlusCircleIcon:dS,PlusIcon:Ws,PlusSquare:QC,PlusSquareIcon:QC,Pocket:Tne,PocketIcon:Tne,PocketKnife:Cne,PocketKnifeIcon:Cne,Podcast:Ene,PodcastIcon:Ene,Pointer:Mne,PointerIcon:Mne,PointerOff:Ane,PointerOffIcon:Ane,Popcorn:Ine,PopcornIcon:Ine,Popsicle:Pne,PopsicleIcon:Pne,PoundSterling:Lne,PoundSterlingIcon:Lne,Power:jO,PowerCircle:uS,PowerCircleIcon:uS,PowerIcon:jO,PowerOff:Dne,PowerOffIcon:Dne,PowerSquare:JC,PowerSquareIcon:JC,Presentation:n0,PresentationIcon:n0,Printer:NO,PrinterCheck:Rne,PrinterCheckIcon:Rne,PrinterIcon:NO,Projector:One,ProjectorIcon:One,Proportions:Fne,ProportionsIcon:Fne,Puzzle:Bne,PuzzleIcon:Bne,Pyramid:zne,PyramidIcon:zne,QrCode:Hv,QrCodeIcon:Hv,Quote:z3,QuoteIcon:z3,Rabbit:$ne,RabbitIcon:$ne,Radar:hM,RadarIcon:hM,Radiation:Une,RadiationIcon:Une,Radical:qne,RadicalIcon:qne,Radio:r_,RadioIcon:r_,RadioReceiver:Vne,RadioReceiverIcon:Vne,RadioTower:Hne,RadioTowerIcon:Hne,Radius:Gne,RadiusIcon:Gne,RailSymbol:Wne,RailSymbolIcon:Wne,Rainbow:Kne,RainbowIcon:Kne,Rat:Yne,RatIcon:Yne,Ratio:Zne,RatioIcon:Zne,Receipt:aae,ReceiptCent:Xne,ReceiptCentIcon:Xne,ReceiptEuro:Qne,ReceiptEuroIcon:Qne,ReceiptIcon:aae,ReceiptIndianRupee:Jne,ReceiptIndianRupeeIcon:Jne,ReceiptJapaneseYen:eae,ReceiptJapaneseYenIcon:eae,ReceiptPoundSterling:tae,ReceiptPoundSterlingIcon:tae,ReceiptRussianRuble:sae,ReceiptRussianRubleIcon:sae,ReceiptSwissFranc:rae,ReceiptSwissFrancIcon:rae,ReceiptText:nae,ReceiptTextIcon:nae,RectangleEllipsis:nC,RectangleEllipsisIcon:nC,RectangleHorizontal:iae,RectangleHorizontalIcon:iae,RectangleVertical:oae,RectangleVerticalIcon:oae,Recycle:lae,RecycleIcon:lae,Redo:e2,Redo2:cae,Redo2Icon:cae,RedoDot:dae,RedoDotIcon:dae,RedoIcon:e2,RefreshCcw:mM,RefreshCcwDot:uae,RefreshCcwDotIcon:uae,RefreshCcwIcon:mM,RefreshCw:Di,RefreshCwIcon:Di,RefreshCwOff:hae,RefreshCwOffIcon:hae,Refrigerator:mae,RefrigeratorIcon:mae,Regex:fae,RegexIcon:fae,RemoveFormatting:pae,RemoveFormattingIcon:pae,Repeat:kO,Repeat1:xae,Repeat1Icon:xae,Repeat2:gae,Repeat2Icon:gae,RepeatIcon:kO,Replace:vae,ReplaceAll:yae,ReplaceAllIcon:yae,ReplaceIcon:vae,Reply:SO,ReplyAll:bae,ReplyAllIcon:bae,ReplyIcon:SO,Rewind:_ae,RewindIcon:_ae,Ribbon:wae,RibbonIcon:wae,Rocket:Gv,RocketIcon:Gv,RockingChair:jae,RockingChairIcon:jae,RollerCoaster:Nae,RollerCoasterIcon:Nae,Rotate3D:aC,Rotate3DIcon:aC,Rotate3d:aC,Rotate3dIcon:aC,RotateCcw:Wv,RotateCcwIcon:Wv,RotateCcwSquare:kae,RotateCcwSquareIcon:kae,RotateCw:$3,RotateCwIcon:$3,RotateCwSquare:Sae,RotateCwSquareIcon:Sae,Route:Tae,RouteIcon:Tae,RouteOff:Cae,RouteOffIcon:Cae,Router:Eae,RouterIcon:Eae,Rows:iC,Rows2:iC,Rows2Icon:iC,Rows3:oC,Rows3Icon:oC,Rows4:Aae,Rows4Icon:Aae,RowsIcon:iC,Rss:Mae,RssIcon:Mae,Ruler:U3,RulerIcon:U3,RussianRuble:Iae,RussianRubleIcon:Iae,Sailboat:Pae,SailboatIcon:Pae,Salad:Lae,SaladIcon:Lae,Sandwich:Dae,SandwichIcon:Dae,Satellite:Oae,SatelliteDish:Rae,SatelliteDishIcon:Rae,SatelliteIcon:Oae,Save:ql,SaveAll:Fae,SaveAllIcon:Fae,SaveIcon:ql,SaveOff:Bae,SaveOffIcon:Bae,Scale:CO,Scale3D:lC,Scale3DIcon:lC,Scale3d:lC,Scale3dIcon:lC,ScaleIcon:CO,Scaling:zae,ScalingIcon:zae,Scan:Kae,ScanBarcode:$ae,ScanBarcodeIcon:$ae,ScanEye:Uae,ScanEyeIcon:Uae,ScanFace:qae,ScanFaceIcon:qae,ScanIcon:Kae,ScanLine:Vae,ScanLineIcon:Vae,ScanQrCode:Hae,ScanQrCodeIcon:Hae,ScanSearch:Gae,ScanSearchIcon:Gae,ScanText:Wae,ScanTextIcon:Wae,ScatterChart:Vk,ScatterChartIcon:Vk,School:Yae,School2:f4,School2Icon:f4,SchoolIcon:Yae,Scissors:Xae,ScissorsIcon:Xae,ScissorsLineDashed:Zae,ScissorsLineDashedIcon:Zae,ScissorsSquare:e4,ScissorsSquareDashedBottom:SC,ScissorsSquareDashedBottomIcon:SC,ScissorsSquareIcon:e4,ScreenShare:Jae,ScreenShareIcon:Jae,ScreenShareOff:Qae,ScreenShareOffIcon:Qae,Scroll:tie,ScrollIcon:tie,ScrollText:eie,ScrollTextIcon:eie,Search:fn,SearchCheck:sie,SearchCheckIcon:sie,SearchCode:rie,SearchCodeIcon:rie,SearchIcon:fn,SearchSlash:nie,SearchSlashIcon:nie,SearchX:TO,SearchXIcon:TO,Section:aie,SectionIcon:aie,Send:Zr,SendHorizonal:cC,SendHorizonalIcon:cC,SendHorizontal:cC,SendHorizontalIcon:cC,SendIcon:Zr,SendToBack:iie,SendToBackIcon:iie,SeparatorHorizontal:oie,SeparatorHorizontalIcon:oie,SeparatorVertical:lie,SeparatorVerticalIcon:lie,Server:hie,ServerCog:cie,ServerCogIcon:cie,ServerCrash:die,ServerCrashIcon:die,ServerIcon:hie,ServerOff:uie,ServerOffIcon:uie,Settings:lo,Settings2:EO,Settings2Icon:EO,SettingsIcon:lo,Shapes:mie,ShapesIcon:mie,Share:AO,Share2:Pc,Share2Icon:Pc,ShareIcon:AO,Sheet:fie,SheetIcon:fie,Shell:pie,ShellIcon:pie,Shield:Zu,ShieldAlert:MO,ShieldAlertIcon:MO,ShieldBan:xie,ShieldBanIcon:xie,ShieldCheck:a0,ShieldCheckIcon:a0,ShieldClose:dC,ShieldCloseIcon:dC,ShieldEllipsis:gie,ShieldEllipsisIcon:gie,ShieldHalf:yie,ShieldHalfIcon:yie,ShieldIcon:Zu,ShieldMinus:vie,ShieldMinusIcon:vie,ShieldOff:q3,ShieldOffIcon:q3,ShieldPlus:bie,ShieldPlusIcon:bie,ShieldQuestion:_ie,ShieldQuestionIcon:_ie,ShieldX:dC,ShieldXIcon:dC,Ship:jie,ShipIcon:jie,ShipWheel:wie,ShipWheelIcon:wie,Shirt:Nie,ShirtIcon:Nie,ShoppingBag:Kv,ShoppingBagIcon:Kv,ShoppingBasket:kie,ShoppingBasketIcon:kie,ShoppingCart:lp,ShoppingCartIcon:lp,Shovel:Sie,ShovelIcon:Sie,ShowerHead:Cie,ShowerHeadIcon:Cie,Shrink:Tie,ShrinkIcon:Tie,Shrub:Eie,ShrubIcon:Eie,Shuffle:V3,ShuffleIcon:V3,Sidebar:eC,SidebarClose:XS,SidebarCloseIcon:XS,SidebarIcon:eC,SidebarOpen:JS,SidebarOpenIcon:JS,Sigma:Aie,SigmaIcon:Aie,SigmaSquare:t4,SigmaSquareIcon:t4,Signal:Die,SignalHigh:Mie,SignalHighIcon:Mie,SignalIcon:Die,SignalLow:Iie,SignalLowIcon:Iie,SignalMedium:Pie,SignalMediumIcon:Pie,SignalZero:Lie,SignalZeroIcon:Lie,Signature:Rie,SignatureIcon:Rie,Signpost:Fie,SignpostBig:Oie,SignpostBigIcon:Oie,SignpostIcon:Fie,Siren:Bie,SirenIcon:Bie,SkipBack:zie,SkipBackIcon:zie,SkipForward:$ie,SkipForwardIcon:$ie,Skull:Uie,SkullIcon:Uie,Slack:qie,SlackIcon:qie,Slash:Vie,SlashIcon:Vie,SlashSquare:s4,SlashSquareIcon:s4,Slice:Hie,SliceIcon:Hie,Sliders:uC,SlidersHorizontal:H3,SlidersHorizontalIcon:H3,SlidersIcon:uC,SlidersVertical:uC,SlidersVerticalIcon:uC,Smartphone:zg,SmartphoneCharging:Gie,SmartphoneChargingIcon:Gie,SmartphoneIcon:zg,SmartphoneNfc:Wie,SmartphoneNfcIcon:Wie,Smile:Yie,SmileIcon:Yie,SmilePlus:Kie,SmilePlusIcon:Kie,Snail:Zie,SnailIcon:Zie,Snowflake:Ev,SnowflakeIcon:Ev,Sofa:Xie,SofaIcon:Xie,SortAsc:Nk,SortAscIcon:Nk,SortDesc:_k,SortDescIcon:_k,Soup:Qie,SoupIcon:Qie,Space:Jie,SpaceIcon:Jie,Spade:eoe,SpadeIcon:eoe,Sparkle:toe,SparkleIcon:toe,Sparkles:jr,SparklesIcon:jr,Speaker:soe,SpeakerIcon:soe,Speech:roe,SpeechIcon:roe,SpellCheck:aoe,SpellCheck2:noe,SpellCheck2Icon:noe,SpellCheckIcon:aoe,Spline:ioe,SplineIcon:ioe,Split:ooe,SplitIcon:ooe,SplitSquareHorizontal:r4,SplitSquareHorizontalIcon:r4,SplitSquareVertical:n4,SplitSquareVerticalIcon:n4,SprayCan:loe,SprayCanIcon:loe,Sprout:G3,SproutIcon:G3,Square:$g,SquareActivity:hC,SquareActivityIcon:hC,SquareArrowDown:pC,SquareArrowDownIcon:pC,SquareArrowDownLeft:mC,SquareArrowDownLeftIcon:mC,SquareArrowDownRight:fC,SquareArrowDownRightIcon:fC,SquareArrowLeft:xC,SquareArrowLeftIcon:xC,SquareArrowOutDownLeft:gC,SquareArrowOutDownLeftIcon:gC,SquareArrowOutDownRight:yC,SquareArrowOutDownRightIcon:yC,SquareArrowOutUpLeft:vC,SquareArrowOutUpLeftIcon:vC,SquareArrowOutUpRight:bC,SquareArrowOutUpRightIcon:bC,SquareArrowRight:_C,SquareArrowRightIcon:_C,SquareArrowUp:NC,SquareArrowUpIcon:NC,SquareArrowUpLeft:wC,SquareArrowUpLeftIcon:wC,SquareArrowUpRight:jC,SquareArrowUpRightIcon:jC,SquareAsterisk:kC,SquareAsteriskIcon:kC,SquareBottomDashedScissors:SC,SquareBottomDashedScissorsIcon:SC,SquareChartGantt:ov,SquareChartGanttIcon:ov,SquareCheck:CC,SquareCheckBig:Lb,SquareCheckBigIcon:Lb,SquareCheckIcon:CC,SquareChevronDown:TC,SquareChevronDownIcon:TC,SquareChevronLeft:EC,SquareChevronLeftIcon:EC,SquareChevronRight:AC,SquareChevronRightIcon:AC,SquareChevronUp:MC,SquareChevronUpIcon:MC,SquareCode:IC,SquareCodeIcon:IC,SquareDashed:DC,SquareDashedBottom:doe,SquareDashedBottomCode:coe,SquareDashedBottomCodeIcon:coe,SquareDashedBottomIcon:doe,SquareDashedIcon:DC,SquareDashedKanban:PC,SquareDashedKanbanIcon:PC,SquareDashedMousePointer:LC,SquareDashedMousePointerIcon:LC,SquareDivide:RC,SquareDivideIcon:RC,SquareDot:OC,SquareDotIcon:OC,SquareEqual:FC,SquareEqualIcon:FC,SquareFunction:BC,SquareFunctionIcon:BC,SquareGanttChart:ov,SquareGanttChartIcon:ov,SquareIcon:$g,SquareKanban:zC,SquareKanbanIcon:zC,SquareLibrary:$C,SquareLibraryIcon:$C,SquareM:UC,SquareMIcon:UC,SquareMenu:qC,SquareMenuIcon:qC,SquareMinus:VC,SquareMinusIcon:VC,SquareMousePointer:HC,SquareMousePointerIcon:HC,SquareParking:WC,SquareParkingIcon:WC,SquareParkingOff:GC,SquareParkingOffIcon:GC,SquarePen:nd,SquarePenIcon:nd,SquarePercent:KC,SquarePercentIcon:KC,SquarePi:YC,SquarePiIcon:YC,SquarePilcrow:ZC,SquarePilcrowIcon:ZC,SquarePlay:XC,SquarePlayIcon:XC,SquarePlus:QC,SquarePlusIcon:QC,SquarePower:JC,SquarePowerIcon:JC,SquareRadical:uoe,SquareRadicalIcon:uoe,SquareScissors:e4,SquareScissorsIcon:e4,SquareSigma:t4,SquareSigmaIcon:t4,SquareSlash:s4,SquareSlashIcon:s4,SquareSplitHorizontal:r4,SquareSplitHorizontalIcon:r4,SquareSplitVertical:n4,SquareSplitVerticalIcon:n4,SquareSquare:hoe,SquareSquareIcon:hoe,SquareStack:moe,SquareStackIcon:moe,SquareTerminal:a4,SquareTerminalIcon:a4,SquareUser:o4,SquareUserIcon:o4,SquareUserRound:i4,SquareUserRoundIcon:i4,SquareX:l4,SquareXIcon:l4,Squircle:foe,SquircleIcon:foe,Squirrel:poe,SquirrelIcon:poe,Stamp:xoe,StampIcon:xoe,Star:Qn,StarHalf:goe,StarHalfIcon:goe,StarIcon:Qn,StarOff:yoe,StarOffIcon:yoe,Stars:jr,StarsIcon:jr,StepBack:voe,StepBackIcon:voe,StepForward:boe,StepForwardIcon:boe,Stethoscope:_oe,StethoscopeIcon:_oe,Sticker:woe,StickerIcon:woe,StickyNote:joe,StickyNoteIcon:joe,StopCircle:mS,StopCircleIcon:mS,Store:Noe,StoreIcon:Noe,StretchHorizontal:koe,StretchHorizontalIcon:koe,StretchVertical:Soe,StretchVerticalIcon:Soe,Strikethrough:IO,StrikethroughIcon:IO,Subscript:Coe,SubscriptIcon:Coe,Subtitles:Ik,SubtitlesIcon:Ik,Sun:n_,SunDim:Toe,SunDimIcon:Toe,SunIcon:n_,SunMedium:Eoe,SunMediumIcon:Eoe,SunMoon:Aoe,SunMoonIcon:Aoe,SunSnow:Moe,SunSnowIcon:Moe,Sunrise:Ioe,SunriseIcon:Ioe,Sunset:Poe,SunsetIcon:Poe,Superscript:Loe,SuperscriptIcon:Loe,SwatchBook:Doe,SwatchBookIcon:Doe,SwissFranc:Roe,SwissFrancIcon:Roe,SwitchCamera:Ooe,SwitchCameraIcon:Ooe,Sword:Foe,SwordIcon:Foe,Swords:Boe,SwordsIcon:Boe,Syringe:zoe,SyringeIcon:zoe,Table:pM,Table2:fM,Table2Icon:fM,TableCellsMerge:$oe,TableCellsMergeIcon:$oe,TableCellsSplit:Uoe,TableCellsSplitIcon:Uoe,TableColumnsSplit:qoe,TableColumnsSplitIcon:qoe,TableIcon:pM,TableOfContents:Voe,TableOfContentsIcon:Voe,TableProperties:Hoe,TablePropertiesIcon:Hoe,TableRowsSplit:Goe,TableRowsSplitIcon:Goe,Tablet:Koe,TabletIcon:Koe,TabletSmartphone:Woe,TabletSmartphoneIcon:Woe,Tablets:Yoe,TabletsIcon:Yoe,Tag:Ah,TagIcon:Ah,Tags:Zoe,TagsIcon:Zoe,Tally1:Xoe,Tally1Icon:Xoe,Tally2:Qoe,Tally2Icon:Qoe,Tally3:Joe,Tally3Icon:Joe,Tally4:ele,Tally4Icon:ele,Tally5:tle,Tally5Icon:tle,Tangent:sle,TangentIcon:sle,Target:zd,TargetIcon:zd,Telescope:rle,TelescopeIcon:rle,Tent:ale,TentIcon:ale,TentTree:nle,TentTreeIcon:nle,Terminal:ile,TerminalIcon:ile,TerminalSquare:a4,TerminalSquareIcon:a4,TestTube:ole,TestTube2:c4,TestTube2Icon:c4,TestTubeDiagonal:c4,TestTubeDiagonalIcon:c4,TestTubeIcon:ole,TestTubes:lle,TestTubesIcon:lle,Text:mle,TextCursor:dle,TextCursorIcon:dle,TextCursorInput:cle,TextCursorInputIcon:cle,TextIcon:mle,TextQuote:ule,TextQuoteIcon:ule,TextSearch:hle,TextSearchIcon:hle,TextSelect:d4,TextSelectIcon:d4,TextSelection:d4,TextSelectionIcon:d4,Theater:fle,TheaterIcon:fle,Thermometer:gle,ThermometerIcon:gle,ThermometerSnowflake:ple,ThermometerSnowflakeIcon:ple,ThermometerSun:xle,ThermometerSunIcon:xle,ThumbsDown:PO,ThumbsDownIcon:PO,ThumbsUp:Mh,ThumbsUpIcon:Mh,Ticket:LO,TicketCheck:yle,TicketCheckIcon:yle,TicketIcon:LO,TicketMinus:vle,TicketMinusIcon:vle,TicketPercent:ble,TicketPercentIcon:ble,TicketPlus:_le,TicketPlusIcon:_le,TicketSlash:wle,TicketSlashIcon:wle,TicketX:jle,TicketXIcon:jle,Tickets:kle,TicketsIcon:kle,TicketsPlane:Nle,TicketsPlaneIcon:Nle,Timer:Tle,TimerIcon:Tle,TimerOff:Sle,TimerOffIcon:Sle,TimerReset:Cle,TimerResetIcon:Cle,ToggleLeft:Ele,ToggleLeftIcon:Ele,ToggleRight:Ale,ToggleRightIcon:Ale,Toilet:Mle,ToiletIcon:Mle,Tornado:Ile,TornadoIcon:Ile,Torus:Ple,TorusIcon:Ple,Touchpad:Dle,TouchpadIcon:Dle,TouchpadOff:Lle,TouchpadOffIcon:Lle,TowerControl:Rle,TowerControlIcon:Rle,ToyBrick:Ole,ToyBrickIcon:Ole,Tractor:Fle,TractorIcon:Fle,TrafficCone:Ble,TrafficConeIcon:Ble,Train:u4,TrainFront:$le,TrainFrontIcon:$le,TrainFrontTunnel:zle,TrainFrontTunnelIcon:zle,TrainIcon:u4,TrainTrack:Ule,TrainTrackIcon:Ule,TramFront:u4,TramFrontIcon:u4,Trash:qle,Trash2:yr,Trash2Icon:yr,TrashIcon:qle,TreeDeciduous:Vle,TreeDeciduousIcon:Vle,TreePalm:h4,TreePalmIcon:h4,TreePine:t2,TreePineIcon:t2,Trees:Hle,TreesIcon:Hle,Trello:Gle,TrelloIcon:Gle,TrendingDown:a_,TrendingDownIcon:a_,TrendingUp:_o,TrendingUpDown:Wle,TrendingUpDownIcon:Wle,TrendingUpIcon:_o,Triangle:Yle,TriangleAlert:od,TriangleAlertIcon:od,TriangleIcon:Yle,TriangleRight:Kle,TriangleRightIcon:Kle,Trophy:Zi,TrophyIcon:Zi,Truck:DO,TruckIcon:DO,Turtle:Zle,TurtleIcon:Zle,Tv:Qle,Tv2:m4,Tv2Icon:m4,TvIcon:Qle,TvMinimal:m4,TvMinimalIcon:m4,TvMinimalPlay:Xle,TvMinimalPlayIcon:Xle,Twitch:Jle,TwitchIcon:Jle,Twitter:ece,TwitterIcon:ece,Type:sce,TypeIcon:sce,TypeOutline:tce,TypeOutlineIcon:tce,Umbrella:nce,UmbrellaIcon:nce,UmbrellaOff:rce,UmbrellaOffIcon:rce,Underline:xM,UnderlineIcon:xM,Undo:s2,Undo2:ace,Undo2Icon:ace,UndoDot:ice,UndoDotIcon:ice,UndoIcon:s2,UnfoldHorizontal:oce,UnfoldHorizontalIcon:oce,UnfoldVertical:lce,UnfoldVerticalIcon:lce,Ungroup:cce,UngroupIcon:cce,University:f4,UniversityIcon:f4,Unlink:W3,Unlink2:dce,Unlink2Icon:dce,UnlinkIcon:W3,Unlock:VS,UnlockIcon:VS,UnlockKeyhole:qS,UnlockKeyholeIcon:qS,Unplug:uce,UnplugIcon:uce,Upload:oa,UploadCloud:vS,UploadCloudIcon:vS,UploadIcon:oa,Usb:hce,UsbIcon:hce,User:Bi,User2:b4,User2Icon:b4,UserCheck:Yv,UserCheck2:p4,UserCheck2Icon:p4,UserCheckIcon:Yv,UserCircle:pS,UserCircle2:fS,UserCircle2Icon:fS,UserCircleIcon:pS,UserCog:RO,UserCog2:x4,UserCog2Icon:x4,UserCogIcon:RO,UserIcon:Bi,UserMinus:OO,UserMinus2:g4,UserMinus2Icon:g4,UserMinusIcon:OO,UserPen:mce,UserPenIcon:mce,UserPlus:nl,UserPlus2:y4,UserPlus2Icon:y4,UserPlusIcon:nl,UserRound:b4,UserRoundCheck:p4,UserRoundCheckIcon:p4,UserRoundCog:x4,UserRoundCogIcon:x4,UserRoundIcon:b4,UserRoundMinus:g4,UserRoundMinusIcon:g4,UserRoundPen:fce,UserRoundPenIcon:fce,UserRoundPlus:y4,UserRoundPlusIcon:y4,UserRoundSearch:pce,UserRoundSearchIcon:pce,UserRoundX:v4,UserRoundXIcon:v4,UserSearch:xce,UserSearchIcon:xce,UserSquare:o4,UserSquare2:i4,UserSquare2Icon:i4,UserSquareIcon:o4,UserX:gce,UserX2:v4,UserX2Icon:v4,UserXIcon:gce,Users:fr,Users2:_4,Users2Icon:_4,UsersIcon:fr,UsersRound:_4,UsersRoundIcon:_4,Utensils:j4,UtensilsCrossed:w4,UtensilsCrossedIcon:w4,UtensilsIcon:j4,UtilityPole:yce,UtilityPoleIcon:yce,Variable:gM,VariableIcon:gM,Vault:vce,VaultIcon:vce,Vegan:bce,VeganIcon:bce,VenetianMask:_ce,VenetianMaskIcon:_ce,Verified:Ck,VerifiedIcon:Ck,Vibrate:jce,VibrateIcon:jce,VibrateOff:wce,VibrateOffIcon:wce,Video:sn,VideoIcon:sn,VideoOff:Nce,VideoOffIcon:Nce,Videotape:kce,VideotapeIcon:kce,View:Sce,ViewIcon:Sce,Voicemail:Cce,VoicemailIcon:Cce,Volleyball:Tce,VolleyballIcon:Tce,Volume:Mce,Volume1:Ece,Volume1Icon:Ece,Volume2:FO,Volume2Icon:FO,VolumeIcon:Mce,VolumeOff:Ace,VolumeOffIcon:Ace,VolumeX:BO,VolumeXIcon:BO,Vote:Ice,VoteIcon:Ice,Wallet:zO,Wallet2:N4,Wallet2Icon:N4,WalletCards:Pce,WalletCardsIcon:Pce,WalletIcon:zO,WalletMinimal:N4,WalletMinimalIcon:N4,Wallpaper:Lce,WallpaperIcon:Lce,Wand:Dce,Wand2:Ag,Wand2Icon:Ag,WandIcon:Dce,WandSparkles:Ag,WandSparklesIcon:Ag,Warehouse:Rce,WarehouseIcon:Rce,WashingMachine:Oce,WashingMachineIcon:Oce,Watch:Fce,WatchIcon:Fce,Waves:Bce,WavesIcon:Bce,Waypoints:zce,WaypointsIcon:zce,Webcam:$ce,WebcamIcon:$ce,Webhook:qce,WebhookIcon:qce,WebhookOff:Uce,WebhookOffIcon:Uce,Weight:Vce,WeightIcon:Vce,Wheat:Gce,WheatIcon:Gce,WheatOff:Hce,WheatOffIcon:Hce,WholeWord:Wce,WholeWordIcon:Wce,Wifi:Qce,WifiHigh:Kce,WifiHighIcon:Kce,WifiIcon:Qce,WifiLow:Yce,WifiLowIcon:Yce,WifiOff:Zce,WifiOffIcon:Zce,WifiZero:Xce,WifiZeroIcon:Xce,Wind:ede,WindArrowDown:Jce,WindArrowDownIcon:Jce,WindIcon:ede,Wine:sde,WineIcon:sde,WineOff:tde,WineOffIcon:tde,Workflow:$O,WorkflowIcon:$O,Worm:rde,WormIcon:rde,WrapText:nde,WrapTextIcon:nde,Wrench:i0,WrenchIcon:i0,X:_r,XCircle:Mc,XCircleIcon:Mc,XIcon:_r,XOctagon:KS,XOctagonIcon:KS,XSquare:l4,XSquareIcon:l4,Youtube:ade,YoutubeIcon:ade,Zap:Xu,ZapIcon:Xu,ZapOff:ide,ZapOffIcon:ide,ZoomIn:r2,ZoomInIcon:r2,ZoomOut:yM,ZoomOutIcon:yM,createLucideIcon:ee,icons:v2t},Symbol.toStringTag,{value:"Module"})),f4e="-",b2t=s=>{const t=w2t(s),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=s;return{getClassGroupId:l=>{const o=l.split(f4e);return o[0]===""&&o.length!==1&&o.shift(),gZe(o,t)||_2t(l)},getConflictingClassGroupIds:(l,o)=>{const c=r[l]||[];return o&&n[l]?[...c,...n[l]]:c}}},gZe=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const r=s[0],n=t.nextPart.get(r),a=n?gZe(s.slice(1),n):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(f4e);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},eRe=/^\[(.+)\]$/,_2t=s=>{if(eRe.test(s)){const t=eRe.exec(s)[1],r=t==null?void 0:t.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},w2t=s=>{const{theme:t,prefix:r}=s,n={nextPart:new Map,validators:[]};return N2t(Object.entries(s.classGroups),r).forEach(([i,l])=>{uje(l,n,i,t)}),n},uje=(s,t,r,n)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:tRe(t,a);i.classGroupId=r;return}if(typeof a=="function"){if(j2t(a)){uje(a(n),t,r,n);return}t.validators.push({validator:a,classGroupId:r});return}Object.entries(a).forEach(([i,l])=>{uje(l,tRe(t,i),r,n)})})},tRe=(s,t)=>{let r=s;return t.split(f4e).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},j2t=s=>s.isThemeGetter,N2t=(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,k2t=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)}}},yZe="!",S2t=s=>{const{separator:t,experimentalParseClassName:r}=s,n=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,h=0,m;for(let b=0;bh?m-h:void 0;return{modifiers:c,hasImportantModifier:g,baseClassName:v,maybePostfixModifierPosition:j}};return r?o=>r({className:o,parseClassName:l}):l},C2t=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},T2t=s=>({cache:k2t(s.cacheSize),parseClassName:S2t(s),...b2t(s)}),E2t=/\s+/,A2t=(s,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(E2t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:h,hasImportantModifier:m,baseClassName:x,maybePostfixModifierPosition:g}=r(d);let v=!!g,j=n(v?x.substring(0,g):x);if(!j){if(!v){o=d+(o.length>0?" "+o:o);continue}if(j=n(x),!j){o=d+(o.length>0?" "+o:o);continue}v=!1}const b=C2t(h).join(":"),N=m?b+yZe:b,S=N+j;if(i.includes(S))continue;i.push(S);const T=a(j,v);for(let A=0;A0?" "+o:o)}return o};function M2t(){let s=0,t,r,n="";for(;s{if(typeof s=="string")return s;let t,r="";for(let n=0;nm(h),s());return r=T2t(d),n=r.cache.get,a=r.cache.set,i=o,o(c)}function o(c){const d=n(c);if(d)return d;const h=A2t(c,r);return a(c,h),h}return function(){return i(M2t.apply(null,arguments))}}const Nc=s=>{const t=r=>r[s]||[];return t.isThemeGetter=!0,t},bZe=/^\[(?:([a-z-]+):)?(.+)\]$/i,P2t=/^\d+\/\d+$/,L2t=new Set(["px","full","screen"]),D2t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,R2t=/\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$/,O2t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,F2t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,B2t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,db=s=>vM(s)||L2t.has(s)||P2t.test(s),Ew=s=>gP(s,"length",W2t),vM=s=>!!s&&!Number.isNaN(Number(s)),Wve=s=>gP(s,"number",vM),PD=s=>!!s&&Number.isInteger(Number(s)),z2t=s=>s.endsWith("%")&&vM(s.slice(0,-1)),Ki=s=>bZe.test(s),Aw=s=>D2t.test(s),$2t=new Set(["length","size","percentage"]),U2t=s=>gP(s,$2t,_Ze),q2t=s=>gP(s,"position",_Ze),V2t=new Set(["image","url"]),H2t=s=>gP(s,V2t,Y2t),G2t=s=>gP(s,"",K2t),LD=()=>!0,gP=(s,t,r)=>{const n=bZe.exec(s);return n?n[1]?typeof t=="string"?n[1]===t:t.has(n[1]):r(n[2]):!1},W2t=s=>R2t.test(s)&&!O2t.test(s),_Ze=()=>!1,K2t=s=>F2t.test(s),Y2t=s=>B2t.test(s),Z2t=()=>{const s=Nc("colors"),t=Nc("spacing"),r=Nc("blur"),n=Nc("brightness"),a=Nc("borderColor"),i=Nc("borderRadius"),l=Nc("borderSpacing"),o=Nc("borderWidth"),c=Nc("contrast"),d=Nc("grayscale"),h=Nc("hueRotate"),m=Nc("invert"),x=Nc("gap"),g=Nc("gradientColorStops"),v=Nc("gradientColorStopPositions"),j=Nc("inset"),b=Nc("margin"),N=Nc("opacity"),S=Nc("padding"),T=Nc("saturate"),A=Nc("scale"),P=Nc("sepia"),D=Nc("skew"),B=Nc("space"),z=Nc("translate"),F=()=>["auto","contain","none"],$=()=>["auto","hidden","clip","visible","scroll"],X=()=>["auto",Ki,t],K=()=>[Ki,t],Q=()=>["",db,Ew],Y=()=>["auto",vM,Ki],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],de=()=>["solid","dashed","dotted","double","none"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>["start","end","center","between","around","evenly","stretch"],ie=()=>["","0",Ki],me=()=>["auto","avoid","all","avoid-page","page","left","right","column"],oe=()=>[vM,Ki];return{cacheSize:500,separator:":",theme:{colors:[LD],spacing:[db,Ew],blur:["none","",Aw,Ki],brightness:oe(),borderColor:[s],borderRadius:["none","","full",Aw,Ki],borderSpacing:K(),borderWidth:Q(),contrast:oe(),grayscale:ie(),hueRotate:oe(),invert:ie(),gap:K(),gradientColorStops:[s],gradientColorStopPositions:[z2t,Ew],inset:X(),margin:X(),opacity:oe(),padding:K(),saturate:oe(),scale:oe(),sepia:ie(),skew:oe(),space:K(),translate:K()},classGroups:{aspect:[{aspect:["auto","square","video",Ki]}],container:["container"],columns:[{columns:[Aw]}],"break-after":[{"break-after":me()}],"break-before":[{"break-before":me()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Ki]}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[j]}],"inset-x":[{"inset-x":[j]}],"inset-y":[{"inset-y":[j]}],start:[{start:[j]}],end:[{end:[j]}],top:[{top:[j]}],right:[{right:[j]}],bottom:[{bottom:[j]}],left:[{left:[j]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",PD,Ki]}],basis:[{basis:X()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ki]}],grow:[{grow:ie()}],shrink:[{shrink:ie()}],order:[{order:["first","last","none",PD,Ki]}],"grid-cols":[{"grid-cols":[LD]}],"col-start-end":[{col:["auto",{span:["full",PD,Ki]},Ki]}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":[LD]}],"row-start-end":[{row:["auto",{span:[PD,Ki]},Ki]}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ki]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ki]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...ae()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ae(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ae(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[S]}],px:[{px:[S]}],py:[{py:[S]}],ps:[{ps:[S]}],pe:[{pe:[S]}],pt:[{pt:[S]}],pr:[{pr:[S]}],pb:[{pb:[S]}],pl:[{pl:[S]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[B]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[B]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ki,t]}],"min-w":[{"min-w":[Ki,t,"min","max","fit"]}],"max-w":[{"max-w":[Ki,t,"none","full","min","max","fit","prose",{screen:[Aw]},Aw]}],h:[{h:[Ki,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ki,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ki,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ki,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Aw,Ew]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Wve]}],"font-family":[{font:[LD]}],"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",Ki]}],"line-clamp":[{"line-clamp":["none",vM,Wve]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",db,Ki]}],"list-image":[{"list-image":["none",Ki]}],"list-style-type":[{list:["none","disc","decimal",Ki]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[N]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[N]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...de(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",db,Ew]}],"underline-offset":[{"underline-offset":["auto",db,Ki]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:K()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ki]}],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",Ki]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[N]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),q2t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",U2t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},H2t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[v]}],"gradient-via-pos":[{via:[v]}],"gradient-to-pos":[{to:[v]}],"gradient-from":[{from:[g]}],"gradient-via":[{via:[g]}],"gradient-to":[{to:[g]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[N]}],"border-style":[{border:[...de(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[N]}],"divide-style":[{divide:de()}],"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:["",...de()]}],"outline-offset":[{"outline-offset":[db,Ki]}],"outline-w":[{outline:[db,Ew]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:Q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[N]}],"ring-offset-w":[{"ring-offset":[db,Ew]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",Aw,G2t]}],"shadow-color":[{shadow:[LD]}],opacity:[{opacity:[N]}],"mix-blend":[{"mix-blend":[...ce(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ce()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Aw,Ki]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[T]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[N]}],"backdrop-saturate":[{"backdrop-saturate":[T]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Ki]}],duration:[{duration:oe()}],ease:[{ease:["linear","in","out","in-out",Ki]}],delay:[{delay:oe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ki]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[PD,Ki]}],"translate-x":[{"translate-x":[z]}],"translate-y":[{"translate-y":[z]}],"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",Ki]}],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",Ki]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":K()}],"scroll-mx":[{"scroll-mx":K()}],"scroll-my":[{"scroll-my":K()}],"scroll-ms":[{"scroll-ms":K()}],"scroll-me":[{"scroll-me":K()}],"scroll-mt":[{"scroll-mt":K()}],"scroll-mr":[{"scroll-mr":K()}],"scroll-mb":[{"scroll-mb":K()}],"scroll-ml":[{"scroll-ml":K()}],"scroll-p":[{"scroll-p":K()}],"scroll-px":[{"scroll-px":K()}],"scroll-py":[{"scroll-py":K()}],"scroll-ps":[{"scroll-ps":K()}],"scroll-pe":[{"scroll-pe":K()}],"scroll-pt":[{"scroll-pt":K()}],"scroll-pr":[{"scroll-pr":K()}],"scroll-pb":[{"scroll-pb":K()}],"scroll-pl":[{"scroll-pl":K()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ki]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[db,Ew,Wve]}],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"]}}},X2t=I2t(Z2t);function Bt(...s){return X2t(Ui(s))}function uc(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 sRe(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function H8(s){return s?s.replace(/<[^>]*>/g,""):""}const Q2t=x2t,wZe=k.forwardRef(({className:s,...t},r)=>e.jsx(lZe,{ref:r,className:Bt("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}));wZe.displayName=lZe.displayName;const J2t=V5("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"}}),jZe=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx(cZe,{ref:n,className:Bt(J2t({variant:t}),s),...r}));jZe.displayName=cZe.displayName;const eNt=k.forwardRef(({className:s,...t},r)=>e.jsx(hZe,{ref:r,className:Bt("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}));eNt.displayName=hZe.displayName;const NZe=k.forwardRef(({className:s,...t},r)=>e.jsx(mZe,{ref:r,className:Bt("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"})}));NZe.displayName=mZe.displayName;const kZe=k.forwardRef(({className:s,...t},r)=>e.jsx(dZe,{ref:r,className:Bt("text-sm font-semibold",s),...t}));kZe.displayName=dZe.displayName;const SZe=k.forwardRef(({className:s,...t},r)=>e.jsx(uZe,{ref:r,className:Bt("text-sm opacity-90",s),...t}));SZe.displayName=uZe.displayName;function tNt(){const{toasts:s}=Ea();return e.jsxs(Q2t,{children:[s.map(function({id:t,title:r,description:n,action:a,...i}){return e.jsxs(jZe,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[r&&e.jsx(kZe,{children:r}),n&&e.jsx(SZe,{children:n})]}),a,e.jsx(NZe,{})]},t)}),e.jsx(wZe,{})]})}var rRe=["light","dark"],sNt="(prefers-color-scheme: dark)",rNt=k.createContext(void 0),nNt={setTheme:s=>{},themes:[]},aNt=()=>{var s;return(s=k.useContext(rNt))!=null?s:nNt};k.memo(({forcedTheme:s,storageKey:t,attribute:r,enableSystem:n,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",h=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(v=>`'${v}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,m=a?rRe.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",x=(v,j=!1,b=!0)=>{let N=l?l[v]:v,S=j?v+"|| ''":`'${N}'`,T="";return a&&b&&!j&&rRe.includes(v)&&(T+=`d.style.colorScheme = '${v}';`),r==="class"?j||N?T+=`c.add(${S})`:T+="null":N&&(T+=`d[s](n,${S})`),T},g=s?`!function(){${h}${x(s)}}()`:n?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${sNt}',m=window.matchMedia(t);if(m.media!==t||m.matches){${x("dark")}}else{${x("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${x(l?"x[e]":"e",!0)}}${d?"":"else{"+x(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${x(l?"x[e]":"e",!0)}}else{${x(i,!1,!1)};}${m}}catch(t){}}();`;return k.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:g}})});var iNt=s=>{switch(s){case"success":return cNt;case"info":return uNt;case"warning":return dNt;case"error":return hNt;default:return null}},oNt=Array(12).fill(0),lNt=({visible:s,className:t})=>wt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},wt.createElement("div",{className:"sonner-spinner"},oNt.map((r,n)=>wt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),cNt=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),dNt=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},wt.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),uNt=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),hNt=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),mNt=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},wt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),wt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),fNt=()=>{let[s,t]=wt.useState(document.hidden);return wt.useEffect(()=>{let r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),s},hje=1,pNt=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:hje++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:n}),{...c,...t,id:i,dismissible:o,title:n}):c):this.addToast({title:n,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(r=>{this.subscribers.forEach(n=>n({id:r.id,dismiss:!0}))}),this.subscribers.forEach(r=>r({id:t,dismiss:!0})),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let n;r.loading!==void 0&&(n=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));let a=t instanceof Promise?t:t(),i=n!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],wt.isValidElement(d))i=!1,this.create({id:n,type:"default",message:d});else if(gNt(d)&&!d.ok){i=!1;let h=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,m=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description;this.create({id:n,type:"error",message:h,description:m})}else if(r.success!==void 0){i=!1;let h=typeof r.success=="function"?await r.success(d):r.success,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"success",message:h,description:m})}}).catch(async d=>{if(l=["reject",d],r.error!==void 0){i=!1;let h=typeof r.error=="function"?await r.error(d):r.error,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"error",message:h,description:m})}}).finally(()=>{var d;i&&(this.dismiss(n),n=void 0),(d=r.finally)==null||d.call(r)}),c=()=>new Promise((d,h)=>o.then(()=>l[0]==="reject"?h(l[1]):d(l[1])).catch(h));return typeof n!="string"&&typeof n!="number"?{unwrap:c}:Object.assign(n,{unwrap:c})},this.custom=(t,r)=>{let n=(r==null?void 0:r.id)||hje++;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}},sp=new pNt,xNt=(s,t)=>{let r=(t==null?void 0:t.id)||hje++;return sp.addToast({title:s,...t,id:r}),r},gNt=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",yNt=xNt,vNt=()=>sp.toasts,bNt=()=>sp.getActiveToasts(),ue=Object.assign(yNt,{success:sp.success,info:sp.info,warning:sp.warning,error:sp.error,custom:sp.custom,message:sp.message,promise:sp.promise,dismiss:sp.dismiss,loading:sp.loading},{getHistory:vNt,getToasts:bNt});function _Nt(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))}_Nt(`: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 B$(s){return s.label!==void 0}var wNt=3,jNt="32px",NNt="16px",nRe=4e3,kNt=356,SNt=14,CNt=20,TNt=200;function Ty(...s){return s.filter(Boolean).join(" ")}function ENt(s){let[t,r]=s.split("-"),n=[];return t&&n.push(t),r&&n.push(r),n}var ANt=s=>{var t,r,n,a,i,l,o,c,d,h,m;let{invert:x,toast:g,unstyled:v,interacting:j,setHeights:b,visibleToasts:N,heights:S,index:T,toasts:A,expanded:P,removeToast:D,defaultRichColors:B,closeButton:z,style:F,cancelButtonStyle:$,actionButtonStyle:X,className:K="",descriptionClassName:Q="",duration:Y,position:ne,gap:de,loadingIcon:ce,expandByDefault:ae,classNames:ie,icons:me,closeButtonAriaLabel:oe="Close toast",pauseWhenPageIsHidden:ge}=s,[be,Oe]=wt.useState(null),[Me,Pe]=wt.useState(null),[Ee,$e]=wt.useState(!1),[Se,ze]=wt.useState(!1),[Te,ye]=wt.useState(!1),[ct,ve]=wt.useState(!1),[rt,Re]=wt.useState(!1),[Qe,Ke]=wt.useState(0),[Ce,nt]=wt.useState(0),$t=wt.useRef(g.duration||Y||nRe),lt=wt.useRef(null),it=wt.useRef(null),Nt=T===0,Ft=T+1<=N,at=g.type,Ie=g.dismissible!==!1,et=g.className||"",Dt=g.descriptionClassName||"",Jt=wt.useMemo(()=>S.findIndex(Sr=>Sr.toastId===g.id)||0,[S,g.id]),cs=wt.useMemo(()=>{var Sr;return(Sr=g.closeButton)!=null?Sr:z},[g.closeButton,z]),Ht=wt.useMemo(()=>g.duration||Y||nRe,[g.duration,Y]),dt=wt.useRef(0),Qt=wt.useRef(0),yt=wt.useRef(0),ss=wt.useRef(null),[Is,fs]=ne.split("-"),ar=wt.useMemo(()=>S.reduce((Sr,hn,zn)=>zn>=Jt?Sr:Sr+hn.height,0),[S,Jt]),Er=fNt(),Tr=g.invert||x,Lr=at==="loading";Qt.current=wt.useMemo(()=>Jt*de+ar,[Jt,ar]),wt.useEffect(()=>{$t.current=Ht},[Ht]),wt.useEffect(()=>{$e(!0)},[]),wt.useEffect(()=>{let Sr=it.current;if(Sr){let hn=Sr.getBoundingClientRect().height;return nt(hn),b(zn=>[{toastId:g.id,height:hn,position:g.position},...zn]),()=>b(zn=>zn.filter(Xs=>Xs.toastId!==g.id))}},[b,g.id]),wt.useLayoutEffect(()=>{if(!Ee)return;let Sr=it.current,hn=Sr.style.height;Sr.style.height="auto";let zn=Sr.getBoundingClientRect().height;Sr.style.height=hn,nt(zn),b(Xs=>Xs.find(Ur=>Ur.toastId===g.id)?Xs.map(Ur=>Ur.toastId===g.id?{...Ur,height:zn}:Ur):[{toastId:g.id,height:zn,position:g.position},...Xs])},[Ee,g.title,g.description,b,g.id]);let $r=wt.useCallback(()=>{ze(!0),Ke(Qt.current),b(Sr=>Sr.filter(hn=>hn.toastId!==g.id)),setTimeout(()=>{D(g)},TNt)},[g,D,b,Qt]);wt.useEffect(()=>{if(g.promise&&at==="loading"||g.duration===1/0||g.type==="loading")return;let Sr;return P||j||ge&&Er?(()=>{if(yt.current{var hn;(hn=g.onAutoClose)==null||hn.call(g,g),$r()},$t.current)),()=>clearTimeout(Sr)},[P,j,g,at,ge,Er,$r]),wt.useEffect(()=>{g.delete&&$r()},[$r,g.delete]);function kr(){var Sr,hn,zn;return me!=null&&me.loading?wt.createElement("div",{className:Ty(ie==null?void 0:ie.loader,(Sr=g==null?void 0:g.classNames)==null?void 0:Sr.loader,"sonner-loader"),"data-visible":at==="loading"},me.loading):ce?wt.createElement("div",{className:Ty(ie==null?void 0:ie.loader,(hn=g==null?void 0:g.classNames)==null?void 0:hn.loader,"sonner-loader"),"data-visible":at==="loading"},ce):wt.createElement(lNt,{className:Ty(ie==null?void 0:ie.loader,(zn=g==null?void 0:g.classNames)==null?void 0:zn.loader),visible:at==="loading"})}return wt.createElement("li",{tabIndex:0,ref:it,className:Ty(K,et,ie==null?void 0:ie.toast,(t=g==null?void 0:g.classNames)==null?void 0:t.toast,ie==null?void 0:ie.default,ie==null?void 0:ie[at],(r=g==null?void 0:g.classNames)==null?void 0:r[at]),"data-sonner-toast":"","data-rich-colors":(n=g.richColors)!=null?n:B,"data-styled":!(g.jsx||g.unstyled||v),"data-mounted":Ee,"data-promise":!!g.promise,"data-swiped":rt,"data-removed":Se,"data-visible":Ft,"data-y-position":Is,"data-x-position":fs,"data-index":T,"data-front":Nt,"data-swiping":Te,"data-dismissible":Ie,"data-type":at,"data-invert":Tr,"data-swipe-out":ct,"data-swipe-direction":Me,"data-expanded":!!(P||ae&&Ee),style:{"--index":T,"--toasts-before":T,"--z-index":A.length-T,"--offset":`${Se?Qe:Qt.current}px`,"--initial-height":ae?"auto":`${Ce}px`,...F,...g.style},onDragEnd:()=>{ye(!1),Oe(null),ss.current=null},onPointerDown:Sr=>{Lr||!Ie||(lt.current=new Date,Ke(Qt.current),Sr.target.setPointerCapture(Sr.pointerId),Sr.target.tagName!=="BUTTON"&&(ye(!0),ss.current={x:Sr.clientX,y:Sr.clientY}))},onPointerUp:()=>{var Sr,hn,zn,Xs;if(ct||!Ie)return;ss.current=null;let Ur=Number(((Sr=it.current)==null?void 0:Sr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),xn=Number(((hn=it.current)==null?void 0:hn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),us=new Date().getTime()-((zn=lt.current)==null?void 0:zn.getTime()),pr=be==="x"?Ur:xn,Hr=Math.abs(pr)/us;if(Math.abs(pr)>=CNt||Hr>.11){Ke(Qt.current),(Xs=g.onDismiss)==null||Xs.call(g,g),Pe(be==="x"?Ur>0?"right":"left":xn>0?"down":"up"),$r(),ve(!0),Re(!1);return}ye(!1),Oe(null)},onPointerMove:Sr=>{var hn,zn,Xs,Ur;if(!ss.current||!Ie||((hn=window.getSelection())==null?void 0:hn.toString().length)>0)return;let xn=Sr.clientY-ss.current.y,us=Sr.clientX-ss.current.x,pr=(zn=s.swipeDirections)!=null?zn:ENt(ne);!be&&(Math.abs(us)>1||Math.abs(xn)>1)&&Oe(Math.abs(us)>Math.abs(xn)?"x":"y");let Hr={x:0,y:0};be==="y"?(pr.includes("top")||pr.includes("bottom"))&&(pr.includes("top")&&xn<0||pr.includes("bottom")&&xn>0)&&(Hr.y=xn):be==="x"&&(pr.includes("left")||pr.includes("right"))&&(pr.includes("left")&&us<0||pr.includes("right")&&us>0)&&(Hr.x=us),(Math.abs(Hr.x)>0||Math.abs(Hr.y)>0)&&Re(!0),(Xs=it.current)==null||Xs.style.setProperty("--swipe-amount-x",`${Hr.x}px`),(Ur=it.current)==null||Ur.style.setProperty("--swipe-amount-y",`${Hr.y}px`)}},cs&&!g.jsx?wt.createElement("button",{"aria-label":oe,"data-disabled":Lr,"data-close-button":!0,onClick:Lr||!Ie?()=>{}:()=>{var Sr;$r(),(Sr=g.onDismiss)==null||Sr.call(g,g)},className:Ty(ie==null?void 0:ie.closeButton,(a=g==null?void 0:g.classNames)==null?void 0:a.closeButton)},(i=me==null?void 0:me.close)!=null?i:mNt):null,g.jsx||k.isValidElement(g.title)?g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title:wt.createElement(wt.Fragment,null,at||g.icon||g.promise?wt.createElement("div",{"data-icon":"",className:Ty(ie==null?void 0:ie.icon,(l=g==null?void 0:g.classNames)==null?void 0:l.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||kr():null,g.type!=="loading"?g.icon||(me==null?void 0:me[at])||iNt(at):null):null,wt.createElement("div",{"data-content":"",className:Ty(ie==null?void 0:ie.content,(o=g==null?void 0:g.classNames)==null?void 0:o.content)},wt.createElement("div",{"data-title":"",className:Ty(ie==null?void 0:ie.title,(c=g==null?void 0:g.classNames)==null?void 0:c.title)},typeof g.title=="function"?g.title():g.title),g.description?wt.createElement("div",{"data-description":"",className:Ty(Q,Dt,ie==null?void 0:ie.description,(d=g==null?void 0:g.classNames)==null?void 0:d.description)},typeof g.description=="function"?g.description():g.description):null),k.isValidElement(g.cancel)?g.cancel:g.cancel&&B$(g.cancel)?wt.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||$,onClick:Sr=>{var hn,zn;B$(g.cancel)&&Ie&&((zn=(hn=g.cancel).onClick)==null||zn.call(hn,Sr),$r())},className:Ty(ie==null?void 0:ie.cancelButton,(h=g==null?void 0:g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,k.isValidElement(g.action)?g.action:g.action&&B$(g.action)?wt.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||X,onClick:Sr=>{var hn,zn;B$(g.action)&&((zn=(hn=g.action).onClick)==null||zn.call(hn,Sr),!Sr.defaultPrevented&&$r())},className:Ty(ie==null?void 0:ie.actionButton,(m=g==null?void 0:g.classNames)==null?void 0:m.actionButton)},g.action.label):null))};function aRe(){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 MNt(s,t){let r={};return[s,t].forEach((n,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?NNt:jNt;function c(d){["top","right","bottom","left"].forEach(h=>{r[`${l}-${h}`]=typeof d=="number"?`${d}px`:d})}typeof n=="number"||typeof n=="string"?c(n):typeof n=="object"?["top","right","bottom","left"].forEach(d=>{n[d]===void 0?r[`${l}-${d}`]=o:r[`${l}-${d}`]=typeof n[d]=="number"?`${n[d]}px`:n[d]}):c(o)}),r}var INt=k.forwardRef(function(s,t){let{invert:r,position:n="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:h="light",richColors:m,duration:x,style:g,visibleToasts:v=wNt,toastOptions:j,dir:b=aRe(),gap:N=SNt,loadingIcon:S,icons:T,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:P}=s,[D,B]=wt.useState([]),z=wt.useMemo(()=>Array.from(new Set([n].concat(D.filter(ge=>ge.position).map(ge=>ge.position)))),[D,n]),[F,$]=wt.useState([]),[X,K]=wt.useState(!1),[Q,Y]=wt.useState(!1),[ne,de]=wt.useState(h!=="system"?h:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ce=wt.useRef(null),ae=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ie=wt.useRef(null),me=wt.useRef(!1),oe=wt.useCallback(ge=>{B(be=>{var Oe;return(Oe=be.find(Me=>Me.id===ge.id))!=null&&Oe.delete||sp.dismiss(ge.id),be.filter(({id:Me})=>Me!==ge.id)})},[]);return wt.useEffect(()=>sp.subscribe(ge=>{if(ge.dismiss){B(be=>be.map(Oe=>Oe.id===ge.id?{...Oe,delete:!0}:Oe));return}setTimeout(()=>{$Ye.flushSync(()=>{B(be=>{let Oe=be.findIndex(Me=>Me.id===ge.id);return Oe!==-1?[...be.slice(0,Oe),{...be[Oe],...ge},...be.slice(Oe+1)]:[ge,...be]})})})}),[]),wt.useEffect(()=>{if(h!=="system"){de(h);return}if(h==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?de("dark"):de("light")),typeof window>"u")return;let ge=window.matchMedia("(prefers-color-scheme: dark)");try{ge.addEventListener("change",({matches:be})=>{de(be?"dark":"light")})}catch{ge.addListener(({matches:Oe})=>{try{de(Oe?"dark":"light")}catch(Me){console.error(Me)}})}},[h]),wt.useEffect(()=>{D.length<=1&&K(!1)},[D]),wt.useEffect(()=>{let ge=be=>{var Oe,Me;a.every(Pe=>be[Pe]||be.code===Pe)&&(K(!0),(Oe=ce.current)==null||Oe.focus()),be.code==="Escape"&&(document.activeElement===ce.current||(Me=ce.current)!=null&&Me.contains(document.activeElement))&&K(!1)};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[a]),wt.useEffect(()=>{if(ce.current)return()=>{ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null,me.current=!1)}},[ce.current]),wt.createElement("section",{ref:t,"aria-label":`${A} ${ae}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},z.map((ge,be)=>{var Oe;let[Me,Pe]=ge.split("-");return D.length?wt.createElement("ol",{key:ge,dir:b==="auto"?aRe():b,tabIndex:-1,ref:ce,className:o,"data-sonner-toaster":!0,"data-theme":ne,"data-y-position":Me,"data-lifted":X&&D.length>1&&!i,"data-x-position":Pe,style:{"--front-toast-height":`${((Oe=F[0])==null?void 0:Oe.height)||0}px`,"--width":`${kNt}px`,"--gap":`${N}px`,...g,...MNt(c,d)},onBlur:Ee=>{me.current&&!Ee.currentTarget.contains(Ee.relatedTarget)&&(me.current=!1,ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null))},onFocus:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||me.current||(me.current=!0,ie.current=Ee.relatedTarget)},onMouseEnter:()=>K(!0),onMouseMove:()=>K(!0),onMouseLeave:()=>{Q||K(!1)},onDragEnd:()=>K(!1),onPointerDown:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||Y(!0)},onPointerUp:()=>Y(!1)},D.filter(Ee=>!Ee.position&&be===0||Ee.position===ge).map((Ee,$e)=>{var Se,ze;return wt.createElement(ANt,{key:Ee.id,icons:T,index:$e,toast:Ee,defaultRichColors:m,duration:(Se=j==null?void 0:j.duration)!=null?Se:x,className:j==null?void 0:j.className,descriptionClassName:j==null?void 0:j.descriptionClassName,invert:r,visibleToasts:v,closeButton:(ze=j==null?void 0:j.closeButton)!=null?ze:l,interacting:Q,position:ge,style:j==null?void 0:j.style,unstyled:j==null?void 0:j.unstyled,classNames:j==null?void 0:j.classNames,cancelButtonStyle:j==null?void 0:j.cancelButtonStyle,actionButtonStyle:j==null?void 0:j.actionButtonStyle,removeToast:oe,toasts:D.filter(Te=>Te.position==Ee.position),heights:F.filter(Te=>Te.position==Ee.position),setHeights:$,expandByDefault:i,gap:N,loadingIcon:S,expanded:X,pauseWhenPageIsHidden:P,swipeDirections:s.swipeDirections})})):null}))});const PNt=({...s})=>{const{theme:t="system"}=aNt();return e.jsx(INt,{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 LNt=jB[" useId ".trim().toString()]||(()=>{}),DNt=0;function Qu(s){const[t,r]=k.useState(LNt());return fd(()=>{r(n=>n??String(DNt++))},[s]),t?`radix-${t}`:""}const RNt=["top","right","bottom","left"],b2=Math.min,ox=Math.max,gue=Math.round,z$=Math.floor,Zv=s=>({x:s,y:s}),ONt={left:"right",right:"left",bottom:"top",top:"bottom"};function mje(s,t,r){return ox(s,b2(t,r))}function x_(s,t){return typeof s=="function"?s(t):s}function g_(s){return s.split("-")[0]}function yP(s){return s.split("-")[1]}function p4e(s){return s==="x"?"y":"x"}function x4e(s){return s==="y"?"height":"width"}function Av(s){const t=s[0];return t==="t"||t==="b"?"y":"x"}function g4e(s){return p4e(Av(s))}function FNt(s,t,r){r===void 0&&(r=!1);const n=yP(s),a=g4e(s),i=x4e(a);let l=a==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=yue(l)),[l,yue(l)]}function BNt(s){const t=yue(s);return[fje(s),t,fje(t)]}function fje(s){return s.includes("start")?s.replace("start","end"):s.replace("end","start")}const iRe=["left","right"],oRe=["right","left"],zNt=["top","bottom"],$Nt=["bottom","top"];function UNt(s,t,r){switch(s){case"top":case"bottom":return r?t?oRe:iRe:t?iRe:oRe;case"left":case"right":return t?zNt:$Nt;default:return[]}}function qNt(s,t,r,n){const a=yP(s);let i=UNt(g_(s),r==="start",n);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(fje)))),i}function yue(s){const t=g_(s);return ONt[t]+s.slice(t.length)}function VNt(s){return{top:0,right:0,bottom:0,left:0,...s}}function CZe(s){return typeof s!="number"?VNt(s):{top:s,right:s,bottom:s,left:s}}function vue(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 lRe(s,t,r){let{reference:n,floating:a}=s;const i=Av(t),l=g4e(t),o=x4e(l),c=g_(t),d=i==="y",h=n.x+n.width/2-a.width/2,m=n.y+n.height/2-a.height/2,x=n[o]/2-a[o]/2;let g;switch(c){case"top":g={x:h,y:n.y-a.height};break;case"bottom":g={x:h,y:n.y+n.height};break;case"right":g={x:n.x+n.width,y:m};break;case"left":g={x:n.x-a.width,y:m};break;default:g={x:n.x,y:n.y}}switch(yP(t)){case"start":g[l]-=x*(r&&d?-1:1);break;case"end":g[l]+=x*(r&&d?-1:1);break}return g}async function HNt(s,t){var r;t===void 0&&(t={});const{x:n,y:a,platform:i,rects:l,elements:o,strategy:c}=s,{boundary:d="clippingAncestors",rootBoundary:h="viewport",elementContext:m="floating",altBoundary:x=!1,padding:g=0}=x_(t,s),v=CZe(g),b=o[x?m==="floating"?"reference":"floating":m],N=vue(await i.getClippingRect({element:(r=await(i.isElement==null?void 0:i.isElement(b)))==null||r?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:d,rootBoundary:h,strategy:c})),S=m==="floating"?{x:n,y:a,width:l.floating.width,height:l.floating.height}:l.reference,T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),A=await(i.isElement==null?void 0:i.isElement(T))?await(i.getScale==null?void 0:i.getScale(T))||{x:1,y:1}:{x:1,y:1},P=vue(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:S,offsetParent:T,strategy:c}):S);return{top:(N.top-P.top+v.top)/A.y,bottom:(P.bottom-N.bottom+v.bottom)/A.y,left:(N.left-P.left+v.left)/A.x,right:(P.right-N.right+v.right)/A.x}}const GNt=50,WNt=async(s,t,r)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:l}=r,o=l.detectOverflow?l:{...l,detectOverflow:HNt},c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:h,y:m}=lRe(d,n,c),x=n,g=0;const v={};for(let j=0;j({name:"arrow",options:s,async fn(t){const{x:r,y:n,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:h=0}=x_(s,t)||{};if(d==null)return{};const m=CZe(h),x={x:r,y:n},g=g4e(a),v=x4e(g),j=await l.getDimensions(d),b=g==="y",N=b?"top":"left",S=b?"bottom":"right",T=b?"clientHeight":"clientWidth",A=i.reference[v]+i.reference[g]-x[g]-i.floating[v],P=x[g]-i.reference[g],D=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let B=D?D[T]:0;(!B||!await(l.isElement==null?void 0:l.isElement(D)))&&(B=o.floating[T]||i.floating[v]);const z=A/2-P/2,F=B/2-j[v]/2-1,$=b2(m[N],F),X=b2(m[S],F),K=$,Q=B-j[v]-X,Y=B/2-j[v]/2+z,ne=mje(K,Y,Q),de=!c.arrow&&yP(a)!=null&&Y!==ne&&i.reference[v]/2-(YY<=0)){var X,K;const Y=(((X=i.flip)==null?void 0:X.index)||0)+1,ne=B[Y];if(ne&&(!(m==="alignment"?S!==Av(ne):!1)||$.every(ae=>Av(ae.placement)===S?ae.overflows[0]>0:!0)))return{data:{index:Y,overflows:$},reset:{placement:ne}};let de=(K=$.filter(ce=>ce.overflows[0]<=0).sort((ce,ae)=>ce.overflows[1]-ae.overflows[1])[0])==null?void 0:K.placement;if(!de)switch(g){case"bestFit":{var Q;const ce=(Q=$.filter(ae=>{if(D){const ie=Av(ae.placement);return ie===S||ie==="y"}return!0}).map(ae=>[ae.placement,ae.overflows.filter(ie=>ie>0).reduce((ie,me)=>ie+me,0)]).sort((ae,ie)=>ae[1]-ie[1])[0])==null?void 0:Q[0];ce&&(de=ce);break}case"initialPlacement":de=o;break}if(a!==de)return{reset:{placement:de}}}return{}}}};function cRe(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function dRe(s){return RNt.some(t=>s[t]>=0)}const ZNt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:r,platform:n}=t,{strategy:a="referenceHidden",...i}=x_(s,t);switch(a){case"referenceHidden":{const l=await n.detectOverflow(t,{...i,elementContext:"reference"}),o=cRe(l,r.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:dRe(o)}}}case"escaped":{const l=await n.detectOverflow(t,{...i,altBoundary:!0}),o=cRe(l,r.floating);return{data:{escapedOffsets:o,escaped:dRe(o)}}}default:return{}}}}},TZe=new Set(["left","top"]);async function XNt(s,t){const{placement:r,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),l=g_(r),o=yP(r),c=Av(r)==="y",d=TZe.has(l)?-1:1,h=i&&c?-1:1,m=x_(t,s);let{mainAxis:x,crossAxis:g,alignmentAxis:v}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return o&&typeof v=="number"&&(g=o==="end"?v*-1:v),c?{x:g*h,y:x*d}:{x:x*d,y:g*h}}const QNt=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 XNt(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}}}}},JNt=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:r,y:n,placement:a,platform:i}=t,{mainAxis:l=!0,crossAxis:o=!1,limiter:c={fn:N=>{let{x:S,y:T}=N;return{x:S,y:T}}},...d}=x_(s,t),h={x:r,y:n},m=await i.detectOverflow(t,d),x=Av(g_(a)),g=p4e(x);let v=h[g],j=h[x];if(l){const N=g==="y"?"top":"left",S=g==="y"?"bottom":"right",T=v+m[N],A=v-m[S];v=mje(T,v,A)}if(o){const N=x==="y"?"top":"left",S=x==="y"?"bottom":"right",T=j+m[N],A=j-m[S];j=mje(T,j,A)}const b=c.fn({...t,[g]:v,[x]:j});return{...b,data:{x:b.x-r,y:b.y-n,enabled:{[g]:l,[x]:o}}}}}},ekt=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}=x_(s,t),h={x:r,y:n},m=Av(a),x=p4e(m);let g=h[x],v=h[m];const j=x_(o,t),b=typeof j=="number"?{mainAxis:j,crossAxis:0}:{mainAxis:0,crossAxis:0,...j};if(c){const T=x==="y"?"height":"width",A=i.reference[x]-i.floating[T]+b.mainAxis,P=i.reference[x]+i.reference[T]-b.mainAxis;gP&&(g=P)}if(d){var N,S;const T=x==="y"?"width":"height",A=TZe.has(g_(a)),P=i.reference[m]-i.floating[T]+(A&&((N=l.offset)==null?void 0:N[m])||0)+(A?0:b.crossAxis),D=i.reference[m]+i.reference[T]+(A?0:((S=l.offset)==null?void 0:S[m])||0)-(A?b.crossAxis:0);vD&&(v=D)}return{[x]:g,[m]:v}}}},tkt=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}=x_(s,t),h=await l.detectOverflow(t,d),m=g_(a),x=yP(a),g=Av(a)==="y",{width:v,height:j}=i.floating;let b,N;m==="top"||m==="bottom"?(b=m,N=x===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(N=m,b=x==="end"?"top":"bottom");const S=j-h.top-h.bottom,T=v-h.left-h.right,A=b2(j-h[b],S),P=b2(v-h[N],T),D=!t.middlewareData.shift;let B=A,z=P;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(z=T),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(B=S),D&&!x){const $=ox(h.left,0),X=ox(h.right,0),K=ox(h.top,0),Q=ox(h.bottom,0);g?z=v-2*($!==0||X!==0?$+X:ox(h.left,h.right)):B=j-2*(K!==0||Q!==0?K+Q:ox(h.top,h.bottom))}await c({...t,availableWidth:z,availableHeight:B});const F=await l.getDimensions(o.floating);return v!==F.width||j!==F.height?{reset:{rects:!0}}:{}}}};function Hfe(){return typeof window<"u"}function vP(s){return EZe(s)?(s.nodeName||"").toLowerCase():"#document"}function yx(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function p1(s){var t;return(t=(EZe(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function EZe(s){return Hfe()?s instanceof Node||s instanceof yx(s).Node:!1}function u0(s){return Hfe()?s instanceof Element||s instanceof yx(s).Element:!1}function E_(s){return Hfe()?s instanceof HTMLElement||s instanceof yx(s).HTMLElement:!1}function uRe(s){return!Hfe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof yx(s).ShadowRoot}function AB(s){const{overflow:t,overflowX:r,overflowY:n,display:a}=h0(s);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&a!=="inline"&&a!=="contents"}function skt(s){return/^(table|td|th)$/.test(vP(s))}function Gfe(s){try{if(s.matches(":popover-open"))return!0}catch{}try{return s.matches(":modal")}catch{return!1}}const rkt=/transform|translate|scale|rotate|perspective|filter/,nkt=/paint|layout|strict|content/,nk=s=>!!s&&s!=="none";let Kve;function y4e(s){const t=u0(s)?h0(s):s;return nk(t.transform)||nk(t.translate)||nk(t.scale)||nk(t.rotate)||nk(t.perspective)||!v4e()&&(nk(t.backdropFilter)||nk(t.filter))||rkt.test(t.willChange||"")||nkt.test(t.contain||"")}function akt(s){let t=_2(s);for(;E_(t)&&!lI(t);){if(y4e(t))return t;if(Gfe(t))return null;t=_2(t)}return null}function v4e(){return Kve==null&&(Kve=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Kve}function lI(s){return/^(html|body|#document)$/.test(vP(s))}function h0(s){return yx(s).getComputedStyle(s)}function Wfe(s){return u0(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function _2(s){if(vP(s)==="html")return s;const t=s.assignedSlot||s.parentNode||uRe(s)&&s.host||p1(s);return uRe(t)?t.host:t}function AZe(s){const t=_2(s);return lI(t)?s.ownerDocument?s.ownerDocument.body:s.body:E_(t)&&AB(t)?t:AZe(t)}function G8(s,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const a=AZe(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),l=yx(a);if(i){const o=pje(l);return t.concat(l,l.visualViewport||[],AB(a)?a:[],o&&r?G8(o):[])}else return t.concat(a,G8(a,[],r))}function pje(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function MZe(s){const t=h0(s);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const a=E_(s),i=a?s.offsetWidth:r,l=a?s.offsetHeight:n,o=gue(r)!==i||gue(n)!==l;return o&&(r=i,n=l),{width:r,height:n,$:o}}function b4e(s){return u0(s)?s:s.contextElement}function bM(s){const t=b4e(s);if(!E_(t))return Zv(1);const r=t.getBoundingClientRect(),{width:n,height:a,$:i}=MZe(t);let l=(i?gue(r.width):r.width)/n,o=(i?gue(r.height):r.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const ikt=Zv(0);function IZe(s){const t=yx(s);return!v4e()||!t.visualViewport?ikt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function okt(s,t,r){return t===void 0&&(t=!1),!r||t&&r!==yx(s)?!1:t}function f5(s,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const a=s.getBoundingClientRect(),i=b4e(s);let l=Zv(1);t&&(n?u0(n)&&(l=bM(n)):l=bM(s));const o=okt(i,r,n)?IZe(i):Zv(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,h=a.width/l.x,m=a.height/l.y;if(i){const x=yx(i),g=n&&u0(n)?yx(n):n;let v=x,j=pje(v);for(;j&&n&&g!==v;){const b=bM(j),N=j.getBoundingClientRect(),S=h0(j),T=N.left+(j.clientLeft+parseFloat(S.paddingLeft))*b.x,A=N.top+(j.clientTop+parseFloat(S.paddingTop))*b.y;c*=b.x,d*=b.y,h*=b.x,m*=b.y,c+=T,d+=A,v=yx(j),j=pje(v)}}return vue({width:h,height:m,x:c,y:d})}function Kfe(s,t){const r=Wfe(s).scrollLeft;return t?t.left+r:f5(p1(s)).left+r}function PZe(s,t){const r=s.getBoundingClientRect(),n=r.left+t.scrollLeft-Kfe(s,r),a=r.top+t.scrollTop;return{x:n,y:a}}function lkt(s){let{elements:t,rect:r,offsetParent:n,strategy:a}=s;const i=a==="fixed",l=p1(n),o=t?Gfe(t.floating):!1;if(n===l||o&&i)return r;let c={scrollLeft:0,scrollTop:0},d=Zv(1);const h=Zv(0),m=E_(n);if((m||!m&&!i)&&((vP(n)!=="body"||AB(l))&&(c=Wfe(n)),m)){const g=f5(n);d=bM(n),h.x=g.x+n.clientLeft,h.y=g.y+n.clientTop}const x=l&&!m&&!i?PZe(l,c):Zv(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+h.x+x.x,y:r.y*d.y-c.scrollTop*d.y+h.y+x.y}}function ckt(s){return Array.from(s.getClientRects())}function dkt(s){const t=p1(s),r=Wfe(s),n=s.ownerDocument.body,a=ox(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=ox(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let l=-r.scrollLeft+Kfe(s);const o=-r.scrollTop;return h0(n).direction==="rtl"&&(l+=ox(t.clientWidth,n.clientWidth)-a),{width:a,height:i,x:l,y:o}}const hRe=25;function ukt(s,t){const r=yx(s),n=p1(s),a=r.visualViewport;let i=n.clientWidth,l=n.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const h=v4e();(!h||h&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}const d=Kfe(n);if(d<=0){const h=n.ownerDocument,m=h.body,x=getComputedStyle(m),g=h.compatMode==="CSS1Compat"&&parseFloat(x.marginLeft)+parseFloat(x.marginRight)||0,v=Math.abs(n.clientWidth-m.clientWidth-g);v<=hRe&&(i-=v)}else d<=hRe&&(i+=d);return{width:i,height:l,x:o,y:c}}function hkt(s,t){const r=f5(s,!0,t==="fixed"),n=r.top+s.clientTop,a=r.left+s.clientLeft,i=E_(s)?bM(s):Zv(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 mRe(s,t,r){let n;if(t==="viewport")n=ukt(s,r);else if(t==="document")n=dkt(p1(s));else if(u0(t))n=hkt(t,r);else{const a=IZe(s);n={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return vue(n)}function LZe(s,t){const r=_2(s);return r===t||!u0(r)||lI(r)?!1:h0(r).position==="fixed"||LZe(r,t)}function mkt(s,t){const r=t.get(s);if(r)return r;let n=G8(s,[],!1).filter(o=>u0(o)&&vP(o)!=="body"),a=null;const i=h0(s).position==="fixed";let l=i?_2(s):s;for(;u0(l)&&!lI(l);){const o=h0(l),c=y4e(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&(a.position==="absolute"||a.position==="fixed")||AB(l)&&!c&&LZe(s,l))?n=n.filter(h=>h!==l):a=o,l=_2(l)}return t.set(s,n),n}function fkt(s){let{element:t,boundary:r,rootBoundary:n,strategy:a}=s;const l=[...r==="clippingAncestors"?Gfe(t)?[]:mkt(t,this._c):[].concat(r),n],o=mRe(t,l[0],a);let c=o.top,d=o.right,h=o.bottom,m=o.left;for(let x=1;x{l(!1,1e-7)},1e3)}B===1&&!RZe(d,s.getBoundingClientRect())&&l(),A=!1}try{r=new IntersectionObserver(P,{...T,root:a.ownerDocument})}catch{r=new IntersectionObserver(P,T)}r.observe(s)}return l(!0),i}function _kt(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=b4e(s),h=a||i?[...d?G8(d):[],...t?G8(t):[]]:[];h.forEach(N=>{a&&N.addEventListener("scroll",r,{passive:!0}),i&&N.addEventListener("resize",r)});const m=d&&o?bkt(d,r):null;let x=-1,g=null;l&&(g=new ResizeObserver(N=>{let[S]=N;S&&S.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(x),x=requestAnimationFrame(()=>{var T;(T=g)==null||T.observe(t)})),r()}),d&&!c&&g.observe(d),t&&g.observe(t));let v,j=c?f5(s):null;c&&b();function b(){const N=f5(s);j&&!RZe(j,N)&&r(),j=N,v=requestAnimationFrame(b)}return r(),()=>{var N;h.forEach(S=>{a&&S.removeEventListener("scroll",r),i&&S.removeEventListener("resize",r)}),m==null||m(),(N=g)==null||N.disconnect(),g=null,c&&cancelAnimationFrame(v)}}const wkt=QNt,jkt=JNt,Nkt=YNt,kkt=tkt,Skt=ZNt,pRe=KNt,Ckt=ekt,Tkt=(s,t,r)=>{const n=new Map,a={platform:vkt,...r},i={...a.platform,_c:n};return WNt(s,t,{...a,platform:i})};var Ekt=typeof document<"u",Akt=function(){},ode=Ekt?k.useLayoutEffect:Akt;function bue(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(!bue(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)&&!bue(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function OZe(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function xRe(s,t){const r=OZe(s);return Math.round(t*r)/r}function Zve(s){const t=k.useRef(s);return ode(()=>{t.current=s}),t}function Mkt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[h,m]=k.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[x,g]=k.useState(n);bue(x,n)||g(n);const[v,j]=k.useState(null),[b,N]=k.useState(null),S=k.useCallback(ae=>{ae!==D.current&&(D.current=ae,j(ae))},[]),T=k.useCallback(ae=>{ae!==B.current&&(B.current=ae,N(ae))},[]),A=i||v,P=l||b,D=k.useRef(null),B=k.useRef(null),z=k.useRef(h),F=c!=null,$=Zve(c),X=Zve(a),K=Zve(d),Q=k.useCallback(()=>{if(!D.current||!B.current)return;const ae={placement:t,strategy:r,middleware:x};X.current&&(ae.platform=X.current),Tkt(D.current,B.current,ae).then(ie=>{const me={...ie,isPositioned:K.current!==!1};Y.current&&!bue(z.current,me)&&(z.current=me,pf.flushSync(()=>{m(me)}))})},[x,t,r,X,K]);ode(()=>{d===!1&&z.current.isPositioned&&(z.current.isPositioned=!1,m(ae=>({...ae,isPositioned:!1})))},[d]);const Y=k.useRef(!1);ode(()=>(Y.current=!0,()=>{Y.current=!1}),[]),ode(()=>{if(A&&(D.current=A),P&&(B.current=P),A&&P){if($.current)return $.current(A,P,Q);Q()}},[A,P,Q,$,F]);const ne=k.useMemo(()=>({reference:D,floating:B,setReference:S,setFloating:T}),[S,T]),de=k.useMemo(()=>({reference:A,floating:P}),[A,P]),ce=k.useMemo(()=>{const ae={position:r,left:0,top:0};if(!de.floating)return ae;const ie=xRe(de.floating,h.x),me=xRe(de.floating,h.y);return o?{...ae,transform:"translate("+ie+"px, "+me+"px)",...OZe(de.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:ie,top:me}},[r,o,de.floating,h.x,h.y]);return k.useMemo(()=>({...h,update:Q,refs:ne,elements:de,floatingStyles:ce}),[h,Q,ne,de,ce])}const Ikt=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?pRe({element:n.current,padding:a}).fn(r):{}:n?pRe({element:n,padding:a}).fn(r):{}}}},Pkt=(s,t)=>{const r=wkt(s);return{name:r.name,fn:r.fn,options:[s,t]}},Lkt=(s,t)=>{const r=jkt(s);return{name:r.name,fn:r.fn,options:[s,t]}},Dkt=(s,t)=>({fn:Ckt(s).fn,options:[s,t]}),Rkt=(s,t)=>{const r=Nkt(s);return{name:r.name,fn:r.fn,options:[s,t]}},Okt=(s,t)=>{const r=kkt(s);return{name:r.name,fn:r.fn,options:[s,t]}},Fkt=(s,t)=>{const r=Skt(s);return{name:r.name,fn:r.fn,options:[s,t]}},Bkt=(s,t)=>{const r=Ikt(s);return{name:r.name,fn:r.fn,options:[s,t]}};var zkt="Arrow",FZe=k.forwardRef((s,t)=>{const{children:r,width:n=10,height:a=5,...i}=s;return e.jsx(pn.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"})})});FZe.displayName=zkt;var $kt=FZe;function MB(s){const[t,r]=k.useState(void 0);return fd(()=>{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 _4e="Popper",[BZe,x1]=yd(_4e),[Ukt,zZe]=BZe(_4e),$Ze=s=>{const{__scopePopper:t,children:r}=s,[n,a]=k.useState(null),[i,l]=k.useState(void 0);return e.jsx(Ukt,{scope:t,anchor:n,onAnchorChange:a,placementState:i,setPlacementState:l,children:r})};$Ze.displayName=_4e;var UZe="PopperAnchor",qZe=k.forwardRef((s,t)=>{const{__scopePopper:r,virtualRef:n,...a}=s,i=zZe(UZe,r),l=k.useRef(null),o=i.onAnchorChange,c=k.useCallback(v=>{l.current=v,v&&o(v)},[o]),d=Qa(t,c),h=k.useRef(null);k.useEffect(()=>{if(!n)return;const v=h.current;h.current=n.current,v!==h.current&&o(h.current)});const m=i.placementState&&j4e(i.placementState),x=m==null?void 0:m[0],g=m==null?void 0:m[1];return n?null:e.jsx(pn.div,{"data-radix-popper-side":x,"data-radix-popper-align":g,...a,ref:d})});qZe.displayName=UZe;var w4e="PopperContent",[qkt,Vkt]=BZe(w4e),VZe=k.forwardRef((s,t)=>{var $e,Se,ze,Te,ye,ct;const{__scopePopper:r,side:n="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d,collisionPadding:h=0,sticky:m="partial",hideWhenDetached:x=!1,updatePositionStrategy:g="optimized",onPlaced:v,...j}=s,b=zZe(w4e,r),[N,S]=k.useState(null),T=Qa(t,ve=>S(ve)),[A,P]=k.useState(null),D=MB(A),B=(D==null?void 0:D.width)??0,z=(D==null?void 0:D.height)??0,F=n+(i!=="center"?"-"+i:""),$=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},X=d?Array.isArray(d)?d:[d]:void 0,K=X!==void 0&&X.length>0,Q={padding:$,boundary:X==null?void 0:X.filter(Gkt),altBoundary:K},{refs:Y,floatingStyles:ne,placement:de,isPositioned:ce,middlewareData:ae}=Mkt({strategy:"fixed",placement:F,whileElementsMounted:(...ve)=>_kt(...ve,{animationFrame:g==="always"}),elements:{reference:b.anchor},middleware:[Pkt({mainAxis:a+z,alignmentAxis:l}),c&&Lkt({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?Dkt():void 0,...Q}),c&&Rkt({...Q}),Okt({...Q,apply:({elements:ve,rects:rt,availableWidth:Re,availableHeight:Qe})=>{const{width:Ke,height:Ce}=rt.reference,nt=ve.floating.style;nt.setProperty("--radix-popper-available-width",`${Re}px`),nt.setProperty("--radix-popper-available-height",`${Qe}px`),nt.setProperty("--radix-popper-anchor-width",`${Ke}px`),nt.setProperty("--radix-popper-anchor-height",`${Ce}px`)}}),A&&Bkt({element:A,padding:o}),Wkt({arrowWidth:B,arrowHeight:z}),x&&Fkt({strategy:"referenceHidden",...Q})]}),ie=b.setPlacementState;fd(()=>(ie(de),()=>{ie(void 0)}),[de,ie]);const[me,oe]=j4e(de),ge=Ld(v);fd(()=>{ce&&(ge==null||ge())},[ce,ge]);const be=($e=ae.arrow)==null?void 0:$e.x,Oe=(Se=ae.arrow)==null?void 0:Se.y,Me=((ze=ae.arrow)==null?void 0:ze.centerOffset)!==0,[Pe,Ee]=k.useState();return fd(()=>{N&&Ee(window.getComputedStyle(N).zIndex)},[N]),e.jsx("div",{ref:Y.setFloating,"data-radix-popper-content-wrapper":"",style:{...ne,transform:ce?ne.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Pe,"--radix-popper-transform-origin":[(Te=ae.transformOrigin)==null?void 0:Te.x,(ye=ae.transformOrigin)==null?void 0:ye.y].join(" "),...((ct=ae.hide)==null?void 0:ct.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(qkt,{scope:r,placedSide:me,placedAlign:oe,onArrowChange:P,arrowX:be,arrowY:Oe,shouldHideArrow:Me,children:e.jsx(pn.div,{"data-side":me,"data-align":oe,...j,ref:T,style:{...j.style,animation:ce?void 0:"none"}})})})});VZe.displayName=w4e;var HZe="PopperArrow",Hkt={top:"bottom",right:"left",bottom:"top",left:"right"},GZe=k.forwardRef(function(t,r){const{__scopePopper:n,...a}=t,i=Vkt(HZe,n),l=Hkt[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($kt,{...a,ref:r,style:{...a.style,display:"block"}})})});GZe.displayName=HZe;function Gkt(s){return s!==null}var Wkt=s=>({name:"transformOrigin",options:s,fn(t){var b,N,S;const{placement:r,rects:n,middlewareData:a}=t,l=((b=a.arrow)==null?void 0:b.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,h]=j4e(r),m={start:"0%",center:"50%",end:"100%"}[h],x=(((N=a.arrow)==null?void 0:N.x)??0)+o/2,g=(((S=a.arrow)==null?void 0:S.y)??0)+c/2;let v="",j="";return d==="bottom"?(v=l?m:`${x}px`,j=`${-c}px`):d==="top"?(v=l?m:`${x}px`,j=`${n.floating.height+c}px`):d==="right"?(v=`${-c}px`,j=l?m:`${g}px`):d==="left"&&(v=`${n.floating.width+c}px`,j=l?m:`${g}px`),{data:{x:v,y:j}}}});function j4e(s){const[t,r="center"]=s.split("-");return[t,r]}var IB=$Ze,bP=qZe,PB=VZe,LB=GZe,[Yfe]=yd("Tooltip",[x1]),Zfe=x1(),WZe="TooltipProvider",Kkt=700,xje="tooltip.open",[Ykt,N4e]=Yfe(WZe),KZe=s=>{const{__scopeTooltip:t,delayDuration:r=Kkt,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=s,l=k.useRef(!0),o=k.useRef(!1),c=k.useRef(0);return k.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(Ykt,{scope:t,isOpenDelayedRef:l,delayDuration:r,onOpen:k.useCallback(()=>{n<=0||(window.clearTimeout(c.current),l.current=!1)},[n]),onClose:k.useCallback(()=>{n<=0||(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})};KZe.displayName=WZe;var W8="Tooltip",[Zkt,Xfe]=Yfe(W8),YZe=s=>{const{__scopeTooltip:t,children:r,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=N4e(W8,s.__scopeTooltip),d=Zfe(t),[h,m]=k.useState(null),x=Qu(),g=k.useRef(0),v=l??c.disableHoverableContent,j=o??c.delayDuration,b=k.useRef(!1),[N,S]=Lh({prop:n,defaultProp:a??!1,onChange:B=>{B?(c.onOpen(),document.dispatchEvent(new CustomEvent(xje))):c.onClose(),i==null||i(B)},caller:W8}),T=k.useMemo(()=>N?b.current?"delayed-open":"instant-open":"closed",[N]),A=k.useCallback(()=>{window.clearTimeout(g.current),g.current=0,b.current=!1,S(!0)},[S]),P=k.useCallback(()=>{window.clearTimeout(g.current),g.current=0,S(!1)},[S]),D=k.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{b.current=!0,S(!0),g.current=0},j)},[j,S]);return k.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),e.jsx(IB,{...d,children:e.jsx(Zkt,{scope:t,contentId:x,open:N,stateAttribute:T,trigger:h,onTriggerChange:m,onTriggerEnter:k.useCallback(()=>{c.isOpenDelayedRef.current?D():A()},[c.isOpenDelayedRef,D,A]),onTriggerLeave:k.useCallback(()=>{v?P():(window.clearTimeout(g.current),g.current=0)},[P,v]),onOpen:A,onClose:P,disableHoverableContent:v,children:r})})};YZe.displayName=W8;var gje="TooltipTrigger",ZZe=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Xfe(gje,r),i=N4e(gje,r),l=Zfe(r),o=k.useRef(null),c=Qa(t,o,a.onTriggerChange),d=k.useRef(!1),h=k.useRef(!1),m=k.useCallback(()=>d.current=!1,[]);return k.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(bP,{asChild:!0,...l,children:e.jsx(pn.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...n,ref:c,onPointerMove:Or(s.onPointerMove,x=>{x.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),h.current=!0)}),onPointerLeave:Or(s.onPointerLeave,()=>{a.onTriggerLeave(),h.current=!1}),onPointerDown:Or(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:Or(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:Or(s.onBlur,a.onClose),onClick:Or(s.onClick,a.onClose)})})});ZZe.displayName=gje;var Xkt="TooltipPortal",[IUs,Qkt]=Yfe(Xkt,{forceMount:void 0}),cI="TooltipContent",XZe=k.forwardRef((s,t)=>{const r=Qkt(cI,s.__scopeTooltip),{forceMount:n=r.forceMount,side:a="top",...i}=s,l=Xfe(cI,s.__scopeTooltip);return e.jsx(qd,{present:n||l.open,children:l.disableHoverableContent?e.jsx(QZe,{side:a,...i,ref:t}):e.jsx(Jkt,{side:a,...i,ref:t})})}),Jkt=k.forwardRef((s,t)=>{const r=Xfe(cI,s.__scopeTooltip),n=N4e(cI,s.__scopeTooltip),a=k.useRef(null),i=Qa(t,a),[l,o]=k.useState(null),{trigger:c,onClose:d}=r,h=a.current,{onPointerInTransitChange:m}=n,x=k.useCallback(()=>{o(null),m(!1)},[m]),g=k.useCallback((v,j)=>{const b=v.currentTarget,N={x:v.clientX,y:v.clientY},S=nSt(N,b.getBoundingClientRect()),T=aSt(N,S),A=iSt(j.getBoundingClientRect()),P=lSt([...T,...A]);o(P),m(!0)},[m]);return k.useEffect(()=>()=>x(),[x]),k.useEffect(()=>{if(c&&h){const v=b=>g(b,h),j=b=>g(b,c);return c.addEventListener("pointerleave",v),h.addEventListener("pointerleave",j),()=>{c.removeEventListener("pointerleave",v),h.removeEventListener("pointerleave",j)}}},[c,h,g,x]),k.useEffect(()=>{if(l){const v=j=>{const b=j.target,N={x:j.clientX,y:j.clientY},S=(c==null?void 0:c.contains(b))||(h==null?void 0:h.contains(b)),T=!oSt(N,l);S?x():T&&(x(),d())};return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[c,h,l,d,x]),e.jsx(QZe,{...s,ref:i})}),[eSt,tSt]=Yfe(W8,{isInside:!1}),sSt=VYe("TooltipContent"),QZe=k.forwardRef((s,t)=>{const{__scopeTooltip:r,children:n,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=Xfe(cI,r),d=Zfe(r),{onClose:h}=c;return k.useEffect(()=>(document.addEventListener(xje,h),()=>document.removeEventListener(xje,h)),[h]),k.useEffect(()=>{if(c.trigger){const m=x=>{x.target instanceof Node&&x.target.contains(c.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[c.trigger,h]),e.jsx(F2,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:m=>m.preventDefault(),onDismiss:h,children:e.jsxs(PB,{"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(sSt,{children:n}),e.jsx(eSt,{scope:r,isInside:!0,children:e.jsx(Qjt,{id:c.contentId,role:"tooltip",children:a||n})})]})})});XZe.displayName=cI;var JZe="TooltipArrow",rSt=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Zfe(r);return tSt(JZe,r).isInside?null:e.jsx(LB,{...a,...n,ref:t})});rSt.displayName=JZe;function nSt(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 aSt(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 iSt(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 oSt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=x>n&&r<(m-d)*(n-h)/(x-h)+d&&(a=!a)}return a}function lSt(s){const t=s.slice();return t.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),cSt(t)}function cSt(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 dSt=KZe,uSt=YZe,hSt=ZZe,eXe=XZe;const A_=dSt,hc=uSt,mc=hSt,Wl=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(eXe,{ref:n,sideOffset:t,className:Bt("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}));Wl.displayName=eXe.displayName;var _P=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(){}},a3,gj,UM,gWe,mSt=(gWe=class extends _P{constructor(){super();Ua(this,a3);Ua(this,gj);Ua(this,UM);Zn(this,UM,t=>{if(typeof window<"u"&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Ts(this,gj)||this.setEventListener(Ts(this,UM))}onUnsubscribe(){var t;this.hasListeners()||((t=Ts(this,gj))==null||t.call(this),Zn(this,gj,void 0))}setEventListener(t){var r;Zn(this,UM,t),(r=Ts(this,gj))==null||r.call(this),Zn(this,gj,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Ts(this,a3)!==t&&(Zn(this,a3,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Ts(this,a3)=="boolean"?Ts(this,a3):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},a3=new WeakMap,gj=new WeakMap,UM=new WeakMap,gWe),k4e=new mSt,fSt={setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s),setInterval:(s,t)=>setInterval(s,t),clearInterval:s=>clearInterval(s)},yj,fCe,yWe,pSt=(yWe=class{constructor(){Ua(this,yj,fSt);Ua(this,fCe,!1)}setTimeoutProvider(s){Zn(this,yj,s)}setTimeout(s,t){return Ts(this,yj).setTimeout(s,t)}clearTimeout(s){Ts(this,yj).clearTimeout(s)}setInterval(s,t){return Ts(this,yj).setInterval(s,t)}clearInterval(s){Ts(this,yj).clearInterval(s)}},yj=new WeakMap,fCe=new WeakMap,yWe),$4=new pSt;function xSt(s){setTimeout(s,0)}var gSt=typeof window>"u"||"Deno"in globalThis;function hf(){}function ySt(s,t){return typeof s=="function"?s(t):s}function yje(s){return typeof s=="number"&&s>=0&&s!==1/0}function tXe(s,t){return Math.max(s+(t||0)-Date.now(),0)}function n2(s,t){return typeof s=="function"?s(t):s}function rx(s,t){return typeof s=="function"?s(t):s}function gRe(s,t){const{type:r="all",exact:n,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(n){if(t.queryHash!==S4e(l,t.options))return!1}else if(!K8(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 yRe(s,t){const{exact:r,status:n,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(r){if(p5(t.options.mutationKey)!==p5(i))return!1}else if(!K8(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||a&&!a(t))}function S4e(s,t){return((t==null?void 0:t.queryKeyHashFn)||p5)(s)}function p5(s){return JSON.stringify(s,(t,r)=>vje(r)?Object.keys(r).sort().reduce((n,a)=>(n[a]=r[a],n),{}):r)}function K8(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(r=>K8(s[r],t[r])):!1}var vSt=Object.prototype.hasOwnProperty;function sXe(s,t,r=0){if(s===t)return s;if(r>500)return t;const n=vRe(s)&&vRe(t);if(!n&&!(vje(s)&&vje(t)))return t;const i=(n?s:Object.keys(s)).length,l=n?t:Object.keys(t),o=l.length,c=n?new Array(o):{};let d=0;for(let h=0;h{$4.setTimeout(t,s)})}function bje(s,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(s,t):r.structuralSharing!==!1?sXe(s,t):t}function _St(s,t,r=0){const n=[...s,t];return r&&n.length>r?n.slice(1):n}function wSt(s,t,r=0){const n=[t,...s];return r&&n.length>r?n.slice(0,-1):n}var C4e=Symbol();function rXe(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===C4e?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function T4e(s,t){return typeof s=="function"?s(...t):!!s}function jSt(s,t,r){let n=!1,a;return Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(a??(a=t()),n||(n=!0,a.aborted?r():a.addEventListener("abort",r,{once:!0})),a)}),s}var Y8=(()=>{let s=()=>gSt;return{isServer(){return s()},setIsServer(t){s=t}}})();function _je(){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}var NSt=xSt;function kSt(){let s=[],t=0,r=o=>{o()},n=o=>{o()},a=NSt;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 Uu=kSt(),qM,vj,VM,vWe,SSt=(vWe=class extends _P{constructor(){super();Ua(this,qM,!0);Ua(this,vj);Ua(this,VM);Zn(this,VM,t=>{if(typeof window<"u"&&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(){Ts(this,vj)||this.setEventListener(Ts(this,VM))}onUnsubscribe(){var t;this.hasListeners()||((t=Ts(this,vj))==null||t.call(this),Zn(this,vj,void 0))}setEventListener(t){var r;Zn(this,VM,t),(r=Ts(this,vj))==null||r.call(this),Zn(this,vj,t(this.setOnline.bind(this)))}setOnline(t){Ts(this,qM)!==t&&(Zn(this,qM,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Ts(this,qM)}},qM=new WeakMap,vj=new WeakMap,VM=new WeakMap,vWe),wue=new SSt;function CSt(s){return Math.min(1e3*2**s,3e4)}function nXe(s){return(s??"online")==="online"?wue.isOnline():!0}var wje=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function aXe(s){let t=!1,r=0,n;const a=_je(),i=()=>a.status!=="pending",l=j=>{var b;if(!i()){const N=new wje(j);x(N),(b=s.onCancel)==null||b.call(s,N)}},o=()=>{t=!0},c=()=>{t=!1},d=()=>k4e.isFocused()&&(s.networkMode==="always"||wue.isOnline())&&s.canRun(),h=()=>nXe(s.networkMode)&&s.canRun(),m=j=>{i()||(n==null||n(),a.resolve(j))},x=j=>{i()||(n==null||n(),a.reject(j))},g=()=>new Promise(j=>{var b;n=N=>{(i()||d())&&j(N)},(b=s.onPause)==null||b.call(s)}).then(()=>{var j;n=void 0,i()||(j=s.onContinue)==null||j.call(s)}),v=()=>{if(i())return;let j;const b=r===0?s.initialPromise:void 0;try{j=b??s.fn()}catch(N){j=Promise.reject(N)}Promise.resolve(j).then(m).catch(N=>{var D;if(i())return;const S=s.retry??(Y8.isServer()?0:3),T=s.retryDelay??CSt,A=typeof T=="function"?T(r,N):T,P=S===!0||typeof S=="number"&&rd()?void 0:g()).then(()=>{t?x(N):v()})})};return{promise:a,status:()=>a.status,cancel:l,continue:()=>(n==null||n(),a),cancelRetry:o,continueRetry:c,canStart:h,start:()=>(h()?v():g().then(v),a)}}var i3,bWe,iXe=(bWe=class{constructor(){Ua(this,i3)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yje(this.gcTime)&&Zn(this,i3,$4.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(Y8.isServer()?1/0:5*60*1e3))}clearGcTimeout(){Ts(this,i3)!==void 0&&($4.clearTimeout(Ts(this,i3)),Zn(this,i3,void 0))}},i3=new WeakMap,bWe);function TSt(s){return{onFetch:(t,r)=>{var h,m,x,g,v;const n=t.options,a=(x=(m=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,i=((g=t.state.data)==null?void 0:g.pages)||[],l=((v=t.state.data)==null?void 0:v.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let j=!1;const b=T=>{jSt(T,()=>t.signal,()=>j=!0)},N=rXe(t.options,t.fetchOptions),S=async(T,A,P)=>{if(j)return Promise.reject(t.signal.reason);if(A==null&&T.pages.length)return Promise.resolve(T);const B=(()=>{const X={client:t.client,queryKey:t.queryKey,pageParam:A,direction:P?"backward":"forward",meta:t.options.meta};return b(X),X})(),z=await N(B),{maxPages:F}=t.options,$=P?wSt:_St;return{pages:$(T.pages,z,F),pageParams:$(T.pageParams,A,F)}};if(a&&i.length){const T=a==="backward",A=T?oXe:jje,P={pages:i,pageParams:l},D=A(n,P);o=await S(P,D,T)}else{const T=s??i.length;do{const A=c===0?l[0]??n.initialPageParam:jje(n,o);if(c>0&&A==null)break;o=await S(o,A),c++}while(c{var j,b;return(b=(j=t.options).persister)==null?void 0:b.call(j,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=d}}}function jje(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 oXe(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 ESt(s,t){return t?jje(s,t)!=null:!1}function ASt(s,t){return!t||!s.getPreviousPageParam?!1:oXe(s,t)!=null}var HM,o3,GM,wg,l3,xh,gB,c3,sx,lXe,vb,_We,MSt=(_We=class extends iXe{constructor(t){super();Ua(this,sx);Ua(this,HM);Ua(this,o3);Ua(this,GM);Ua(this,wg);Ua(this,l3);Ua(this,xh);Ua(this,gB);Ua(this,c3);Zn(this,c3,!1),Zn(this,gB,t.defaultOptions),this.setOptions(t.options),this.observers=[],Zn(this,l3,t.client),Zn(this,wg,Ts(this,l3).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Zn(this,o3,wRe(this.options)),this.state=t.state??Ts(this,o3),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Ts(this,HM)}get promise(){var t;return(t=Ts(this,xh))==null?void 0:t.promise}setOptions(t){if(this.options={...Ts(this,gB),...t},t!=null&&t._type&&Zn(this,HM,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=wRe(this.options);r.data!==void 0&&(this.setState(_Re(r.data,r.dataUpdatedAt)),Zn(this,o3,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Ts(this,wg).remove(this)}setData(t,r){const n=bje(this.state.data,t,this.options);return Wi(this,sx,vb).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t){Wi(this,sx,vb).call(this,{type:"setState",state:t})}cancel(t){var n,a;const r=(n=Ts(this,xh))==null?void 0:n.promise;return(a=Ts(this,xh))==null||a.cancel(t),r?r.then(hf).catch(hf):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Ts(this,o3)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>rx(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===C4e||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>n2(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:!tXe(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Ts(this,xh))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Ts(this,xh))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Ts(this,wg).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Ts(this,xh)&&(Ts(this,c3)||Wi(this,sx,lXe).call(this)?Ts(this,xh).cancel({revert:!0}):Ts(this,xh).cancelRetry()),this.scheduleGc()),Ts(this,wg).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Wi(this,sx,vb).call(this,{type:"invalidate"})}async fetch(t,r){var d,h,m,x,g,v,j,b,N,S,T;if(this.state.fetchStatus!=="idle"&&((d=Ts(this,xh))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Ts(this,xh))return Ts(this,xh).continueRetry(),Ts(this,xh).promise}if(t&&this.setOptions(t),!this.options.queryFn){const A=this.observers.find(P=>P.options.queryFn);A&&this.setOptions(A.options)}const n=new AbortController,a=A=>{Object.defineProperty(A,"signal",{enumerable:!0,get:()=>(Zn(this,c3,!0),n.signal)})},i=()=>{const A=rXe(this.options,r),D=(()=>{const B={client:Ts(this,l3),queryKey:this.queryKey,meta:this.meta};return a(B),B})();return Zn(this,c3,!1),this.options.persister?this.options.persister(A,D,this):A(D)},o=(()=>{const A={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Ts(this,l3),state:this.state,fetchFn:i};return a(A),A})(),c=Ts(this,HM)==="infinite"?TSt(this.options.pages):this.options.behavior;c==null||c.onFetch(o,this),Zn(this,GM,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&Wi(this,sx,vb).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta}),Zn(this,xh,aXe({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,onCancel:A=>{A instanceof wje&&A.revert&&this.setState({...Ts(this,GM),fetchStatus:"idle"}),n.abort()},onFail:(A,P)=>{Wi(this,sx,vb).call(this,{type:"failed",failureCount:A,error:P})},onPause:()=>{Wi(this,sx,vb).call(this,{type:"pause"})},onContinue:()=>{Wi(this,sx,vb).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const A=await Ts(this,xh).start();if(A===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(A),(g=(x=Ts(this,wg).config).onSuccess)==null||g.call(x,A,this),(j=(v=Ts(this,wg).config).onSettled)==null||j.call(v,A,this.state.error,this),A}catch(A){if(A instanceof wje){if(A.silent)return Ts(this,xh).promise;if(A.revert){if(this.state.data===void 0)throw A;return this.state.data}}throw Wi(this,sx,vb).call(this,{type:"error",error:A}),(N=(b=Ts(this,wg).config).onError)==null||N.call(b,A,this),(T=(S=Ts(this,wg).config).onSettled)==null||T.call(S,this.state.data,A,this),A}finally{this.scheduleGc()}}},HM=new WeakMap,o3=new WeakMap,GM=new WeakMap,wg=new WeakMap,l3=new WeakMap,xh=new WeakMap,gB=new WeakMap,c3=new WeakMap,sx=new WeakSet,lXe=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},vb=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,...cXe(n.data,this.options),fetchMeta:t.meta??null};case"success":const a={...n,..._Re(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Zn(this,GM,t.manual?a:void 0),a;case"error":const i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),Uu.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Ts(this,wg).notify({query:this,type:"updated",action:t})})},_We);function cXe(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:nXe(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function _Re(s,t){return{data:s,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function wRe(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 ep,Co,yB,df,d3,WM,Db,bj,vB,KM,YM,u3,h3,_j,ZM,bl,gR,Nje,kje,Sje,Cje,Tje,Eje,Aje,uXe,wWe,dXe=(wWe=class extends _P{constructor(t,r){super();Ua(this,bl);Ua(this,ep);Ua(this,Co);Ua(this,yB);Ua(this,df);Ua(this,d3);Ua(this,WM);Ua(this,Db);Ua(this,bj);Ua(this,vB);Ua(this,KM);Ua(this,YM);Ua(this,u3);Ua(this,h3);Ua(this,_j);Ua(this,ZM,new Set);this.options=r,Zn(this,ep,t),Zn(this,bj,null),Zn(this,Db,_je()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Ts(this,Co).addObserver(this),jRe(Ts(this,Co),this.options)?Wi(this,bl,gR).call(this):this.updateResult(),Wi(this,bl,Cje).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Mje(Ts(this,Co),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Mje(Ts(this,Co),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Wi(this,bl,Tje).call(this),Wi(this,bl,Eje).call(this),Ts(this,Co).removeObserver(this)}setOptions(t){const r=this.options,n=Ts(this,Co);if(this.options=Ts(this,ep).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof rx(this.options.enabled,Ts(this,Co))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Wi(this,bl,Aje).call(this),Ts(this,Co).setOptions(this.options),r._defaulted&&!_ue(this.options,r)&&Ts(this,ep).getQueryCache().notify({type:"observerOptionsUpdated",query:Ts(this,Co),observer:this});const a=this.hasListeners();a&&NRe(Ts(this,Co),n,this.options,r)&&Wi(this,bl,gR).call(this),this.updateResult(),a&&(Ts(this,Co)!==n||rx(this.options.enabled,Ts(this,Co))!==rx(r.enabled,Ts(this,Co))||n2(this.options.staleTime,Ts(this,Co))!==n2(r.staleTime,Ts(this,Co)))&&Wi(this,bl,Nje).call(this);const i=Wi(this,bl,kje).call(this);a&&(Ts(this,Co)!==n||rx(this.options.enabled,Ts(this,Co))!==rx(r.enabled,Ts(this,Co))||i!==Ts(this,_j))&&Wi(this,bl,Sje).call(this,i)}getOptimisticResult(t){const r=Ts(this,ep).getQueryCache().build(Ts(this,ep),t),n=this.createResult(r,t);return PSt(this,n)&&(Zn(this,df,n),Zn(this,WM,this.options),Zn(this,d3,Ts(this,Co).state)),n}getCurrentResult(){return Ts(this,df)}trackResult(t,r){return new Proxy(t,{get:(n,a)=>(this.trackProp(a),r==null||r(a),a==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&Ts(this,Db).status==="pending"&&Ts(this,Db).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,a))})}trackProp(t){Ts(this,ZM).add(t)}getCurrentQuery(){return Ts(this,Co)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Ts(this,ep).defaultQueryOptions(t),n=Ts(this,ep).getQueryCache().build(Ts(this,ep),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return Wi(this,bl,gR).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Ts(this,df)))}createResult(t,r){var F;const n=Ts(this,Co),a=this.options,i=Ts(this,df),l=Ts(this,d3),o=Ts(this,WM),d=t!==n?t.state:Ts(this,yB),{state:h}=t;let m={...h},x=!1,g;if(r._optimisticResults){const $=this.hasListeners(),X=!$&&jRe(t,r),K=$&&NRe(t,n,r,a);(X||K)&&(m={...m,...cXe(h.data,t.options)}),r._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:v,errorUpdatedAt:j,status:b}=m;g=m.data;let N=!1;if(r.placeholderData!==void 0&&g===void 0&&b==="pending"){let $;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?($=i.data,N=!0):$=typeof r.placeholderData=="function"?r.placeholderData((F=Ts(this,YM))==null?void 0:F.state.data,Ts(this,YM)):r.placeholderData,$!==void 0&&(b="success",g=bje(i==null?void 0:i.data,$,r),x=!0)}if(r.select&&g!==void 0&&!N)if(i&&g===(l==null?void 0:l.data)&&r.select===Ts(this,vB))g=Ts(this,KM);else try{Zn(this,vB,r.select),g=r.select(g),g=bje(i==null?void 0:i.data,g,r),Zn(this,KM,g),Zn(this,bj,null)}catch($){Zn(this,bj,$)}Ts(this,bj)&&(v=Ts(this,bj),g=Ts(this,KM),j=Date.now(),b="error");const S=m.fetchStatus==="fetching",T=b==="pending",A=b==="error",P=T&&S,D=g!==void 0,z={status:b,fetchStatus:m.fetchStatus,isPending:T,isSuccess:b==="success",isError:A,isInitialLoading:P,isLoading:P,data:g,dataUpdatedAt:m.dataUpdatedAt,error:v,errorUpdatedAt:j,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:m.dataUpdateCount>d.dataUpdateCount||m.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!T,isLoadingError:A&&!D,isPaused:m.fetchStatus==="paused",isPlaceholderData:x,isRefetchError:A&&D,isStale:E4e(t,r),refetch:this.refetch,promise:Ts(this,Db),isEnabled:rx(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const $=z.data!==void 0,X=z.status==="error"&&!$,K=ne=>{X?ne.reject(z.error):$&&ne.resolve(z.data)},Q=()=>{const ne=Zn(this,Db,z.promise=_je());K(ne)},Y=Ts(this,Db);switch(Y.status){case"pending":t.queryHash===n.queryHash&&K(Y);break;case"fulfilled":(X||z.data!==Y.value)&&Q();break;case"rejected":(!X||z.error!==Y.reason)&&Q();break}}return z}updateResult(){const t=Ts(this,df),r=this.createResult(Ts(this,Co),this.options);if(Zn(this,d3,Ts(this,Co).state),Zn(this,WM,this.options),Ts(this,d3).data!==void 0&&Zn(this,YM,Ts(this,Co)),_ue(r,t))return;Zn(this,df,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Ts(this,ZM).size)return!0;const l=new Set(i??Ts(this,ZM));return this.options.throwOnError&&l.add("error"),Object.keys(Ts(this,df)).some(o=>{const c=o;return Ts(this,df)[c]!==t[c]&&l.has(c)})};Wi(this,bl,uXe).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Wi(this,bl,Cje).call(this)}},ep=new WeakMap,Co=new WeakMap,yB=new WeakMap,df=new WeakMap,d3=new WeakMap,WM=new WeakMap,Db=new WeakMap,bj=new WeakMap,vB=new WeakMap,KM=new WeakMap,YM=new WeakMap,u3=new WeakMap,h3=new WeakMap,_j=new WeakMap,ZM=new WeakMap,bl=new WeakSet,gR=function(t){Wi(this,bl,Aje).call(this);let r=Ts(this,Co).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(hf)),r},Nje=function(){Wi(this,bl,Tje).call(this);const t=n2(this.options.staleTime,Ts(this,Co));if(Y8.isServer()||Ts(this,df).isStale||!yje(t))return;const n=tXe(Ts(this,df).dataUpdatedAt,t)+1;Zn(this,u3,$4.setTimeout(()=>{Ts(this,df).isStale||this.updateResult()},n))},kje=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Ts(this,Co)):this.options.refetchInterval)??!1},Sje=function(t){Wi(this,bl,Eje).call(this),Zn(this,_j,t),!(Y8.isServer()||rx(this.options.enabled,Ts(this,Co))===!1||!yje(Ts(this,_j))||Ts(this,_j)===0)&&Zn(this,h3,$4.setInterval(()=>{(this.options.refetchIntervalInBackground||k4e.isFocused())&&Wi(this,bl,gR).call(this)},Ts(this,_j)))},Cje=function(){Wi(this,bl,Nje).call(this),Wi(this,bl,Sje).call(this,Wi(this,bl,kje).call(this))},Tje=function(){Ts(this,u3)!==void 0&&($4.clearTimeout(Ts(this,u3)),Zn(this,u3,void 0))},Eje=function(){Ts(this,h3)!==void 0&&($4.clearInterval(Ts(this,h3)),Zn(this,h3,void 0))},Aje=function(){const t=Ts(this,ep).getQueryCache().build(Ts(this,ep),this.options);if(t===Ts(this,Co))return;const r=Ts(this,Co);Zn(this,Co,t),Zn(this,yB,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},uXe=function(t){Uu.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Ts(this,df))}),Ts(this,ep).getQueryCache().notify({query:Ts(this,Co),type:"observerResultsUpdated"})})},wWe);function ISt(s,t){return rx(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&rx(t.retryOnMount,s)===!1)}function jRe(s,t){return ISt(s,t)||s.state.data!==void 0&&Mje(s,t,t.refetchOnMount)}function Mje(s,t,r){if(rx(t.enabled,s)!==!1&&n2(t.staleTime,s)!=="static"){const n=typeof r=="function"?r(s):r;return n==="always"||n!==!1&&E4e(s,t)}return!1}function NRe(s,t,r,n){return(s!==t||rx(n.enabled,s)===!1)&&(!r.suspense||s.state.status!=="error")&&E4e(s,r)}function E4e(s,t){return rx(t.enabled,s)!==!1&&s.isStaleByTime(n2(t.staleTime,s))}function PSt(s,t){return!_ue(s.getCurrentResult(),t)}var LSt=class extends dXe{constructor(s,t){super(s,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){s._type="infinite",super.setOptions(s)}getOptimisticResult(s){return s._type="infinite",super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,t){var v,j;const{state:r}=s,n=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=n,c=(j=(v=r.fetchMeta)==null?void 0:v.fetchMore)==null?void 0:j.direction,d=l&&c==="forward",h=a&&c==="forward",m=l&&c==="backward",x=a&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:ESt(t,r.data),hasPreviousPage:ASt(t,r.data),isFetchNextPageError:d,isFetchingNextPage:h,isFetchPreviousPageError:m,isFetchingPreviousPage:x,isRefetchError:o&&!d&&!m,isRefetching:i&&!h&&!x}}},bB,xv,Sm,m3,gv,$w,jWe,DSt=(jWe=class extends iXe{constructor(t){super();Ua(this,gv);Ua(this,bB);Ua(this,xv);Ua(this,Sm);Ua(this,m3);Zn(this,bB,t.client),this.mutationId=t.mutationId,Zn(this,Sm,t.mutationCache),Zn(this,xv,[]),this.state=t.state||hXe(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Ts(this,xv).includes(t)||(Ts(this,xv).push(t),this.clearGcTimeout(),Ts(this,Sm).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Zn(this,xv,Ts(this,xv).filter(r=>r!==t)),this.scheduleGc(),Ts(this,Sm).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Ts(this,xv).length||(this.state.status==="pending"?this.scheduleGc():Ts(this,Sm).remove(this))}continue(){var t;return((t=Ts(this,m3))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var l,o,c,d,h,m,x,g,v,j,b,N,S,T,A,P,D,B;const r=()=>{Wi(this,gv,$w).call(this,{type:"continue"})},n={client:Ts(this,bB),meta:this.options.meta,mutationKey:this.options.mutationKey};Zn(this,m3,aXe({fn:()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),onFail:(z,F)=>{Wi(this,gv,$w).call(this,{type:"failed",failureCount:z,error:F})},onPause:()=>{Wi(this,gv,$w).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Ts(this,Sm).canRun(this)}));const a=this.state.status==="pending",i=!Ts(this,m3).canStart();try{if(a)r();else{Wi(this,gv,$w).call(this,{type:"pending",variables:t,isPaused:i}),Ts(this,Sm).config.onMutate&&await Ts(this,Sm).config.onMutate(t,this,n);const F=await((o=(l=this.options).onMutate)==null?void 0:o.call(l,t,n));F!==this.state.context&&Wi(this,gv,$w).call(this,{type:"pending",context:F,variables:t,isPaused:i})}const z=await Ts(this,m3).start();return await((d=(c=Ts(this,Sm).config).onSuccess)==null?void 0:d.call(c,z,t,this.state.context,this,n)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,z,t,this.state.context,n)),await((g=(x=Ts(this,Sm).config).onSettled)==null?void 0:g.call(x,z,null,this.state.variables,this.state.context,this,n)),await((j=(v=this.options).onSettled)==null?void 0:j.call(v,z,null,t,this.state.context,n)),Wi(this,gv,$w).call(this,{type:"success",data:z}),z}catch(z){try{await((N=(b=Ts(this,Sm).config).onError)==null?void 0:N.call(b,z,t,this.state.context,this,n))}catch(F){Promise.reject(F)}try{await((T=(S=this.options).onError)==null?void 0:T.call(S,z,t,this.state.context,n))}catch(F){Promise.reject(F)}try{await((P=(A=Ts(this,Sm).config).onSettled)==null?void 0:P.call(A,void 0,z,this.state.variables,this.state.context,this,n))}catch(F){Promise.reject(F)}try{await((B=(D=this.options).onSettled)==null?void 0:B.call(D,void 0,z,t,this.state.context,n))}catch(F){Promise.reject(F)}throw Wi(this,gv,$w).call(this,{type:"error",error:z}),z}finally{Ts(this,Sm).runNext(this)}}},bB=new WeakMap,xv=new WeakMap,Sm=new WeakMap,m3=new WeakMap,gv=new WeakSet,$w=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),Uu.batch(()=>{Ts(this,xv).forEach(n=>{n.onMutationUpdate(t)}),Ts(this,Sm).notify({mutation:this,type:"updated",action:t})})},jWe);function hXe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Rb,Fy,_B,NWe,RSt=(NWe=class extends _P{constructor(t={}){super();Ua(this,Rb);Ua(this,Fy);Ua(this,_B);this.config=t,Zn(this,Rb,new Set),Zn(this,Fy,new Map),Zn(this,_B,0)}build(t,r,n){const a=new DSt({client:t,mutationCache:this,mutationId:++y$(this,_B)._,options:t.defaultMutationOptions(r),state:n});return this.add(a),a}add(t){Ts(this,Rb).add(t);const r=$$(t);if(typeof r=="string"){const n=Ts(this,Fy).get(r);n?n.push(t):Ts(this,Fy).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Ts(this,Rb).delete(t)){const r=$$(t);if(typeof r=="string"){const n=Ts(this,Fy).get(r);if(n)if(n.length>1){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}else n[0]===t&&Ts(this,Fy).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=$$(t);if(typeof r=="string"){const n=Ts(this,Fy).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=$$(t);if(typeof r=="string"){const a=(n=Ts(this,Fy).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(){Uu.batch(()=>{Ts(this,Rb).forEach(t=>{this.notify({type:"removed",mutation:t})}),Ts(this,Rb).clear(),Ts(this,Fy).clear()})}getAll(){return Array.from(Ts(this,Rb))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>yRe(r,n))}findAll(t={}){return this.getAll().filter(r=>yRe(t,r))}notify(t){Uu.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return Uu.batch(()=>Promise.all(t.map(r=>r.continue().catch(hf))))}},Rb=new WeakMap,Fy=new WeakMap,_B=new WeakMap,NWe);function $$(s){var t;return(t=s.options.scope)==null?void 0:t.id}var Ob,wj,tp,Fb,u_,lde,Ije,kWe,OSt=(kWe=class extends _P{constructor(r,n){super();Ua(this,u_);Ua(this,Ob);Ua(this,wj);Ua(this,tp);Ua(this,Fb);Zn(this,Ob,r),this.setOptions(n),this.bindMethods(),Wi(this,u_,lde).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=Ts(this,Ob).defaultMutationOptions(r),_ue(this.options,n)||Ts(this,Ob).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Ts(this,tp),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&p5(n.mutationKey)!==p5(this.options.mutationKey)?this.reset():((a=Ts(this,tp))==null?void 0:a.state.status)==="pending"&&Ts(this,tp).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Ts(this,tp))==null||r.removeObserver(this)}onMutationUpdate(r){Wi(this,u_,lde).call(this),Wi(this,u_,Ije).call(this,r)}getCurrentResult(){return Ts(this,wj)}reset(){var r;(r=Ts(this,tp))==null||r.removeObserver(this),Zn(this,tp,void 0),Wi(this,u_,lde).call(this),Wi(this,u_,Ije).call(this)}mutate(r,n){var a;return Zn(this,Fb,n),(a=Ts(this,tp))==null||a.removeObserver(this),Zn(this,tp,Ts(this,Ob).getMutationCache().build(Ts(this,Ob),this.options)),Ts(this,tp).addObserver(this),Ts(this,tp).execute(r)}},Ob=new WeakMap,wj=new WeakMap,tp=new WeakMap,Fb=new WeakMap,u_=new WeakSet,lde=function(){var n;const r=((n=Ts(this,tp))==null?void 0:n.state)??hXe();Zn(this,wj,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Ije=function(r){Uu.batch(()=>{var n,a,i,l,o,c,d,h;if(Ts(this,Fb)&&this.hasListeners()){const m=Ts(this,wj).variables,x=Ts(this,wj).context,g={client:Ts(this,Ob),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(a=(n=Ts(this,Fb)).onSuccess)==null||a.call(n,r.data,m,x,g)}catch(v){Promise.reject(v)}try{(l=(i=Ts(this,Fb)).onSettled)==null||l.call(i,r.data,null,m,x,g)}catch(v){Promise.reject(v)}}else if((r==null?void 0:r.type)==="error"){try{(c=(o=Ts(this,Fb)).onError)==null||c.call(o,r.error,m,x,g)}catch(v){Promise.reject(v)}try{(h=(d=Ts(this,Fb)).onSettled)==null||h.call(d,void 0,r.error,m,x,g)}catch(v){Promise.reject(v)}}}this.listeners.forEach(m=>{m(Ts(this,wj))})})},kWe),yv,SWe,FSt=(SWe=class extends _P{constructor(t={}){super();Ua(this,yv);this.config=t,Zn(this,yv,new Map)}build(t,r,n){const a=r.queryKey,i=r.queryHash??S4e(a,r);let l=this.get(i);return l||(l=new MSt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Ts(this,yv).has(t.queryHash)||(Ts(this,yv).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Ts(this,yv).get(t.queryHash);r&&(t.destroy(),r===t&&Ts(this,yv).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Uu.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Ts(this,yv).get(t)}getAll(){return[...Ts(this,yv).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>gRe(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>gRe(t,n)):r}notify(t){Uu.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){Uu.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Uu.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},yv=new WeakMap,SWe),Cd,jj,Nj,XM,QM,kj,JM,eI,CWe,BSt=(CWe=class{constructor(s={}){Ua(this,Cd);Ua(this,jj);Ua(this,Nj);Ua(this,XM);Ua(this,QM);Ua(this,kj);Ua(this,JM);Ua(this,eI);Zn(this,Cd,s.queryCache||new FSt),Zn(this,jj,s.mutationCache||new RSt),Zn(this,Nj,s.defaultOptions||{}),Zn(this,XM,new Map),Zn(this,QM,new Map),Zn(this,kj,0)}mount(){y$(this,kj)._++,Ts(this,kj)===1&&(Zn(this,JM,k4e.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ts(this,Cd).onFocus())})),Zn(this,eI,wue.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ts(this,Cd).onOnline())})))}unmount(){var s,t;y$(this,kj)._--,Ts(this,kj)===0&&((s=Ts(this,JM))==null||s.call(this),Zn(this,JM,void 0),(t=Ts(this,eI))==null||t.call(this),Zn(this,eI,void 0))}isFetching(s){return Ts(this,Cd).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Ts(this,jj).findAll({...s,status:"pending"}).length}getQueryData(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ts(this,Cd).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),r=Ts(this,Cd).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(s):(s.revalidateIfStale&&r.isStaleByTime(n2(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(s){return Ts(this,Cd).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=Ts(this,Cd).get(n.queryHash),i=a==null?void 0:a.state.data,l=ySt(t,i);if(l!==void 0)return Ts(this,Cd).build(this,n).setData(l,{...r,manual:!0})}setQueriesData(s,t,r){return Uu.batch(()=>Ts(this,Cd).findAll(s).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ts(this,Cd).get(t.queryHash))==null?void 0:r.state}removeQueries(s){const t=Ts(this,Cd);Uu.batch(()=>{t.findAll(s).forEach(r=>{t.remove(r)})})}resetQueries(s,t){const r=Ts(this,Cd);return Uu.batch(()=>(r.findAll(s).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const r={revert:!0,...t},n=Uu.batch(()=>Ts(this,Cd).findAll(s).map(a=>a.cancel(r)));return Promise.all(n).then(hf).catch(hf)}invalidateQueries(s,t={}){return Uu.batch(()=>(Ts(this,Cd).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=Uu.batch(()=>Ts(this,Cd).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,r);return r.throwOnError||(i=i.catch(hf)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(hf)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const r=Ts(this,Cd).build(this,t);return r.isStaleByTime(n2(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(hf).catch(hf)}fetchInfiniteQuery(s){return s._type="infinite",this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(hf).catch(hf)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return wue.isOnline()?Ts(this,jj).resumePausedMutations():Promise.resolve()}getQueryCache(){return Ts(this,Cd)}getMutationCache(){return Ts(this,jj)}getDefaultOptions(){return Ts(this,Nj)}setDefaultOptions(s){Zn(this,Nj,s)}setQueryDefaults(s,t){Ts(this,XM).set(p5(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Ts(this,XM).values()],r={};return t.forEach(n=>{K8(s,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(s,t){Ts(this,QM).set(p5(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Ts(this,QM).values()],r={};return t.forEach(n=>{K8(s,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Ts(this,Nj).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=S4e(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===C4e&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Ts(this,Nj).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Ts(this,Cd).clear(),Ts(this,jj).clear()}},Cd=new WeakMap,jj=new WeakMap,Nj=new WeakMap,XM=new WeakMap,QM=new WeakMap,kj=new WeakMap,JM=new WeakMap,eI=new WeakMap,CWe),mXe=k.createContext(void 0),es=s=>{const t=k.useContext(mXe);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},zSt=({client:s,children:t})=>(k.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(mXe.Provider,{value:s,children:t})),fXe=k.createContext(!1),$St=()=>k.useContext(fXe);fXe.Provider;function USt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var qSt=k.createContext(USt()),VSt=()=>k.useContext(qSt),HSt=(s,t,r)=>{const n=r!=null&&r.state.error&&typeof s.throwOnError=="function"?T4e(s.throwOnError,[r.state.error,r]):s.throwOnError;(s.suspense||s.experimental_prefetchInRender||n)&&(t.isReset()||(s.retryOnMount=!1))},GSt=s=>{k.useEffect(()=>{s.clearReset()},[s])},WSt=({result:s,errorResetBoundary:t,throwOnError:r,query:n,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&n&&(a&&s.data===void 0||T4e(r,[s.error,n])),KSt=s=>{if(s.suspense){const r=a=>a==="static"?a:Math.max(a??1e3,1e3),n=s.staleTime;s.staleTime=typeof n=="function"?(...a)=>r(n(...a)):r(n),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},YSt=(s,t)=>s.isLoading&&s.isFetching&&!t,ZSt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,kRe=(s,t,r)=>t.fetchOptimistic(s).catch(()=>{r.clearReset()});function pXe(s,t,r){var g,v,j,b;const n=$St(),a=VSt(),i=es(),l=i.defaultQueryOptions(s);(v=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||v.call(g,l);const o=i.getQueryCache().get(l.queryHash),c=s.subscribed!==!1;l._optimisticResults=n?"isRestoring":c?"optimistic":void 0,KSt(l),HSt(l,a,o),GSt(a);const d=!i.getQueryCache().get(l.queryHash),[h]=k.useState(()=>new t(i,l)),m=h.getOptimisticResult(l),x=!n&&c;if(k.useSyncExternalStore(k.useCallback(N=>{const S=x?h.subscribe(Uu.batchCalls(N)):hf;return h.updateResult(),S},[h,x]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),k.useEffect(()=>{h.setOptions(l)},[l,h]),ZSt(l,m))throw kRe(l,h,a);if(WSt({result:m,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw m.error;if((b=(j=i.getDefaultOptions().queries)==null?void 0:j._experimental_afterQuery)==null||b.call(j,l,m),l.experimental_prefetchInRender&&!Y8.isServer()&&YSt(m,n)){const N=d?kRe(l,h,a):o==null?void 0:o.promise;N==null||N.catch(hf).finally(()=>{h.updateResult()})}return l.notifyOnChangeProps?m:h.trackResult(m)}function gt(s,t){return pXe(s,dXe)}function Lt(s,t){const r=es(),[n]=k.useState(()=>new OSt(r,s));k.useEffect(()=>{n.setOptions(s)},[n,s]);const a=k.useSyncExternalStore(k.useCallback(l=>n.subscribe(Uu.batchCalls(l)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=k.useCallback((l,o)=>{n.mutate(l,o).catch(hf)},[n]);if(a.error&&T4e(n.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function XSt(s,t){return pXe(s,LSt)}/** * @remix-run/router v1.23.3 * * 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 Z8(){return Z8=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function A4e(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function JSt(){return Math.random().toString(36).substr(2,8)}function CRe(s,t){return{usr:s.state,key:s.key,idx:t}}function Pje(s,t,r,n){return r===void 0&&(r=null),Z8({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?wP(t):t,{state:r,key:t&&t.key||n||JSt()})}function jue(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 wP(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 eCt(s,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:i=!1}=n,l=a.history,o=Tj.Pop,c=null,d=h();d==null&&(d=0,l.replaceState(Z8({},l.state,{idx:d}),""));function h(){return(l.state||{idx:null}).idx}function m(){o=Tj.Pop;let b=h(),N=b==null?null:b-d;d=b,c&&c({action:o,location:j.location,delta:N})}function x(b,N){o=Tj.Push;let S=Pje(j.location,b,N);d=h()+1;let T=CRe(S,d),A=j.createHref(S);try{l.pushState(T,"",A)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;a.location.assign(A)}i&&c&&c({action:o,location:j.location,delta:1})}function g(b,N){o=Tj.Replace;let S=Pje(j.location,b,N);d=h();let T=CRe(S,d),A=j.createHref(S);l.replaceState(T,"",A),i&&c&&c({action:o,location:j.location,delta:0})}function v(b){let N=a.location.origin!=="null"?a.location.origin:a.location.href,S=typeof b=="string"?b:jue(b);return S=S.replace(/ $/,"%20"),ou(N,"No window.location.(origin|href) available to create URL for href: "+S),new URL(S,N)}let j={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(SRe,m),c=b,()=>{a.removeEventListener(SRe,m),c=null}},createHref(b){return t(a,b)},createURL:v,encodeLocation(b){let N=v(b);return{pathname:N.pathname,search:N.search,hash:N.hash}},push:x,replace:g,go(b){return l.go(b)}};return j}var TRe;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(TRe||(TRe={}));function tCt(s,t,r){return r===void 0&&(r="/"),sCt(s,t,r)}function sCt(s,t,r,n){let a=typeof t=="string"?wP(t):t,i=M4e(a.pathname||"/",r);if(i==null)return null;let l=xXe(s);rCt(l);let o=null,c=pCt(i);for(let d=0;o==null&&d{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(ou(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=a2([n,c.relativePath]),h=r.concat(c);i.children&&i.children.length>0&&(ou(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),xXe(i.children,t,h,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:dCt(d,i.index),routesMeta:h})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of gXe(i.path))a(i,l,c)}),t}function gXe(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=gXe(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 rCt(s){s.sort((t,r)=>t.score!==r.score?r.score-t.score:uCt(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const nCt=/^:[\w-]+$/,aCt=3,iCt=2,oCt=1,lCt=10,cCt=-2,ERe=s=>s==="*";function dCt(s,t){let r=s.split("/"),n=r.length;return r.some(ERe)&&(n+=cCt),t&&(n+=iCt),r.filter(a=>!ERe(a)).reduce((a,i)=>a+(nCt.test(i)?aCt:i===""?oCt:lCt),n)}function uCt(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 hCt(s,t,r){let{routesMeta:n}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:x,isOptional:g}=h;if(x==="*"){let j=o[m]||"";l=i.slice(0,i.length-j.length).replace(/(.)\/+$/,"$1")}const v=o[m];return g&&!v?d[x]=void 0:d[x]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function fCt(s,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),A4e(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 pCt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return A4e(!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 M4e(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)||"/"}const xCt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,gCt=s=>xCt.test(s);function yCt(s,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof s=="string"?wP(s):s,i;if(r)if(gCt(r))i=r;else{if(r.includes("//")){let l=r;r=yXe(r),A4e(!1,"Pathnames cannot have embedded double slashes - normalizing "+(l+" -> "+r))}r.startsWith("/")?i=ARe(r.substring(1),"/"):i=ARe(r,t)}else i=t;return{pathname:i,search:_Ct(n),hash:wCt(a)}}function ARe(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 Xve(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 vCt(s){return s.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function I4e(s,t){let r=vCt(s);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function P4e(s,t,r,n){n===void 0&&(n=!1);let a;typeof s=="string"?a=wP(s):(a=Z8({},s),ou(!a.pathname||!a.pathname.includes("?"),Xve("?","pathname","search",a)),ou(!a.pathname||!a.pathname.includes("#"),Xve("#","pathname","hash",a)),ou(!a.search||!a.search.includes("#"),Xve("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=r;else{let m=t.length-1;if(!n&&l.startsWith("..")){let x=l.split("/");for(;x[0]==="..";)x.shift(),m-=1;a.pathname=x.join("/")}o=m>=0?t[m]:"/"}let c=yCt(a,o),d=l&&l!=="/"&&l.endsWith("/"),h=(i||l===".")&&r.endsWith("/");return!c.pathname.endsWith("/")&&(d||h)&&(c.pathname+="/"),c}const yXe=s=>s.replace(/\/\/+/g,"/"),a2=s=>yXe(s.join("/")),bCt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),_Ct=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,wCt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function jCt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const vXe=["post","put","patch","delete"];new Set(vXe);const NCt=["get",...vXe];new Set(NCt);/** * React Router v6.30.4 * * 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 X8(){return X8=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),k.useCallback(function(d,h){if(h===void 0&&(h={}),!o.current)return;if(typeof d=="number"){n.go(d);return}let m=P4e(d,JSON.parse(l),i,h.relative==="path");s==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:a2([t,m.pathname])),(h.replace?n.replace:n.push)(m,h.state,h)},[t,n,l,i,s])}const TCt=k.createContext(null);function ECt(s){let t=k.useContext(g1).outlet;return t&&k.createElement(TCt.Provider,{value:s},t)}function Xi(){let{matches:s}=k.useContext(g1),t=s[s.length-1];return t?t.params:{}}function wXe(s,t){let{relative:r}=t===void 0?{}:t,{future:n}=k.useContext(B2),{matches:a}=k.useContext(g1),{pathname:i}=sc(),l=JSON.stringify(I4e(a,n.v7_relativeSplatPath));return k.useMemo(()=>P4e(s,JSON.parse(l),i,r==="path"),[s,l,i,r])}function ACt(s,t){return MCt(s,t)}function MCt(s,t,r,n){jP()||ou(!1);let{navigator:a}=k.useContext(B2),{matches:i}=k.useContext(g1),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=sc(),h;if(t){var m;let b=typeof t=="string"?wP(t):t;c==="/"||(m=b.pathname)!=null&&m.startsWith(c)||ou(!1),h=b}else h=d;let x=h.pathname||"/",g=x;if(c!=="/"){let b=c.replace(/^\//,"").split("/");g="/"+x.replace(/^\//,"").split("/").slice(b.length).join("/")}let v=tCt(s,{pathname:g}),j=RCt(v&&v.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:a2([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:a2([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,r,n);return t&&j?k.createElement(Qfe.Provider,{value:{location:X8({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:Tj.Pop}},j):j}function ICt(){let s=zCt(),t=jCt(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 PCt=k.createElement(ICt,null);class LCt 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(g1.Provider,{value:this.props.routeContext},k.createElement(bXe.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function DCt(s){let{routeContext:t,match:r,children:n}=s,a=k.useContext(L4e);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),k.createElement(g1.Provider,{value:t},n)}function RCt(s,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),s==null){var i;if(!r)return null;if(r.errors)s=r.matches;else if((i=n)!=null&&i.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)s=r.matches;else return null}let l=s,o=(a=r)==null?void 0:a.errors;if(o!=null){let h=l.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);h>=0||ou(!1),l=l.slice(0,Math.min(l.length,h+1))}let c=!1,d=-1;if(r&&n&&n.v7_partialHydration)for(let h=0;h=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((h,m,x)=>{let g,v=!1,j=null,b=null;r&&(g=o&&m.route.id?o[m.route.id]:void 0,j=m.route.errorElement||PCt,c&&(d<0&&x===0?(UCt("route-fallback"),v=!0,b=null):d===x&&(v=!0,b=m.route.hydrateFallbackElement||null)));let N=t.concat(l.slice(0,x+1)),S=()=>{let T;return g?T=j:v?T=b:m.route.Component?T=k.createElement(m.route.Component,null):m.route.element?T=m.route.element:T=h,k.createElement(DCt,{match:m,routeContext:{outlet:h,matches:N,isDataRoute:r!=null},children:T})};return r&&(m.route.ErrorBoundary||m.route.errorElement||x===0)?k.createElement(LCt,{location:r.location,revalidation:r.revalidation,component:j,error:g,children:S(),routeContext:{outlet:null,matches:N,isDataRoute:!0}}):S()},null)}var jXe=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(jXe||{}),NXe=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}(NXe||{});function OCt(s){let t=k.useContext(L4e);return t||ou(!1),t}function FCt(s){let t=k.useContext(kCt);return t||ou(!1),t}function BCt(s){let t=k.useContext(g1);return t||ou(!1),t}function kXe(s){let t=BCt(),r=t.matches[t.matches.length-1];return r.route.id||ou(!1),r.route.id}function zCt(){var s;let t=k.useContext(bXe),r=FCt(),n=kXe();return t!==void 0?t:(s=r.errors)==null?void 0:s[n]}function $Ct(){let{router:s}=OCt(jXe.UseNavigateStable),t=kXe(NXe.UseNavigateStable),r=k.useRef(!1);return _Xe(()=>{r.current=!0}),k.useCallback(function(a,i){i===void 0&&(i={}),r.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,X8({fromRouteId:t},i)))},[s,t])}const MRe={};function UCt(s,t,r){MRe[s]||(MRe[s]=!0)}function qCt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function Qve(s){let{to:t,replace:r,state:n,relative:a}=s;jP()||ou(!1);let{future:i,static:l}=k.useContext(B2),{matches:o}=k.useContext(g1),{pathname:c}=sc(),d=vr(),h=P4e(t,I4e(o,i.v7_relativeSplatPath),c,a==="path"),m=JSON.stringify(h);return k.useEffect(()=>d(JSON.parse(m),{replace:r,state:n,relative:a}),[d,m,a,r,n]),null}function VCt(s){return ECt(s.context)}function ps(s){ou(!1)}function HCt(s){let{basename:t="/",children:r=null,location:n,navigationType:a=Tj.Pop,navigator:i,static:l=!1,future:o}=s;jP()&&ou(!1);let c=t.replace(/^\/*/,"/"),d=k.useMemo(()=>({basename:c,navigator:i,static:l,future:X8({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof n=="string"&&(n=wP(n));let{pathname:h="/",search:m="",hash:x="",state:g=null,key:v="default"}=n,j=k.useMemo(()=>{let b=M4e(h,c);return b==null?null:{location:{pathname:b,search:m,hash:x,state:g,key:v},navigationType:a}},[c,h,m,x,g,v,a]);return j==null?null:k.createElement(B2.Provider,{value:d},k.createElement(Qfe.Provider,{children:r,value:j}))}function Nue(s){let{children:t,location:r}=s;return ACt(Lje(t),r)}new Promise(()=>{});function Lje(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,Lje(n.props.children,i));return}n.type!==ps&&ou(!1),!n.props.index||!n.props.children||ou(!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=Lje(n.props.children,i)),r.push(l)}),r}/** * React Router DOM v6.30.4 * * 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 Dje(){return Dje=Object.assign?Object.assign.bind():function(s){for(var t=1;t{let n=s[r];return t.concat(Array.isArray(n)?n.map(a=>[r,a]):[[r,n]])},[]))}function YCt(s,t){let r=Rje(s);return t&&t.forEach((n,a)=>{r.has(a)||t.getAll(a).forEach(i=>{r.append(a,i)})}),r}const ZCt=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],XCt="6";try{window.__reactRouterVersion=XCt}catch{}const QCt="startTransition",IRe=jB[QCt];function JCt(s){let{basename:t,children:r,future:n,window:a}=s,i=k.useRef();i.current==null&&(i.current=QSt({window:a,v5Compat:!0}));let l=i.current,[o,c]=k.useState({action:l.action,location:l.location}),{v7_startTransition:d}=n||{},h=k.useCallback(m=>{d&&IRe?IRe(()=>c(m)):c(m)},[c,d]);return k.useLayoutEffect(()=>l.listen(h),[l,h]),k.useEffect(()=>qCt(n),[n]),k.createElement(HCt,{basename:t,children:r,location:o.location,navigationType:o.action,navigator:l,future:n})}const e4t=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",t4t=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Kn=k.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:h,viewTransition:m}=t,x=GCt(t,ZCt),{basename:g}=k.useContext(B2),v,j=!1;if(typeof d=="string"&&t4t.test(d)&&(v=d,e4t))try{let T=new URL(window.location.href),A=d.startsWith("//")?new URL(T.protocol+d):new URL(d),P=M4e(A.pathname,g);A.origin===T.origin&&P!=null?d=P+A.search+A.hash:j=!0}catch{}let b=SCt(d,{relative:a}),N=s4t(d,{replace:l,state:o,target:c,preventScrollReset:h,relative:a,viewTransition:m});function S(T){n&&n(T),T.defaultPrevented||N(T)}return k.createElement("a",Dje({},x,{href:v||b,onClick:j||i?n:S,ref:r,target:c}))});var PRe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(PRe||(PRe={}));var LRe;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(LRe||(LRe={}));function s4t(s,t){let{target:r,replace:n,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=vr(),d=sc(),h=wXe(s,{relative:l});return k.useCallback(m=>{if(KCt(m,r)){m.preventDefault();let x=n!==void 0?n:jue(d)===jue(h);c(s,{replace:x,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,h,n,a,r,s,i,l,o])}function Lc(s){let t=k.useRef(Rje(s)),r=k.useRef(!1),n=sc(),a=k.useMemo(()=>YCt(n.search,r.current?null:t.current),[n.search]),i=vr(),l=k.useCallback((o,c)=>{const d=Rje(typeof o=="function"?o(a):o);r.current=!0,i("?"+d,c)},[i,a]);return[a,l]}var r4t=typeof Element<"u",n4t=typeof Map=="function",a4t=typeof Set=="function",i4t=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function cde(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(!cde(s[n],t[n]))return!1;return!0}var i;if(n4t&&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(!cde(n.value[1],t.get(n.value[0])))return!1;return!0}if(a4t&&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(i4t&&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(r4t&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!cde(s[a[n]],t[a[n]]))return!1;return!0}return s!==s&&t!==t}var o4t=function(t,r){try{return cde(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 l4t=Io(o4t);var c4t=function(s,t,r,n,a,i,l,o){if(!s){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var d=[r,n,a,i,l,o],h=0;c=new Error(t.replace(/%s/g,function(){return d[h++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},d4t=c4t;const DRe=Io(d4t);var u4t=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))(SXe||{}),Jve={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"]}},RRe=Object.values(SXe),D4e={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},m4t=Object.entries(D4e).reduce((s,[t,r])=>(s[r]=t,s),{}),Zy="data-rh",_M={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},wM=(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},f4t=s=>{let t=wM(s,"title");const r=wM(s,_M.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),r&&t)return r.replace(/%s/g,()=>t);const n=wM(s,_M.DEFAULT_TITLE);return t||n||void 0},p4t=s=>wM(s,_M.ON_CHANGE_CLIENT_STATE)||(()=>{}),e1e=(s,t)=>t.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),x4t=(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),DD=(s,t,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&g4t(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const h=Object.keys(c);for(let x=0;xa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let r=0;r({baseTag:x4t(["href"],s),bodyAttributes:e1e("bodyAttributes",s),defer:wM(s,_M.DEFER),encode:wM(s,_M.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:e1e("htmlAttributes",s),linkTags:DD("link",["rel","href"],s),metaTags:DD("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:DD("noscript",["innerHTML"],s),onChangeClientState:p4t(s),scriptTags:DD("script",["src","innerHTML"],s),styleTags:DD("style",["cssText"],s),title:f4t(s),titleAttributes:e1e("titleAttributes",s),prioritizeSeoTags:y4t(s,_M.PRIORITIZE_SEO_TAGS)}),CXe=s=>Array.isArray(s)?s.join(""):s,b4t=(s,t)=>{const r=Object.keys(s);for(let n=0;nArray.isArray(s)?s.reduce((r,n)=>(b4t(n,t)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},ORe=(s,t)=>({...s,[t]:void 0}),_4t=["noscript","script","style"],Oje=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),TXe=s=>Object.keys(s).reduce((t,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return t?`${t} ${n}`:n},""),w4t=(s,t,r,n)=>{const a=TXe(r),i=CXe(t);return a?`<${s} ${Zy}="true" ${a}>${Oje(i,n)}`:`<${s} ${Zy}="true">${Oje(i,n)}`},j4t=(s,t,r=!0)=>t.reduce((n,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,h)=>{const m=typeof i[h]>"u"?h:`${h}="${Oje(i[h],r)}"`;return d?`${d} ${m}`:m},""),o=i.innerHTML||i.cssText||"",c=_4t.indexOf(s)===-1;return`${n}<${s} ${Zy}="true" ${l}${c?"/>":`>${o}`}`},""),EXe=(s,t={})=>Object.keys(s).reduce((r,n)=>{const a=D4e[n];return r[a||n]=s[n],r},t),N4t=(s,t,r)=>{const n={key:t,[Zy]:!0},a=EXe(r,n);return[wt.createElement("title",a,t)]},dde=(s,t)=>t.map((r,n)=>{const a={key:n,[Zy]:!0};return Object.keys(r).forEach(i=>{const o=D4e[i]||i;if(o==="innerHTML"||o==="cssText"){const c=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=r[i]}),wt.createElement(s,a)}),_g=(s,t,r=!0)=>{switch(s){case"title":return{toComponent:()=>N4t(s,t.title,t.titleAttributes),toString:()=>w4t(s,t.title,t.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>EXe(t),toString:()=>TXe(t)};default:return{toComponent:()=>dde(s,t),toString:()=>j4t(s,t,r)}}},k4t=({metaTags:s,linkTags:t,scriptTags:r,encode:n})=>{const a=t1e(s,Jve.meta),i=t1e(t,Jve.link),l=t1e(r,Jve.script);return{priorityMethods:{toComponent:()=>[...dde("meta",a.priority),...dde("link",i.priority),...dde("script",l.priority)],toString:()=>`${_g("meta",a.priority,n)} ${_g("link",i.priority,n)} ${_g("script",l.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},S4t=s=>{const{baseTag:t,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:h,metaTags:m,scriptTags:x}=s,g={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:g,linkTags:h,metaTags:m,scriptTags:x}=k4t(s)),{priority:g,base:_g("base",t,n),bodyAttributes:_g("bodyAttributes",r,n),htmlAttributes:_g("htmlAttributes",a,n),link:_g("link",h,n),meta:_g("meta",m,n),noscript:_g("noscript",i,n),script:_g("script",x,n),style:_g("style",l,n),title:_g("title",{title:o,titleAttributes:c},n)}},Fje=S4t,U$=[],AXe=!!(typeof window<"u"&&window.document&&window.document.createElement),Bje=class{constructor(s,t){Vn(this,"instances",[]);Vn(this,"canUseDOM",AXe);Vn(this,"context");Vn(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?U$:this.instances,add:s=>{(this.canUseDOM?U$:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?U$:this.instances).indexOf(s);(this.canUseDOM?U$:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=Fje({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},C4t={},MXe=wt.createContext(C4t),f3,IXe=(f3=class extends k.Component{constructor(r){super(r);Vn(this,"helmetData");this.helmetData=new Bje(this.props.context||{},f3.canUseDOM)}render(){return wt.createElement(MXe.Provider,{value:this.helmetData.value},this.props.children)}},Vn(f3,"canUseDOM",AXe),f3),TE=(s,t)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${Zy}]`),a=[].slice.call(n),i=[];let l;return t&&t.length&&t.forEach(o=>{const c=document.createElement(s);for(const d in o)if(Object.prototype.hasOwnProperty.call(o,d))if(d==="innerHTML")c.innerHTML=o.innerHTML;else if(d==="cssText")c.styleSheet?c.styleSheet.cssText=o.cssText:c.appendChild(document.createTextNode(o.cssText));else{const h=d,m=typeof o[h]>"u"?"":o[h];c.setAttribute(d,m)}c.setAttribute(Zy,"true"),a.some((d,h)=>(l=h,c.isEqualNode(d)))?a.splice(l,1):i.push(c)}),a.forEach(o=>{var c;return(c=o.parentNode)==null?void 0:c.removeChild(o)}),i.forEach(o=>r.appendChild(o)),{oldTags:a,newTags:i}},zje=(s,t)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(Zy),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(Zy):r.getAttribute(Zy)!==l.join(",")&&r.setAttribute(Zy,l.join(","))},T4t=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=CXe(s)),zje("title",t)},FRe=(s,t)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:h,title:m,titleAttributes:x}=s;zje("body",n),zje("html",a),T4t(m,x);const g={baseTag:TE("base",r),linkTags:TE("link",i),metaTags:TE("meta",l),noscriptTags:TE("noscript",o),scriptTags:TE("script",d),styleTags:TE("style",h)},v={},j={};Object.keys(g).forEach(b=>{const{newTags:N,oldTags:S}=g[b];N.length&&(v[b]=N),S.length&&(j[b]=g[b].oldTags)}),t&&t(),c(s,v,j)},RD=null,E4t=s=>{RD&&cancelAnimationFrame(RD),s.defer?RD=requestAnimationFrame(()=>{FRe(s,()=>{RD=null})}):(FRe(s),RD=null)},A4t=E4t,BRe=class extends k.Component{constructor(){super(...arguments);Vn(this,"rendered",!1)}shouldComponentUpdate(t){return!h4t(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=v4t(t.get().map(i=>{const l={...i.props};return delete l.context,l}));IXe.canUseDOM?A4t(a):Fje&&(n=Fje(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}},fwe,il=(fwe=class extends k.Component{shouldComponentUpdate(s){return!l4t(ORe(this.props,"helmetData"),ORe(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 DRe(RRe.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 ${RRe.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),DRe(!t||typeof t=="string"||Array.isArray(t)&&!t.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let r={};return wt.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,l=Object.keys(i).reduce((c,d)=>(c[m4t[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 Bje)){const a=n;n=new Bje(a.context,!0),delete r.helmetData}return n?wt.createElement(BRe,{...r,context:n.value}):wt.createElement(MXe.Consumer,null,a=>wt.createElement(BRe,{...r,context:a}))}},Vn(fwe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),fwe);const M4t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ni(async()=>{const{default:n}=await Promise.resolve().then(()=>NP);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)};class R4e extends Error{constructor(t,r="FunctionsError",n){super(t),this.name=r,this.context=n}}class I4t extends R4e{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class P4t extends R4e{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class L4t extends R4e{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var $je;(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"})($je||($je={}));var D4t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class R4t{constructor(t,{headers:r={},customFetch:n,region:a=$je.Any}={}){this.url=t,this.headers=r,this.region=a,this.fetch=M4t(n)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,r={}){var n;return D4t(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=r;let o={},{region:c}=r;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const h=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(v=>{throw new I4t(v)}),m=h.headers.get("x-relay-error");if(m&&m==="true")throw new P4t(h);if(!h.ok)throw new L4t(h);let x=((n=h.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),g;return x==="application/json"?g=yield h.json():x==="application/octet-stream"?g=yield h.blob():x==="text/event-stream"?g=h:x==="multipart/form-data"?g=yield h.formData():g=yield h.text(),{data:g,error:null}}catch(a){return{data:null,error:a}}})}}var ap={},O4e={},Jfe={},DB={},epe={},tpe={},O4t=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")},dI=O4t();const F4t=dI.fetch,PXe=dI.fetch.bind(dI),LXe=dI.Headers,B4t=dI.Request,z4t=dI.Response,NP=Object.freeze(Object.defineProperty({__proto__:null,Headers:LXe,Request:B4t,Response:z4t,default:PXe,fetch:F4t},Symbol.toStringTag,{value:"Module"})),$4t=Wbt(NP);var spe={};Object.defineProperty(spe,"__esModule",{value:!0});let U4t=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};spe.default=U4t;var DXe=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(tpe,"__esModule",{value:!0});const q4t=DXe($4t),V4t=DXe(spe);let H4t=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=q4t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,r){return this.headers=Object.assign({},this.headers),this.headers[t]=r,this}then(t,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let a=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,h=null,m=null,x=i.status,g=i.statusText;if(i.ok){if(this.method!=="HEAD"){const N=await i.text();N===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?h=N:h=JSON.parse(N))}const j=(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("/");j&&b&&b.length>1&&(m=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(d={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,m=null,x=406,g="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{const j=await i.text();try{d=JSON.parse(j),Array.isArray(d)&&i.status===404&&(h=[],d=null,x=200,g="OK")}catch{i.status===404&&j===""?(x=204,g="No Content"):d={message:j}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,x=200,g="OK"),d&&this.shouldThrowOnError)throw new V4t.default(d)}return{error:d,data:h,count:m,status:x,statusText:g}});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}};tpe.default=H4t;var G4t=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(epe,"__esModule",{value:!0});const W4t=G4t(tpe);let K4t=class extends W4t.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}};epe.default=K4t;var Y4t=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(DB,"__esModule",{value:!0});const Z4t=Y4t(epe);let X4t=class extends Z4t.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}};DB.default=X4t;var Q4t=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Jfe,"__esModule",{value:!0});const OD=Q4t(DB);let J4t=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 OD.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 OD.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&o.push(this.headers.Prefer),a&&o.push(`count=${a}`),i||o.push("missing=default"),this.headers.Prefer=o.join(","),Array.isArray(t)){const c=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(c.length>0){const d=[...new Set(c)].map(h=>`"${h}"`);this.url.searchParams.set("columns",d.join(","))}}return new OD.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 OD.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 OD.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Jfe.default=J4t;var rpe={},npe={};Object.defineProperty(npe,"__esModule",{value:!0});npe.version=void 0;npe.version="0.0.0-automated";Object.defineProperty(rpe,"__esModule",{value:!0});rpe.DEFAULT_HEADERS=void 0;const e3t=npe;rpe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${e3t.version}`};var RXe=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(O4e,"__esModule",{value:!0});const t3t=RXe(Jfe),s3t=RXe(DB),r3t=rpe;let n3t=class OXe{constructor(t,{headers:r={},schema:n,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},r3t.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(t){const r=new URL(`${this.url}/${t}`);return new t3t.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new OXe(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,r={},{head:n=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;n||a?(l=n?"HEAD":"GET",Object.entries(r).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{o.searchParams.append(h,m)})):(l="POST",c=r);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new s3t.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};O4e.default=n3t;var kP=su&&su.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ap,"__esModule",{value:!0});ap.PostgrestError=ap.PostgrestBuilder=ap.PostgrestTransformBuilder=ap.PostgrestFilterBuilder=ap.PostgrestQueryBuilder=ap.PostgrestClient=void 0;const FXe=kP(O4e);ap.PostgrestClient=FXe.default;const BXe=kP(Jfe);ap.PostgrestQueryBuilder=BXe.default;const zXe=kP(DB);ap.PostgrestFilterBuilder=zXe.default;const $Xe=kP(epe);ap.PostgrestTransformBuilder=$Xe.default;const UXe=kP(tpe);ap.PostgrestBuilder=UXe.default;const qXe=kP(spe);ap.PostgrestError=qXe.default;var a3t=ap.default={PostgrestClient:FXe.default,PostgrestQueryBuilder:BXe.default,PostgrestFilterBuilder:zXe.default,PostgrestTransformBuilder:$Xe.default,PostgrestBuilder:UXe.default,PostgrestError:qXe.default};const{PostgrestClient:i3t,PostgrestQueryBuilder:BUs,PostgrestFilterBuilder:zUs,PostgrestTransformBuilder:$Us,PostgrestBuilder:UUs,PostgrestError:qUs}=a3t;let Uje;typeof window>"u"?Uje=require("ws"):Uje=window.WebSocket;const o3t="2.11.10",l3t={"X-Client-Info":`realtime-js/${o3t}`},c3t="1.0.0",VXe=1e4,d3t=1e3;var jM;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(jM||(jM={}));var cf;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(cf||(cf={}));var zy;(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"})(zy||(zy={}));var qje;(function(s){s.websocket="websocket"})(qje||(qje={}));var L4;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(L4||(L4={}));class u3t{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 HXe{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 lc;(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"})(lc||(lc={}));const zRe=(s,t,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(t).reduce((i,l)=>(i[l]=h3t(l,s,t,a),i),{})},h3t=(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)?GXe(i,l):Vje(l)},GXe=(s,t)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return x3t(t,r)}switch(s){case lc.bool:return m3t(t);case lc.float4:case lc.float8:case lc.int2:case lc.int4:case lc.int8:case lc.numeric:case lc.oid:return f3t(t);case lc.json:case lc.jsonb:return p3t(t);case lc.timestamp:return g3t(t);case lc.abstime:case lc.date:case lc.daterange:case lc.int4range:case lc.int8range:case lc.money:case lc.reltime:case lc.text:case lc.time:case lc.timestamptz:case lc.timetz:case lc.tsrange:case lc.tstzrange:return Vje(t);default:return Vje(t)}},Vje=s=>s,m3t=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},f3t=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},p3t=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},x3t=(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=>GXe(t,o))}return s},g3t=s=>typeof s=="string"?s.replace(" ","T"):s,WXe=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class s1e{constructor(t,r,n={},a=VXe){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 $Re;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})($Re||($Re={}));class UO{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=UO.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=UO.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=UO.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,r,n,a){const i=this.cloneDeep(t),l=this.transformState(r),o={},c={};return this.map(i,(d,h)=>{l[d]||(c[d]=h)}),this.map(l,(d,h)=>{const m=i[d];if(m){const x=h.map(b=>b.presence_ref),g=m.map(b=>b.presence_ref),v=h.filter(b=>g.indexOf(b.presence_ref)<0),j=m.filter(b=>x.indexOf(b.presence_ref)<0);v.length>0&&(o[d]=v),j.length>0&&(c[d]=j)}else o[d]=h}),this.syncDiff(i,{joins:o,leaves:c},n,a)}static syncDiff(t,r,n,a){const{joins:i,leaves:l}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const h=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),h.length>0){const m=t[o].map(g=>g.presence_ref),x=h.filter(g=>m.indexOf(g.presence_ref)<0);t[o].unshift(...x)}n(o,h,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const h=c.map(m=>m.presence_ref);d=d.filter(m=>h.indexOf(m.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,r){return Object.getOwnPropertyNames(t).map(n=>r(n,t[n]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((r,n)=>{const a=t[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var URe;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(URe||(URe={}));var qRe;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(qRe||(qRe={}));var Nb;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Nb||(Nb={}));class F4e{constructor(t,r={config:{}},n){this.topic=t,this.params=r,this.socket=n,this.bindings={},this.state=cf.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 s1e(this,zy.join,this.params,this.timeout),this.rejoinTimer=new HXe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=cf.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=cf.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=cf.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=cf.errored,this.rejoinTimer.scheduleTimeout())}),this._on(zy.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new UO(this),this.broadcastEndpointURL=WXe(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,r=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:l,private:o}}=this.params;this._onError(h=>t==null?void 0:t(Nb.CHANNEL_ERROR,h)),this._onClose(()=>t==null?void 0:t(Nb.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&a!==void 0?a:[],private:o};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:d},c)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:h})=>{var m;if(this.socket.setAuth(),h===void 0){t==null||t(Nb.SUBSCRIBED);return}else{const x=this.bindings.postgres_changes,g=(m=x==null?void 0:x.length)!==null&&m!==void 0?m:0,v=[];for(let j=0;j{this.state=cf.errored,t==null||t(Nb.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(Nb.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=cf.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(zy.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new s1e(this,zy.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 s1e(this,t,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,r,n){return r}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,r,n){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:h}=zy;if(n&&[o,c,d,h].indexOf(l)>=0&&n!==this._joinRef())return;let x=this._onMessage(l,r,n);if(r&&!x)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(g=>{var v,j,b;return((v=g.filter)===null||v===void 0?void 0:v.event)==="*"||((b=(j=g.filter)===null||j===void 0?void 0:j.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===l}).map(g=>g.callback(x,n)):(i=this.bindings[l])===null||i===void 0||i.filter(g=>{var v,j,b,N,S,T;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in g){const A=g.id,P=(v=g.filter)===null||v===void 0?void 0:v.event;return A&&((j=r.ids)===null||j===void 0?void 0:j.includes(A))&&(P==="*"||(P==null?void 0:P.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const A=(S=(N=g==null?void 0:g.filter)===null||N===void 0?void 0:N.event)===null||S===void 0?void 0:S.toLocaleLowerCase();return A==="*"||A===((T=r==null?void 0:r.event)===null||T===void 0?void 0:T.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===l}).map(g=>{if(typeof x=="object"&&"ids"in x){const v=x.data,{schema:j,table:b,commit_timestamp:N,type:S,errors:T}=v;x=Object.assign(Object.assign({},{schema:j,table:b,commit_timestamp:N,eventType:S,new:{},old:{},errors:T}),this._getPayloadRecords(v))}g.callback(x,n)})}_isClosed(){return this.state===cf.closed}_isJoined(){return this.state===cf.joined}_isJoining(){return this.state===cf.joining}_isLeaving(){return this.state===cf.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&&F4e.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(zy.close,{},t)}_onError(t){this._on(zy.error,{},r=>t(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=cf.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=zRe(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=zRe(t.columns,t.old_record)),r}}const VRe=()=>{},y3t=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class v3t{constructor(t,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=l3t,this.params={},this.timeout=VXe,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=VRe,this.ref=0,this.logger=VRe,this.conn=null,this.sendBuffer=[],this.serializer=new u3t,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>ni(async()=>{const{default:c}=await Promise.resolve().then(()=>NP);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${qje.websocket}`,this.httpEndpoint=WXe(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 HXe(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=Uje),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 b3t(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:c3t}))}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 jM.connecting:return L4.Connecting;case jM.open:return L4.Open;case jM.closing:return L4.Closing;default:return L4.Closed}}isConnected(){return this.connectionState()===L4.Open}channel(t,r={config:{}}){const n=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new F4e(`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(zy.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(d3t,"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(zy.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([y3t],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class b3t{constructor(t,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=jM.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=n.close}}class B4e extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function yh(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class _3t extends B4e{constructor(t,r){super(t),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Hje extends B4e{constructor(t,r){super(t),this.name="StorageUnknownError",this.originalError=r}}var w3t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const KXe=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ni(async()=>{const{default:n}=await Promise.resolve().then(()=>NP);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},j3t=()=>w3t(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ni(()=>Promise.resolve().then(()=>NP),void 0)).Response:Response}),Gje=s=>{if(Array.isArray(s))return s.map(r=>Gje(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]=Gje(n)}),t};var H5=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const r1e=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),N3t=(s,t,r)=>H5(void 0,void 0,void 0,function*(){const n=yield j3t();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{t(new _3t(r1e(a),s.status||500))}).catch(a=>{t(new Hje(r1e(a),a))}):t(new Hje(r1e(s),s))}),k3t=(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 RB(s,t,r,n,a,i){return H5(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(r,k3t(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=>N3t(c,o,n))})})}function kue(s,t,r,n){return H5(this,void 0,void 0,function*(){return RB(s,"GET",t,r,n)})}function Xw(s,t,r,n,a){return H5(this,void 0,void 0,function*(){return RB(s,"POST",t,n,a,r)})}function S3t(s,t,r,n,a){return H5(this,void 0,void 0,function*(){return RB(s,"PUT",t,n,a,r)})}function C3t(s,t,r,n){return H5(this,void 0,void 0,function*(){return RB(s,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function YXe(s,t,r,n,a){return H5(this,void 0,void 0,function*(){return RB(s,"DELETE",t,n,a,r)})}var Xf=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const T3t={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},HRe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class E3t{constructor(t,r={},n,a){this.url=t,this.headers=r,this.bucketId=n,this.fetch=KXe(a)}uploadOrUpdate(t,r,n,a){return Xf(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},HRe),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(r),h=this._getFinalPath(d),m=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),x=yield m.json();return m.ok?{data:{path:d,id:x.Id,fullPath:x.Key},error:null}:{data:null,error:x}}catch(i){if(yh(i))return{data:null,error:i};throw i}})}upload(t,r,n){return Xf(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,r,n)})}uploadToSignedUrl(t,r,n,a){return Xf(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:HRe.upsert},a),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.append("cacheControl",d.cacheControl)):(c=n,h["cache-control"]=`max-age=${d.cacheControl}`,h["content-type"]=d.contentType);const m=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:h}),x=yield m.json();return m.ok?{data:{path:i,fullPath:x.Key},error:null}:{data:null,error:x}}catch(c){if(yh(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,r){return Xf(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 Xw(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 B4e("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(n){if(yh(n))return{data:null,error:n};throw n}})}update(t,r,n){return Xf(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,r,n)})}move(t,r,n){return Xf(this,void 0,void 0,function*(){try{return{data:yield Xw(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(yh(a))return{data:null,error:a};throw a}})}copy(t,r,n){return Xf(this,void 0,void 0,function*(){try{return{data:{path:(yield Xw(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(yh(a))return{data:null,error:a};throw a}})}createSignedUrl(t,r,n){return Xf(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield Xw(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(yh(a))return{data:null,error:a};throw a}})}createSignedUrls(t,r,n){return Xf(this,void 0,void 0,function*(){try{const a=yield Xw(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(yh(a))return{data:null,error:a};throw a}})}download(t,r){return Xf(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 kue(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(yh(o))return{data:null,error:o};throw o}})}info(t){return Xf(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{const n=yield kue(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:Gje(n),error:null}}catch(n){if(yh(n))return{data:null,error:n};throw n}})}exists(t){return Xf(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{return yield C3t(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(yh(n)&&n instanceof Hje){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 Xf(this,void 0,void 0,function*(){try{return{data:yield YXe(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(r){if(yh(r))return{data:null,error:r};throw r}})}list(t,r,n){return Xf(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},T3t),r),{prefix:t||""});return{data:yield Xw(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(yh(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 A3t="2.7.1",M3t={"X-Client-Info":`storage-js/${A3t}`};var EE=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class I3t{constructor(t,r={},n){this.url=t,this.headers=Object.assign(Object.assign({},M3t),r),this.fetch=KXe(n)}listBuckets(){return EE(this,void 0,void 0,function*(){try{return{data:yield kue(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(yh(t))return{data:null,error:t};throw t}})}getBucket(t){return EE(this,void 0,void 0,function*(){try{return{data:yield kue(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(r){if(yh(r))return{data:null,error:r};throw r}})}createBucket(t,r={public:!1}){return EE(this,void 0,void 0,function*(){try{return{data:yield Xw(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(yh(n))return{data:null,error:n};throw n}})}updateBucket(t,r){return EE(this,void 0,void 0,function*(){try{return{data:yield S3t(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(yh(n))return{data:null,error:n};throw n}})}emptyBucket(t){return EE(this,void 0,void 0,function*(){try{return{data:yield Xw(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(yh(r))return{data:null,error:r};throw r}})}deleteBucket(t){return EE(this,void 0,void 0,function*(){try{return{data:yield YXe(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(yh(r))return{data:null,error:r};throw r}})}}class P3t extends I3t{constructor(t,r={},n){super(t,r,n)}from(t){return new E3t(this.url,this.headers,t,this.fetch)}}const L3t="2.49.10";let yR="";typeof Deno<"u"?yR="deno":typeof document<"u"?yR="web":typeof navigator<"u"&&navigator.product==="ReactNative"?yR="react-native":yR="node";const D3t={"X-Client-Info":`supabase-js-${yR}/${L3t}`},R3t={headers:D3t},O3t={schema:"public"},F3t={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},B3t={};var z3t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const $3t=s=>{let t;return s?t=s:typeof fetch>"u"?t=PXe:t=fetch,(...r)=>t(...r)},U3t=()=>typeof Headers>"u"?LXe:Headers,q3t=(s,t,r)=>{const n=$3t(r),a=U3t();return(i,l)=>z3t(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 V3t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};function H3t(s){return s.endsWith("/")?s:s+"/"}function G3t(s,t){var r,n;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:h,global:m}=t,x={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},h),l),global:Object.assign(Object.assign(Object.assign({},m),o),{headers:Object.assign(Object.assign({},(r=m==null?void 0:m.headers)!==null&&r!==void 0?r:{}),(n=o==null?void 0:o.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>V3t(this,void 0,void 0,function*(){return""})};return s.accessToken?x.accessToken=s.accessToken:delete x.accessToken,x}const ZXe="2.69.1",iA=30*1e3,Wje=3,n1e=Wje*iA,W3t="http://localhost:9999",K3t="supabase.auth.token",Y3t={"X-Client-Info":`gotrue-js/${ZXe}`},Kje="X-Supabase-Api-Version",XXe={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Z3t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,X3t=6e5;class z4e extends Error{constructor(t,r,n){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Yi(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class Q3t extends z4e{constructor(t,r,n){super(t,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function J3t(s){return Yi(s)&&s.name==="AuthApiError"}class QXe extends z4e{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}}class z2 extends z4e{constructor(t,r,n,a){super(t,n,a),this.name=r,this.status=n}}class Uw extends z2{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function e5t(s){return Yi(s)&&s.name==="AuthSessionMissingError"}class a1e extends z2{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class q$ extends z2{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class V$ extends z2{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 t5t(s){return Yi(s)&&s.name==="AuthImplicitGrantRedirectError"}class GRe extends z2{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 Yje extends z2{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}}function i1e(s){return Yi(s)&&s.name==="AuthRetryableFetchError"}class WRe extends z2{constructor(t,r,n){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class qO extends z2{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const KRe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),YRe=` \r=`.split(""),s5t=(()=>{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 ZRe(s){const t=[],r=l=>{t.push(String.fromCodePoint(l))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{a5t(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 n5t(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}r5t(n,t)}}function a5t(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 i5t(s){const t=[],r={queue:0,queuedBits:0},n=a=>{t.push(a)};for(let a=0;at.push(r)),new Uint8Array(t)}function l5t(s){return Math.round(Date.now()/1e3)+s}function c5t(){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 lv=()=>typeof window<"u"&&typeof document<"u",ak={tested:!1,writable:!1},VO=()=>{if(!lv())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ak.tested)return ak.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),ak.tested=!0,ak.writable=!0}catch{ak.tested=!0,ak.writable=!1}return ak.writable};function d5t(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 eQe=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ni(async()=>{const{default:n}=await Promise.resolve().then(()=>NP);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},u5t=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",tQe=async(s,t,r)=>{await s.setItem(t,JSON.stringify(r))},H$=async(s,t)=>{const r=await s.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},G$=async(s,t)=>{await s.removeItem(t)};class ape{constructor(){this.promise=new ape.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}}ape.promiseConstructor=Promise;function o1e(s){const t=s.split(".");if(t.length!==3)throw new qO("Invalid JWT structure");for(let n=0;n{setTimeout(()=>t(null),s)})}function m5t(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 f5t(s){return("0"+s.toString(16)).substr(-2)}function p5t(){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,f5t).join("")}async function x5t(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 g5t(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 x5t(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function AE(s,t,r=!1){const n=p5t();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await tQe(s,`${t}-code-verifier`,a);const i=await g5t(n);return[i,n===i?"plain":"s256"]}const y5t=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function v5t(s){const t=s.headers.get(Kje);if(!t||!t.match(y5t))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function b5t(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 _5t(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 w5t=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),j5t=[502,503,504];async function XRe(s){var t;if(!u5t(s))throw new Yje(k4(s),0);if(j5t.includes(s.status))throw new Yje(k4(s),s.status);let r;try{r=await s.json()}catch(i){throw new QXe(k4(i),i)}let n;const a=v5t(s);if(a&&a.getTime()>=XXe["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 WRe(k4(r),s.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(n==="session_not_found")throw new Uw}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 WRe(k4(r),s.status,r.weak_password.reasons);throw new Q3t(k4(r),s.status||500,n)}const N5t=(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 bo(s,t,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Kje]||(i[Kje]=XXe["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 k5t(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 k5t(s,t,r,n,a,i){const l=N5t(t,n,a,i);let o;try{o=await s(r,Object.assign({},l))}catch(c){throw console.error(c),new Yje(k4(c),0)}if(o.ok||await XRe(o),n!=null&&n.noResolveJson)return o;try{return await o.json()}catch(c){await XRe(c)}}function qw(s){var t;let r=null;E5t(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=l5t(s.expires_in)));const n=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:r,user:n},error:null}}function QRe(s){const t=qw(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 hj(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function S5t(s){return{data:s,error:null}}function C5t(s){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,l=w5t(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 T5t(s){return s}function E5t(s){return s.access_token&&s.refresh_token&&s.expires_in}var A5t=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&&(g.forEach(v=>{const j=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(v.split(";")[1].split("=")[1]);d[`${b}Page`]=j}),d.total=parseInt(x)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Yi(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await bo(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:hj})}catch(r){if(Yi(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){try{return await bo(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:hj})}catch(n){if(Yi(n))return{data:{user:null},error:n};throw n}}async deleteUser(t,r=!1){try{return await bo(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:hj})}catch(n){if(Yi(n))return{data:{user:null},error:n};throw n}}async _listFactors(t){try{const{data:r,error:n}=await bo(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(Yi(r))return{data:null,error:r};throw r}}async _deleteFactor(t){try{return{data:await bo(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(Yi(r))return{data:null,error:r};throw r}}}const I5t={getItem:s=>VO()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{VO()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{VO()&&globalThis.localStorage.removeItem(s)}};function JRe(s={}){return{getItem:t=>s[t]||null,setItem:(t,r)=>{s[t]=r},removeItem:t=>{delete s[t]}}}function P5t(){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 ME={debug:!!(globalThis&&VO()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class sQe extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class L5t extends sQe{}async function D5t(s,t,r){ME.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),ME.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){ME.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{ME.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw ME.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new L5t(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(ME.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()}}))}P5t();const R5t={url:W3t,storageKey:K3t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Y3t,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function eOe(s,t,r){return await r()}class Q8{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=Q8.nextInstanceID,Q8.nextInstanceID+=1,this.instanceID>0&&lv()&&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({},R5t),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 M5t({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=eQe(a.fetch),this.lock=a.lock||eOe,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:lv()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=D5t:this.lock=eOe,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:VO()?this.storage=I5t:(this.memoryStorage={},this.storage=JRe(this.memoryStorage)):(this.memoryStorage={},this.storage=JRe(this.memoryStorage)),lv()&&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} (${ZXe}) ${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=d5t(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),lv()&&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),t5t(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 Yi(r)?{error:r}:{error:new QXe("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,n,a;try{const i=await bo(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:qw}),{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(Yi(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var r,n,a;try{let i;if("email"in t){const{email:h,password:m,options:x}=t;let g=null,v=null;this.flowType==="pkce"&&([g,v]=await AE(this.storage,this.storageKey)),i=await bo(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:x==null?void 0:x.emailRedirectTo,body:{email:h,password:m,data:(r=x==null?void 0:x.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken},code_challenge:g,code_challenge_method:v},xform:qw})}else if("phone"in t){const{phone:h,password:m,options:x}=t;i=await bo(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=x==null?void 0:x.data)!==null&&n!==void 0?n:{},channel:(a=x==null?void 0:x.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken}},xform:qw})}else throw new q$("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(Yi(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 bo(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:QRe})}else if("phone"in t){const{phone:i,password:l,options:o}=t;r=await bo(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:QRe})}else throw new q$("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 a1e}:(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(Yi(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 H$(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:l}=await bo(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:n},xform:qw});if(await G$(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new a1e}:(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(Yi(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 bo(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:qw}),{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 a1e}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(r){if(Yi(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(t){var r,n,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,h=null;this.flowType==="pkce"&&([d,h]=await AE(this.storage,this.storageKey));const{error:m}=await bo(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:h}=await bo(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(a=c==null?void 0:c.data)!==null&&a!==void 0?a:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(l=c==null?void 0:c.channel)!==null&&l!==void 0?l:"sms"}});return{data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:h}}throw new q$("You must provide either an email or phone number.")}catch(o){if(Yi(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 bo(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:qw});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(Yi(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 AE(this.storage,this.storageKey)),await bo(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:S5t})}catch(i){if(Yi(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 Uw;const{error:a}=await bo(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Yi(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 bo(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 bo(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 q$("You must provide either an email or phone number and a type")}catch(r){if(Yi(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 H$(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const n=t.expires_at?t.expires_at*1e3-Date.now()(!l&&d==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),l=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,h))})}return{data:{session:t},error:null}}const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await bo(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:hj}):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 Uw}:await bo(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:hj})})}catch(r){if(Yi(r))return e5t(r)&&(await this._removeSession(),await G$(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 Uw;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await AE(this.storage,this.storageKey));const{data:d,error:h}=await bo(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:hj});if(h)throw h;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(n){if(Yi(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 Uw;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:l}=o1e(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(Yi(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 Uw;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(Yi(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(t,r){try{if(!lv())throw new V$("No browser detected.");if(t.error||t.error_description||t.error_code)throw new V$(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 GRe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new V$("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 GRe("No code detected.");const{data:S,error:T}=await this._exchangeCodeForSession(t.code);if(T)throw T;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:S.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new V$("No session defined in URL");const h=Math.round(Date.now()/1e3),m=parseInt(o);let x=h+m;c&&(x=parseInt(c));const g=x-h;g*1e3<=iA&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${m}s`);const v=x-m;h-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,x,h):h-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,x,h);const{data:j,error:b}=await this._getUser(i);if(b)throw b;const N={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:x,refresh_token:l,token_type:d,user:j.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:t.type},error:null}}catch(n){if(Yi(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 H$(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&&!(J3t(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await G$(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const r=c5t(),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 AE(this.storage,this.storageKey,!0));try{return await bo(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(Yi(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(Yi(r))return{data:null,error:r};throw r}}async linkIdentity(t){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var l,o,c,d,h;const{data:m,error:x}=i;if(x)throw x;const g=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 bo(this.fetch,"GET",g,{headers:this.headers,jwt:(h=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(a)throw a;return lv()&&!(!((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(Yi(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 bo(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(Yi(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 m5t(async a=>(a>0&&await h5t(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await bo(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:qw})),(a,i)=>{const l=200*Math.pow(2,a);return i&&i1e(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(),iA);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)/iA);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${iA}ms, refresh threshold is ${Wje} ticks`),a<=Wje&&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 sQe)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!lv()||!(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 AE(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 bo(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(Yi(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 bo(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(Yi(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 bo(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(Yi(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 bo(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(Yi(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}=o1e(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(t,r={keys:[]}){let n=r.keys.find(l=>l.kid===t);if(n||(n=this.jwks.keys.find(l=>l.kid===t),n&&this.jwks_cached_at+X3t>Date.now()))return n;const{data:a,error:i}=await bo(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 qO("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(l=>l.kid===t),!n)throw new qO("No matching signing key found in JWKS");return n}async getClaims(t,r={keys:[]}){try{let n=t;if(!n){const{data:g,error:v}=await this.getSession();if(v||!g.session)return{data:null,error:v};n=g.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=o1e(n);if(b5t(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:g}=await this.getUser(n);if(g)throw g;return{data:{claims:i,header:a,signature:l},error:null}}const d=_5t(a.alg),h=await this.fetchJwk(a.kid,r),m=await crypto.subtle.importKey("jwk",h,d,!0,["verify"]);if(!await crypto.subtle.verify(d,m,l,o5t(`${o}.${c}`)))throw new qO("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(n){if(Yi(n))return{data:null,error:n};throw n}}}Q8.nextInstanceID=0;const O5t=Q8;class F5t extends O5t{constructor(t){super(t)}}var B5t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class z5t{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=H3t(t),c=new URL(o);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const d=`sb-${c.hostname.split(".")[0]}-auth-token`,h={db:O3t,realtime:B3t,auth:Object.assign(Object.assign({},F3t),{storageKey:d}),global:R3t},m=G3t(n??{},h);this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=m.global.headers)!==null&&i!==void 0?i:{},m.accessToken?(this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(x,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=m.auth)!==null&&l!==void 0?l:{},this.headers,m.global.fetch),this.fetch=q3t(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 i3t(new URL("rest/v1",c).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch}),m.accessToken||this._listenForAuthEvents()}get functions(){return new R4t(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new P3t(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 B5t(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,h){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new F5t({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),d),storageKey:i,autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,flowType:l,lock:o,debug:c,fetch:h,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new v3t(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 $5t=(s,t,r)=>new z5t(s,t,r),U5t="https://relzejiswnotikjgvjhz.supabase.co",q5t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",H=$5t(U5t,q5t,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),rQe=k.createContext(void 0),V5t=({children:s})=>{const[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState(!1),[j,b]=k.useState(null),[N,S]=k.useState([]),[T,A]=k.useState(null),P=k.useRef(null),D=k.useRef(!1),B=k.useRef(!1),z=vr(),F=()=>{h(!1),x(!1),v(!1),b(null),S([]),A(null),P.current=null,D.current=!1},$=async Y=>{if(!(D.current&&P.current===Y)&&!B.current){B.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",Y);const[{data:ne,error:de},{data:ce,error:ae},{data:ie,error:me}]=await Promise.all([H.rpc("has_role",{_user_id:Y,_role:"admin"}),H.rpc("has_role",{_user_id:Y,_role:"brokerage_manager"}),H.rpc("has_role",{_user_id:Y,_role:"coach"})]);if(de||ae)console.error("Role RPC errors:",{isAdminError:de,isBrokerError:ae,isCoachError:me}),h(!1),x(!1),v(!1);else{const be=!!ne,Oe=!!ce,Me=!!ie;console.log("RPC roles result:",{adminValue:be,brokerValue:Oe,coachValue:Me}),h(be),x(Oe),v(Me)}const{data:oe,error:ge}=await H.from("profiles").select("brokerage_id").eq("id",Y).single();if(b(!ge&&oe?oe.brokerage_id:null),ce){console.log("Fetching managed brokerages for user:",Y);const{data:be,error:Oe}=await H.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",Y);if(console.log("Managed brokerage assignments result:",{assignments:be,assignmentsError:Oe}),Oe||!be){console.error("Error fetching managed brokerage assignments:",Oe),S([]);return}const Me=Array.from(new Set(be.map(Se=>Se.brokerage_id).filter(Boolean)));if(Me.length===0){S([]);return}const{data:Pe,error:Ee}=await H.from("brokerages").select("id, name").in("id",Me);if(console.log("Managed brokerages details result:",{brokeragesData:Pe,brokeragesError:Ee}),Ee||!Pe){console.error("Error fetching managed brokerages details:",Ee),S([]);return}const $e=Pe.map(Se=>({id:Se.id,name:Se.name})).sort((Se,ze)=>Me.indexOf(Se.id)-Me.indexOf(ze.id));console.log("Parsed managed brokerages:",$e),S($e),$e.length>0&&A(Se=>Se??$e[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),S([]);P.current=Y,D.current=!0}catch(ne){console.error("Unexpected error in checkRoles:",ne),F()}finally{B.current=!1,c(!1)}}};k.useEffect(()=>{let Y=!0,ne=!1;const de=()=>{!Y||ne||(ne=!0,l(!1))},{data:{subscription:ce}}=H.auth.onAuthStateChange((me,oe)=>{console.log("Auth event:",me),Y&&(a(oe),r((oe==null?void 0:oe.user)??null),de(),me==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{z("/profile?reset=true")},100)),oe!=null&&oe.user?(!D.current||P.current!==oe.user.id)&&setTimeout(()=>{$(oe.user.id)},0):(F(),c(!1)))}),ae=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),de()},4e3);return(async()=>{try{const{data:{session:me}}=await H.auth.getSession();if(!Y)return;a(me),r((me==null?void 0:me.user)??null),me!=null&&me.user?await $(me.user.id):F()}catch(me){console.error("Error restoring auth session:",me),Y&&(a(null),r(null),F())}finally{de()}})(),()=>{Y=!1,window.clearTimeout(ae),ce.unsubscribe()}},[]);const X=async(Y,ne)=>{const{error:de}=await H.auth.signInWithPassword({email:Y,password:ne});if(de)throw ue.error(de.message),de;ue.success("Welcome back!");const ce=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),z(ce)},K=async(Y,ne,de)=>{var oe;const ce=`${window.location.origin}/dashboard`,ae=localStorage.getItem("levelup_referral_code")||null,{data:ie,error:me}=await H.auth.signUp({email:Y,password:ne,options:{emailRedirectTo:ce,data:{name:de,referred_by_code:ae}}});if(me)throw ue.error(me.message),me;if(ae&&((oe=ie.user)!=null&&oe.id))try{await H.from("profiles").update({referred_by_code:ae}).eq("id",ie.user.id),localStorage.removeItem("levelup_referral_code")}catch(ge){console.warn("Failed to attach referral code to profile",ge)}ue.success("Account created! Welcome to LevelUp."),z("/dashboard")},Q=async()=>{try{const{data:{session:Y}}=await H.auth.getSession();if(Y){const{error:ne}=await H.auth.signOut();ne?ne.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",ne.message):(console.error("Sign out error:",ne),ue.error(ne.message)):ue.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),a(null),h(!1),x(!1),b(null),S([]),A(null),z("/auth")}catch(Y){console.error("Unexpected sign out error:",Y),z("/auth")}};return e.jsx(rQe.Provider,{value:{user:t,session:n,loading:i,rolesLoading:o,signIn:X,signUp:K,signOut:Q,isAdmin:d,isBrokerageManager:m,isCoach:g,brokerageId:j,managedBrokerages:N,selectedBrokerageId:T,setSelectedBrokerageId:A},children:s})},As=()=>{const s=k.useContext(rQe);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},nQe=k.createContext({onlineUsers:[],totalOnline:0}),H5t=async s=>{try{const{data:t}=await H.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:r}=H.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return r.publicUrl}}catch{}},G5t=({children:s})=>{const{user:t,brokerageId:r,isAdmin:n}=As(),[a,i]=k.useState([]),[l,o]=k.useState(null);k.useEffect(()=>{if(!t)return;let d=!1;H.auth.getSession().then(({data:m})=>{var g;const x=(g=m.session)==null?void 0:g.access_token;if(x)try{H.realtime.setAuth(x)}catch{}});const h=H.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return h.on("presence",{event:"sync"},()=>{const m=h.presenceState(),x=[];Object.entries(m).forEach(([g,v])=>{if(v&&v.length>0){const j=v[0];x.push({id:g,name:j.name||"Unknown",avatarUrl:j.avatarUrl,brokerageId:j.brokerageId,onlineSince:j.onlineSince})}}),console.log("[Presence] sync, users:",x.length,x),i(x)}).on("presence",{event:"join"},({key:m,newPresences:x})=>{console.log("[Presence] join",m,x)}).on("presence",{event:"leave"},({key:m})=>{console.log("[Presence] leave",m)}).subscribe(async(m,x)=>{var g;if(console.log("[Presence] subscribe status:",m,x),m==="SUBSCRIBED"&&!d){const{data:v}=await H.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),j=await H5t(t.id),b=await h.track({name:(v==null?void 0:v.name)||((g=t.email)==null?void 0:g.split("@")[0])||"User",avatarUrl:j,brokerageId:v==null?void 0:v.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",b)}}),o(h),()=>{d=!0;try{h.untrack()}catch{}H.removeChannel(h)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(n||r&&d.brokerageId===r||!r&&!d.brokerageId));return e.jsx(nQe.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},aQe=()=>k.useContext(nQe),iQe=k.createContext(void 0),ik="levelup_admin_session",Mw="levelup_impersonation",l1e="levelup_impersonation_return",W5t=({children:s})=>{const[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1);k.useEffect(()=>{const d=sessionStorage.getItem(Mw);if(d)try{const h=JSON.parse(d);r(!0),a(h)}catch{sessionStorage.removeItem(Mw)}},[]);const o=async(d,h)=>{l(!0);try{const{data:{session:m}}=await H.auth.getSession();if(!m)return ue.error("No active session found"),!1;const x={access_token:m.access_token,refresh_token:m.refresh_token};sessionStorage.setItem(ik,JSON.stringify(x)),h&&sessionStorage.setItem(l1e,h);const g=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.access_token}`},body:JSON.stringify({targetUserId:d})}),v=await g.json();if(!g.ok)throw new Error(v.error||"Failed to impersonate user");const j={id:v.targetUser.id,name:v.targetUser.name,email:v.targetUser.email};if(sessionStorage.setItem(Mw,JSON.stringify(j)),v.method==="session"){const{error:b}=await H.auth.setSession({access_token:v.access_token,refresh_token:v.refresh_token});if(b)throw console.error("Set session error:",b),sessionStorage.removeItem(ik),sessionStorage.removeItem(Mw),new Error("Failed to establish impersonation session")}else{const b=v.type||"recovery",{error:N}=await H.auth.verifyOtp({token_hash:v.token_hash,type:b});if(N)throw console.error("Verify OTP error:",N),sessionStorage.removeItem(ik),sessionStorage.removeItem(Mw),new Error("Failed to establish impersonation session")}return r(!0),a(j),ue.success(`Now viewing as ${j.name}`),window.location.href="/dashboard",!0}catch(m){return console.error("Impersonation error:",m),ue.error(m.message||"Failed to impersonate user"),sessionStorage.removeItem(ik),sessionStorage.removeItem(Mw),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(ik);if(!d){await H.auth.signOut(),window.location.href="/auth";return}const h=JSON.parse(d);await H.auth.signOut();const{error:m}=await H.auth.setSession({access_token:h.access_token,refresh_token:h.refresh_token});if(sessionStorage.removeItem(ik),sessionStorage.removeItem(Mw),m){console.error("Failed to restore admin session:",m),ue.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),a(null),ue.success("Returned to your account");const x=sessionStorage.getItem(l1e)||"/admin/members";sessionStorage.removeItem(l1e),window.location.href=x}catch(d){console.error("Stop impersonation error:",d),ue.error("Failed to restore admin session"),sessionStorage.removeItem(ik),sessionStorage.removeItem(Mw),window.location.href="/auth"}finally{l(!1)}};return e.jsx(iQe.Provider,{value:{isImpersonating:t,impersonatedUser:n,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},ipe=()=>{const s=k.useContext(iQe);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},uI=V5("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),G=k.forwardRef(({className:s,variant:t,size:r,asChild:n=!1,...a},i)=>{const l=n?c4e:"button";return e.jsx(l,{className:Bt(uI({variant:t,size:r,className:s})),ref:i,...a})});G.displayName="Button";const K5t=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:r,isLoading:n}=ipe();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(od,{className:"h-5 w-5 flex-shrink-0"}),e.jsxs("span",{className:"font-medium text-sm md:text-base",children:[e.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),e.jsx("strong",{children:t.name}),e.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",t.email,")"]})]})]}),e.jsx(G,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?e.jsx(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"})]})})]})})},oQe=k.createContext(void 0),IE="levelup_acting_as",W$="levelup_acting_as_self",Y5t=({children:s})=>{const{user:t}=As(),[r,n]=k.useState(!1),[a,i]=k.useState([]),[l,o]=k.useState(null),[c,d]=k.useState({}),[h,m]=k.useState(!0),[x,g]=k.useState(()=>sessionStorage.getItem(W$)==="true");k.useEffect(()=>{if(!(t!=null&&t.id)){n(!1),i([]),o(null),d({}),m(!1);return}(async()=>{m(!0);try{const{data:T}=await H.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!T){n(!1),i([]),o(null),d({}),m(!1);return}n(!0);const{data:A,error:P}=await H.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(P||!A||A.length===0){i([]),m(!1);return}const D=A.map(F=>F.agent_id),{data:B}=await H.from("profiles").select("id, name, email, avatar_url").in("id",D),z=(B||[]).map(F=>({id:F.id,name:F.name||F.email||"Unknown",email:F.email||"",avatar_url:F.avatar_url}));if(i(z),sessionStorage.getItem(W$)==="true")g(!0),o(null),d({});else{const F=sessionStorage.getItem(IE);if(F){const $=z.find(X=>X.id===F);if($){o($);const X=A.find(K=>K.agent_id===F);d((X==null?void 0:X.permissions)||{})}else if(z.length>0){o(z[0]);const X=A.find(K=>K.agent_id===z[0].id);d((X==null?void 0:X.permissions)||{}),sessionStorage.setItem(IE,z[0].id)}}else if(z.length>0){o(z[0]);const $=A.find(X=>X.agent_id===z[0].id);d(($==null?void 0:$.permissions)||{}),sessionStorage.setItem(IE,z[0].id)}}}catch(T){console.error("Error loading assistant data:",T)}finally{m(!1)}})()},[t==null?void 0:t.id]);const v=S=>{o(S),g(!1),sessionStorage.removeItem(W$),S?(sessionStorage.setItem(IE,S.id),H.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",S.id).single().then(({data:T})=>{d((T==null?void 0:T.permissions)||{})})):(sessionStorage.removeItem(IE),d({}))},j=()=>{g(!0),o(null),d({}),sessionStorage.setItem(W$,"true"),sessionStorage.removeItem(IE)},b=S=>!r||x?!0:c[S]===!0,N=r&&l&&!x?l.id:(t==null?void 0:t.id)||null;return e.jsx(oQe.Provider,{value:{isAssistant:r,assignedAgents:a,actingAsAgent:l,setActingAsAgent:v,effectiveUserId:N,permissions:c,hasPermission:b,isLoading:h,isActingAsSelf:x,setActingAsSelf:j},children:s})},$4e=()=>{const s=k.useContext(oQe);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},na=()=>{const{effectiveUserId:s}=$4e();return s};var c1e=!1;function Z5t(){const[s,t]=k.useState(c1e);return k.useEffect(()=>{c1e||(c1e=!0,t(!0))},[]),s}var lQe=jB[" useSyncExternalStore ".trim().toString()];function X5t(){return()=>{}}function Q5t(){return lQe(X5t,()=>!0,()=>!1)}var J5t=typeof lQe=="function"?Q5t:Z5t,U4e="Avatar",[eTt]=yd(U4e),[tTt,cQe]=eTt(U4e),dQe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,...n}=s,[a,i]=k.useState("idle");return e.jsx(tTt,{scope:r,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(pn.span,{...n,ref:t})})});dQe.displayName=U4e;var uQe="AvatarImage",hQe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:a=()=>{},...i}=s,l=cQe(uQe,r),o=sTt(n,i),c=Ld(d=>{a(d),l.onImageLoadingStatusChange(d)});return fd(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(pn.img,{...i,ref:t,src:n}):null});hQe.displayName=uQe;var mQe="AvatarFallback",fQe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,delayMs:n,...a}=s,i=cQe(mQe,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(pn.span,{...a,ref:t}):null});fQe.displayName=mQe;function tOe(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function sTt(s,{referrerPolicy:t,crossOrigin:r}){const n=J5t(),a=k.useRef(null),i=n?(a.current||(a.current=new window.Image),a.current):null,[l,o]=k.useState(()=>tOe(i,s));return fd(()=>{o(tOe(i,s))},[i,s]),fd(()=>{const c=m=>()=>{o(m)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof r=="string"&&(i.crossOrigin=r),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,r,t]),l}var pQe=dQe,xQe=hQe,gQe=fQe;const vn=k.forwardRef(({className:s,...t},r)=>e.jsx(pQe,{ref:r,className:Bt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));vn.displayName=pQe.displayName;const ga=k.forwardRef(({className:s,...t},r)=>e.jsx(xQe,{ref:r,className:Bt("aspect-square h-full w-full",s),...t}));ga.displayName=xQe.displayName;const bn=k.forwardRef(({className:s,...t},r)=>e.jsx(gQe,{ref:r,className:Bt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));bn.displayName=gQe.displayName;const rTt=V5("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Ge({className:s,variant:t,...r}){return e.jsx("div",{className:Bt(rTt({variant:t}),s),...r})}var nTt=k.createContext(void 0);function $2(s){const t=k.useContext(nTt);return s||t||"ltr"}var K$=0,ev=null;function ope(){k.useEffect(()=>{ev||(ev={start:sOe(),end:sOe()});const{start:s,end:t}=ev;return document.body.firstElementChild!==s&&document.body.insertAdjacentElement("afterbegin",s),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),K$++,()=>{K$===1&&(ev==null||ev.start.remove(),ev==null||ev.end.remove(),ev=null),K$=Math.max(0,K$-1)}},[])}function sOe(){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 d1e="focusScope.autoFocusOnMount",u1e="focusScope.autoFocusOnUnmount",rOe={bubbles:!1,cancelable:!0},aTt="FocusScope",OB=k.forwardRef((s,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=k.useState(null),d=Ld(a),h=Ld(i),m=k.useRef(null),x=Qa(t,j=>c(j)),g=k.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;k.useEffect(()=>{if(n){let j=function(T){if(g.paused||!o)return;const A=T.target;o.contains(A)?m.current=A:Vw(m.current,{select:!0})},b=function(T){if(g.paused||!o)return;const A=T.relatedTarget;A!==null&&(o.contains(A)||Vw(m.current,{select:!0}))},N=function(T){if(document.activeElement===document.body)for(const P of T)P.removedNodes.length>0&&Vw(o)};document.addEventListener("focusin",j),document.addEventListener("focusout",b);const S=new MutationObserver(N);return o&&S.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",j),document.removeEventListener("focusout",b),S.disconnect()}}},[n,o,g.paused]),k.useEffect(()=>{if(o){aOe.add(g);const j=document.activeElement;if(!o.contains(j)){const N=new CustomEvent(d1e,rOe);o.addEventListener(d1e,d),o.dispatchEvent(N),N.defaultPrevented||(iTt(uTt(yQe(o)),{select:!0}),document.activeElement===j&&Vw(o))}return()=>{o.removeEventListener(d1e,d),setTimeout(()=>{const N=new CustomEvent(u1e,rOe);o.addEventListener(u1e,h),o.dispatchEvent(N),N.defaultPrevented||Vw(j??document.body,{select:!0}),o.removeEventListener(u1e,h),aOe.remove(g)},0)}}},[o,d,h,g]);const v=k.useCallback(j=>{if(!r&&!n||g.paused)return;const b=j.key==="Tab"&&!j.altKey&&!j.ctrlKey&&!j.metaKey,N=document.activeElement;if(b&&N){const S=j.currentTarget,[T,A]=oTt(S);T&&A?!j.shiftKey&&N===A?(j.preventDefault(),r&&Vw(T,{select:!0})):j.shiftKey&&N===T&&(j.preventDefault(),r&&Vw(A,{select:!0})):N===S&&j.preventDefault()}},[r,n,g.paused]);return e.jsx(pn.div,{tabIndex:-1,...l,ref:x,onKeyDown:v})});OB.displayName=aTt;function iTt(s,{select:t=!1}={}){const r=document.activeElement;for(const n of s)if(Vw(n,{select:t}),document.activeElement!==r)return}function oTt(s){const t=yQe(s),r=nOe(t,s),n=nOe(t.reverse(),s);return[r,n]}function yQe(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 nOe(s,t){for(const r of s)if(!lTt(r,{upTo:t}))return r}function lTt(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 cTt(s){return s instanceof HTMLInputElement&&"select"in s}function Vw(s,{select:t=!1}={}){if(s&&s.focus){const r=document.activeElement;s.focus({preventScroll:!0}),s!==r&&cTt(s)&&t&&s.select()}}var aOe=dTt();function dTt(){let s=[];return{add(t){const r=s[0];t!==r&&(r==null||r.pause()),s=iOe(s,t),s.unshift(t)},remove(t){var r;s=iOe(s,t),(r=s[0])==null||r.resume()}}}function iOe(s,t){const r=[...s],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function uTt(s){return s.filter(t=>t.tagName!=="A")}var h1e="rovingFocusGroup.onEntryFocus",hTt={bubbles:!1,cancelable:!0},FB="RovingFocusGroup",[Zje,vQe,mTt]=TB(FB),[fTt,U2]=yd(FB,[mTt]),[pTt,xTt]=fTt(FB),bQe=k.forwardRef((s,t)=>e.jsx(Zje.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Zje.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(gTt,{...s,ref:t})})}));bQe.displayName=FB;var gTt=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...m}=s,x=k.useRef(null),g=Qa(t,x),v=$2(i),[j,b]=Lh({prop:l,defaultProp:o??null,onChange:c,caller:FB}),[N,S]=k.useState(!1),T=Ld(d),A=vQe(r),P=k.useRef(!1),[D,B]=k.useState(0);return k.useEffect(()=>{const z=x.current;if(z)return z.addEventListener(h1e,T),()=>z.removeEventListener(h1e,T)},[T]),e.jsx(pTt,{scope:r,orientation:n,dir:v,loop:a,currentTabStopId:j,onItemFocus:k.useCallback(z=>b(z),[b]),onItemShiftTab:k.useCallback(()=>S(!0),[]),onFocusableItemAdd:k.useCallback(()=>B(z=>z+1),[]),onFocusableItemRemove:k.useCallback(()=>B(z=>z-1),[]),children:e.jsx(pn.div,{tabIndex:N||D===0?-1:0,"data-orientation":n,...m,ref:g,style:{outline:"none",...s.style},onMouseDown:Or(s.onMouseDown,()=>{P.current=!0}),onFocus:Or(s.onFocus,z=>{const F=!P.current;if(z.target===z.currentTarget&&F&&!N){const $=new CustomEvent(h1e,hTt);if(z.currentTarget.dispatchEvent($),!$.defaultPrevented){const X=A().filter(de=>de.focusable),K=X.find(de=>de.active),Q=X.find(de=>de.id===j),ne=[K,Q,...X].filter(Boolean).map(de=>de.ref.current);jQe(ne,h)}}P.current=!1}),onBlur:Or(s.onBlur,()=>S(!1))})})}),_Qe="RovingFocusGroupItem",wQe=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=Qu(),d=i||c,h=xTt(_Qe,r),m=h.currentTabStopId===d,x=vQe(r),{onFocusableItemAdd:g,onFocusableItemRemove:v,currentTabStopId:j}=h;return k.useEffect(()=>{if(n)return g(),()=>v()},[n,g,v]),e.jsx(Zje.ItemSlot,{scope:r,id:d,focusable:n,active:a,children:e.jsx(pn.span,{tabIndex:m?0:-1,"data-orientation":h.orientation,...o,ref:t,onMouseDown:Or(s.onMouseDown,b=>{n?h.onItemFocus(d):b.preventDefault()}),onFocus:Or(s.onFocus,()=>h.onItemFocus(d)),onKeyDown:Or(s.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const N=bTt(b,h.orientation,h.dir);if(N!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let T=x().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(b.currentTarget);T=h.loop?_Tt(T,A+1):T.slice(A+1)}setTimeout(()=>jQe(T))}}),children:typeof l=="function"?l({isCurrentTabStop:m,hasTabStop:j!=null}):l})})});wQe.displayName=_Qe;var yTt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function vTt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function bTt(s,t,r){const n=vTt(s.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return yTt[n]}function jQe(s,t=!1){const r=document.activeElement;for(const n of s)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function _Tt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var lpe=bQe,cpe=wQe,wTt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},PE=new WeakMap,Y$=new WeakMap,Z$={},m1e=0,NQe=function(s){return s&&(s.host||NQe(s.parentNode))},jTt=function(s,t){return t.map(function(r){if(s.contains(r))return r;var n=NQe(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})},NTt=function(s,t,r,n){var a=jTt(t,Array.isArray(s)?s:[s]);Z$[r]||(Z$[r]=new WeakMap);var i=Z$[r],l=[],o=new Set,c=new Set(a),d=function(m){!m||o.has(m)||(o.add(m),d(m.parentNode))};a.forEach(d);var h=function(m){!m||c.has(m)||Array.prototype.forEach.call(m.children,function(x){if(o.has(x))h(x);else try{var g=x.getAttribute(n),v=g!==null&&g!=="false",j=(PE.get(x)||0)+1,b=(i.get(x)||0)+1;PE.set(x,j),i.set(x,b),l.push(x),j===1&&v&&Y$.set(x,!0),b===1&&x.setAttribute(r,"true"),v||x.setAttribute(n,"true")}catch(N){console.error("aria-hidden: cannot operate on ",x,N)}})};return h(t),o.clear(),m1e++,function(){l.forEach(function(m){var x=PE.get(m)-1,g=i.get(m)-1;PE.set(m,x),i.set(m,g),x||(Y$.has(m)||m.removeAttribute(n),Y$.delete(m)),g||m.removeAttribute(r)}),m1e--,m1e||(PE=new WeakMap,PE=new WeakMap,Y$=new WeakMap,Z$={})}},dpe=function(s,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(s)?s:[s]),a=wTt(s);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),NTt(n,a,r,"aria-hidden")):function(){return null}},Nv=function(){return Nv=Object.assign||function(t){for(var r,n=1,a=arguments.length;n"u")return $Tt;var t=UTt(s),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},VTt=TQe(),NM="data-scroll-locked",HTt=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(STt,` { overflow: hidden `).concat(n,`; padding-right: `).concat(o,"px ").concat(n,`; } body[`).concat(NM,`] { 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(ude,` { right: `).concat(o,"px ").concat(n,`; } .`).concat(hde,` { margin-right: `).concat(o,"px ").concat(n,`; } .`).concat(ude," .").concat(ude,` { right: 0 `).concat(n,`; } .`).concat(hde," .").concat(hde,` { margin-right: 0 `).concat(n,`; } body[`).concat(NM,`] { `).concat(CTt,": ").concat(o,`px; } `)},lOe=function(){var s=parseInt(document.body.getAttribute(NM)||"0",10);return isFinite(s)?s:0},GTt=function(){k.useEffect(function(){return document.body.setAttribute(NM,(lOe()+1).toString()),function(){var s=lOe()-1;s<=0?document.body.removeAttribute(NM):document.body.setAttribute(NM,s.toString())}},[])},WTt=function(s){var t=s.noRelative,r=s.noImportant,n=s.gapMode,a=n===void 0?"margin":n;GTt();var i=k.useMemo(function(){return qTt(a)},[a]);return k.createElement(VTt,{styles:HTt(i,!t,a,r?"":"!important")})},Xje=!1;if(typeof window<"u")try{var X$=Object.defineProperty({},"passive",{get:function(){return Xje=!0,!0}});window.addEventListener("test",X$,X$),window.removeEventListener("test",X$,X$)}catch{Xje=!1}var LE=Xje?{passive:!1}:!1,KTt=function(s){return s.tagName==="TEXTAREA"},EQe=function(s,t){if(!(s instanceof Element))return!1;var r=window.getComputedStyle(s);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!KTt(s)&&r[t]==="visible")},YTt=function(s){return EQe(s,"overflowY")},ZTt=function(s){return EQe(s,"overflowX")},cOe=function(s,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=AQe(s,n);if(a){var i=MQe(s,n),l=i[1],o=i[2];if(l>o)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},XTt=function(s){var t=s.scrollTop,r=s.scrollHeight,n=s.clientHeight;return[t,r,n]},QTt=function(s){var t=s.scrollLeft,r=s.scrollWidth,n=s.clientWidth;return[t,r,n]},AQe=function(s,t){return s==="v"?YTt(t):ZTt(t)},MQe=function(s,t){return s==="v"?XTt(t):QTt(t)},JTt=function(s,t){return s==="h"&&t==="rtl"?-1:1},eEt=function(s,t,r,n,a){var i=JTt(s,window.getComputedStyle(t).direction),l=i*n,o=r.target,c=t.contains(o),d=!1,h=l>0,m=0,x=0;do{if(!o)break;var g=MQe(s,o),v=g[0],j=g[1],b=g[2],N=j-b-i*v;(v||N)&&AQe(s,o)&&(m+=N,x+=v);var S=o.parentNode;o=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(h&&Math.abs(m)<1||!h&&Math.abs(x)<1)&&(d=!0),d},Q$=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},dOe=function(s){return[s.deltaX,s.deltaY]},uOe=function(s){return s&&"current"in s?s.current:s},tEt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},sEt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},rEt=0,DE=[];function nEt(s){var t=k.useRef([]),r=k.useRef([0,0]),n=k.useRef(),a=k.useState(rEt++)[0],i=k.useState(TQe)[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 j=kTt([s.lockRef.current],(s.shards||[]).map(uOe),!0).filter(Boolean);return j.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),j.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=k.useCallback(function(j,b){if("touches"in j&&j.touches.length===2||j.type==="wheel"&&j.ctrlKey)return!l.current.allowPinchZoom;var N=Q$(j),S=r.current,T="deltaX"in j?j.deltaX:S[0]-N[0],A="deltaY"in j?j.deltaY:S[1]-N[1],P,D=j.target,B=Math.abs(T)>Math.abs(A)?"h":"v";if("touches"in j&&B==="h"&&D.type==="range")return!1;var z=window.getSelection(),F=z&&z.anchorNode,$=F?F===D||F.contains(D):!1;if($)return!1;var X=cOe(B,D);if(!X)return!0;if(X?P=B:(P=B==="v"?"h":"v",X=cOe(B,D)),!X)return!1;if(!n.current&&"changedTouches"in j&&(T||A)&&(n.current=P),!P)return!0;var K=n.current||P;return eEt(K,b,j,K==="h"?T:A)},[]),c=k.useCallback(function(j){var b=j;if(!(!DE.length||DE[DE.length-1]!==i)){var N="deltaY"in b?dOe(b):Q$(b),S=t.current.filter(function(P){return P.name===b.type&&(P.target===b.target||b.target===P.shadowParent)&&tEt(P.delta,N)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var T=(l.current.shards||[]).map(uOe).filter(Boolean).filter(function(P){return P.contains(b.target)}),A=T.length>0?o(b,T[0]):!l.current.noIsolation;A&&b.cancelable&&b.preventDefault()}}},[]),d=k.useCallback(function(j,b,N,S){var T={name:j,delta:b,target:N,should:S,shadowParent:aEt(N)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(A){return A!==T})},1)},[]),h=k.useCallback(function(j){r.current=Q$(j),n.current=void 0},[]),m=k.useCallback(function(j){d(j.type,dOe(j),j.target,o(j,s.lockRef.current))},[]),x=k.useCallback(function(j){d(j.type,Q$(j),j.target,o(j,s.lockRef.current))},[]);k.useEffect(function(){return DE.push(i),s.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:x}),document.addEventListener("wheel",c,LE),document.addEventListener("touchmove",c,LE),document.addEventListener("touchstart",h,LE),function(){DE=DE.filter(function(j){return j!==i}),document.removeEventListener("wheel",c,LE),document.removeEventListener("touchmove",c,LE),document.removeEventListener("touchstart",h,LE)}},[]);var g=s.removeScrollBar,v=s.inert;return k.createElement(k.Fragment,null,v?k.createElement(i,{styles:sEt(a)}):null,g?k.createElement(WTt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function aEt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const iEt=LTt(CQe,nEt);var BB=k.forwardRef(function(s,t){return k.createElement(upe,Nv({},s,{ref:t,sideCar:iEt}))});BB.classNames=upe.classNames;var Qje=["Enter"," "],oEt=["ArrowDown","PageUp","Home"],IQe=["ArrowUp","PageDown","End"],lEt=[...oEt,...IQe],cEt={ltr:[...Qje,"ArrowRight"],rtl:[...Qje,"ArrowLeft"]},dEt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},zB="Menu",[J8,uEt,hEt]=TB(zB),[G5,PQe]=yd(zB,[hEt,x1,U2]),hpe=x1(),LQe=U2(),[mEt,W5]=G5(zB),[fEt,$B]=G5(zB),DQe=s=>{const{__scopeMenu:t,open:r=!1,children:n,dir:a,onOpenChange:i,modal:l=!0}=s,o=hpe(t),[c,d]=k.useState(null),h=k.useRef(!1),m=Ld(i),x=$2(a);return k.useEffect(()=>{const g=()=>{h.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},v=()=>h.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),e.jsx(IB,{...o,children:e.jsx(mEt,{scope:t,open:r,onOpenChange:m,content:c,onContentChange:d,children:e.jsx(fEt,{scope:t,onClose:k.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:x,modal:l,children:n})})})};DQe.displayName=zB;var pEt="MenuAnchor",q4e=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=hpe(r);return e.jsx(bP,{...a,...n,ref:t})});q4e.displayName=pEt;var V4e="MenuPortal",[xEt,RQe]=G5(V4e,{forceMount:void 0}),OQe=s=>{const{__scopeMenu:t,forceMount:r,children:n,container:a}=s,i=W5(V4e,t);return e.jsx(xEt,{scope:t,forceMount:r,children:e.jsx(qd,{present:r||i.open,children:e.jsx(xP,{asChild:!0,container:a,children:n})})})};OQe.displayName=V4e;var Ug="MenuContent",[gEt,H4e]=G5(Ug),FQe=k.forwardRef((s,t)=>{const r=RQe(Ug,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=W5(Ug,s.__scopeMenu),l=$B(Ug,s.__scopeMenu);return e.jsx(J8.Provider,{scope:s.__scopeMenu,children:e.jsx(qd,{present:n||i.open,children:e.jsx(J8.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(yEt,{...a,ref:t}):e.jsx(vEt,{...a,ref:t})})})})}),yEt=k.forwardRef((s,t)=>{const r=W5(Ug,s.__scopeMenu),n=k.useRef(null),a=Qa(t,n);return k.useEffect(()=>{const i=n.current;if(i)return dpe(i)},[]),e.jsx(G4e,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Or(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),vEt=k.forwardRef((s,t)=>{const r=W5(Ug,s.__scopeMenu);return e.jsx(G4e,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),bEt=v2("MenuContent.ScrollLock"),G4e=k.forwardRef((s,t)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:x,onDismiss:g,disableOutsideScroll:v,...j}=s,b=W5(Ug,r),N=$B(Ug,r),S=hpe(r),T=LQe(r),A=uEt(r),[P,D]=k.useState(null),B=k.useRef(null),z=Qa(t,B,b.onContentChange),F=k.useRef(0),$=k.useRef(""),X=k.useRef(0),K=k.useRef(null),Q=k.useRef("right"),Y=k.useRef(0),ne=v?BB:k.Fragment,de=v?{as:bEt,allowPinchZoom:!0}:void 0,ce=ie=>{var Ee,$e;const me=$.current+ie,oe=A().filter(Se=>!Se.disabled),ge=document.activeElement,be=(Ee=oe.find(Se=>Se.ref.current===ge))==null?void 0:Ee.textValue,Oe=oe.map(Se=>Se.textValue),Me=IEt(Oe,me,be),Pe=($e=oe.find(Se=>Se.textValue===Me))==null?void 0:$e.ref.current;(function Se(ze){$.current=ze,window.clearTimeout(F.current),ze!==""&&(F.current=window.setTimeout(()=>Se(""),1e3))})(me),Pe&&setTimeout(()=>Pe.focus())};k.useEffect(()=>()=>window.clearTimeout(F.current),[]),ope();const ae=k.useCallback(ie=>{var oe,ge;return Q.current===((oe=K.current)==null?void 0:oe.side)&&LEt(ie,(ge=K.current)==null?void 0:ge.area)},[]);return e.jsx(gEt,{scope:r,searchRef:$,onItemEnter:k.useCallback(ie=>{ae(ie)&&ie.preventDefault()},[ae]),onItemLeave:k.useCallback(ie=>{var me;ae(ie)||((me=B.current)==null||me.focus(),D(null))},[ae]),onTriggerLeave:k.useCallback(ie=>{ae(ie)&&ie.preventDefault()},[ae]),pointerGraceTimerRef:X,onPointerGraceIntentChange:k.useCallback(ie=>{K.current=ie},[]),children:e.jsx(ne,{...de,children:e.jsx(OB,{asChild:!0,trapped:a,onMountAutoFocus:Or(i,ie=>{var me;ie.preventDefault(),(me=B.current)==null||me.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(F2,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:x,onDismiss:g,children:e.jsx(lpe,{asChild:!0,...T,dir:N.dir,orientation:"vertical",loop:n,currentTabStopId:P,onCurrentTabStopIdChange:D,onEntryFocus:Or(c,ie=>{N.isUsingKeyboardRef.current||ie.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(PB,{role:"menu","aria-orientation":"vertical","data-state":eJe(b.open),"data-radix-menu-content":"",dir:N.dir,...S,...j,ref:z,style:{outline:"none",...j.style},onKeyDown:Or(j.onKeyDown,ie=>{const oe=ie.target.closest("[data-radix-menu-content]")===ie.currentTarget,ge=ie.ctrlKey||ie.altKey||ie.metaKey,be=ie.key.length===1;oe&&(ie.key==="Tab"&&ie.preventDefault(),!ge&&be&&ce(ie.key));const Oe=B.current;if(ie.target!==Oe||!lEt.includes(ie.key))return;ie.preventDefault();const Pe=A().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);IQe.includes(ie.key)&&Pe.reverse(),AEt(Pe)}),onBlur:Or(s.onBlur,ie=>{ie.currentTarget.contains(ie.target)||(window.clearTimeout(F.current),$.current="")}),onPointerMove:Or(s.onPointerMove,eF(ie=>{const me=ie.target,oe=Y.current!==ie.clientX;if(ie.currentTarget.contains(me)&&oe){const ge=ie.clientX>Y.current?"right":"left";Q.current=ge,Y.current=ie.clientX}}))})})})})})})});FQe.displayName=Ug;var _Et="MenuGroup",W4e=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(pn.div,{role:"group",...n,ref:t})});W4e.displayName=_Et;var wEt="MenuLabel",BQe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(pn.div,{...n,ref:t})});BQe.displayName=wEt;var Sue="MenuItem",hOe="menu.itemSelect",mpe=k.forwardRef((s,t)=>{const{disabled:r=!1,onSelect:n,...a}=s,i=k.useRef(null),l=$B(Sue,s.__scopeMenu),o=H4e(Sue,s.__scopeMenu),c=Qa(t,i),d=k.useRef(!1),h=()=>{const m=i.current;if(!r&&m){const x=new CustomEvent(hOe,{bubbles:!0,cancelable:!0});m.addEventListener(hOe,g=>n==null?void 0:n(g),{once:!0}),d4e(m,x),x.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(zQe,{...a,ref:c,disabled:r,onClick:Or(s.onClick,h),onPointerDown:m=>{var x;(x=s.onPointerDown)==null||x.call(s,m),d.current=!0},onPointerUp:Or(s.onPointerUp,m=>{var x;d.current||(x=m.currentTarget)==null||x.click()}),onKeyDown:Or(s.onKeyDown,m=>{const x=o.searchRef.current!=="";r||x&&m.key===" "||Qje.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});mpe.displayName=Sue;var zQe=k.forwardRef((s,t)=>{const{__scopeMenu:r,disabled:n=!1,textValue:a,...i}=s,l=H4e(Sue,r),o=LQe(r),c=k.useRef(null),d=Qa(t,c),[h,m]=k.useState(!1),[x,g]=k.useState("");return k.useEffect(()=>{const v=c.current;v&&g((v.textContent??"").trim())},[i.children]),e.jsx(J8.ItemSlot,{scope:r,disabled:n,textValue:a??x,children:e.jsx(cpe,{asChild:!0,...o,focusable:!n,children:e.jsx(pn.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...i,ref:d,onPointerMove:Or(s.onPointerMove,eF(v=>{n?l.onItemLeave(v):(l.onItemEnter(v),v.defaultPrevented||v.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Or(s.onPointerLeave,eF(v=>l.onItemLeave(v))),onFocus:Or(s.onFocus,()=>m(!0)),onBlur:Or(s.onBlur,()=>m(!1))})})})}),jEt="MenuCheckboxItem",$Qe=k.forwardRef((s,t)=>{const{checked:r=!1,onCheckedChange:n,...a}=s;return e.jsx(GQe,{scope:s.__scopeMenu,checked:r,children:e.jsx(mpe,{role:"menuitemcheckbox","aria-checked":Cue(r)?"mixed":r,...a,ref:t,"data-state":Y4e(r),onSelect:Or(a.onSelect,()=>n==null?void 0:n(Cue(r)?!0:!r),{checkForDefaultPrevented:!1})})})});$Qe.displayName=jEt;var UQe="MenuRadioGroup",[NEt,kEt]=G5(UQe,{value:void 0,onValueChange:()=>{}}),qQe=k.forwardRef((s,t)=>{const{value:r,onValueChange:n,...a}=s,i=Ld(n);return e.jsx(NEt,{scope:s.__scopeMenu,value:r,onValueChange:i,children:e.jsx(W4e,{...a,ref:t})})});qQe.displayName=UQe;var VQe="MenuRadioItem",HQe=k.forwardRef((s,t)=>{const{value:r,...n}=s,a=kEt(VQe,s.__scopeMenu),i=r===a.value;return e.jsx(GQe,{scope:s.__scopeMenu,checked:i,children:e.jsx(mpe,{role:"menuitemradio","aria-checked":i,...n,ref:t,"data-state":Y4e(i),onSelect:Or(n.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,r)},{checkForDefaultPrevented:!1})})})});HQe.displayName=VQe;var K4e="MenuItemIndicator",[GQe,SEt]=G5(K4e,{checked:!1}),WQe=k.forwardRef((s,t)=>{const{__scopeMenu:r,forceMount:n,...a}=s,i=SEt(K4e,r);return e.jsx(qd,{present:n||Cue(i.checked)||i.checked===!0,children:e.jsx(pn.span,{...a,ref:t,"data-state":Y4e(i.checked)})})});WQe.displayName=K4e;var CEt="MenuSeparator",KQe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(pn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:t})});KQe.displayName=CEt;var TEt="MenuArrow",YQe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=hpe(r);return e.jsx(LB,{...a,...n,ref:t})});YQe.displayName=TEt;var EEt="MenuSub",[VUs,ZQe]=G5(EEt),vR="MenuSubTrigger",XQe=k.forwardRef((s,t)=>{const r=W5(vR,s.__scopeMenu),n=$B(vR,s.__scopeMenu),a=ZQe(vR,s.__scopeMenu),i=H4e(vR,s.__scopeMenu),l=k.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},h=k.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return k.useEffect(()=>h,[h]),k.useEffect(()=>{const m=o.current;return()=>{window.clearTimeout(m),c(null)}},[o,c]),e.jsx(q4e,{asChild:!0,...d,children:e.jsx(zQe,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":r.open?a.contentId:void 0,"data-state":eJe(r.open),...s,ref:y2(t,a.onTriggerChange),onClick:m=>{var x;(x=s.onClick)==null||x.call(s,m),!(s.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Or(s.onPointerMove,eF(m=>{i.onItemEnter(m),!m.defaultPrevented&&!s.disabled&&!r.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{r.onOpenChange(!0),h()},100))})),onPointerLeave:Or(s.onPointerLeave,eF(m=>{var g,v;h();const x=(g=r.content)==null?void 0:g.getBoundingClientRect();if(x){const j=(v=r.content)==null?void 0:v.dataset.side,b=j==="right",N=b?-5:5,S=x[b?"left":"right"],T=x[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+N,y:m.clientY},{x:S,y:x.top},{x:T,y:x.top},{x:T,y:x.bottom},{x:S,y:x.bottom}],side:j}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Or(s.onKeyDown,m=>{var g;const x=i.searchRef.current!=="";s.disabled||x&&m.key===" "||cEt[n.dir].includes(m.key)&&(r.onOpenChange(!0),(g=r.content)==null||g.focus(),m.preventDefault())})})})});XQe.displayName=vR;var QQe="MenuSubContent",JQe=k.forwardRef((s,t)=>{const r=RQe(Ug,s.__scopeMenu),{forceMount:n=r.forceMount,align:a="start",...i}=s,l=W5(Ug,s.__scopeMenu),o=$B(Ug,s.__scopeMenu),c=ZQe(QQe,s.__scopeMenu),d=k.useRef(null),h=Qa(t,d);return e.jsx(J8.Provider,{scope:s.__scopeMenu,children:e.jsx(qd,{present:n||l.open,children:e.jsx(J8.Slot,{scope:s.__scopeMenu,children:e.jsx(G4e,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:h,align:a,side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var x;o.isUsingKeyboardRef.current&&((x=d.current)==null||x.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Or(s.onFocusOutside,m=>{m.target!==c.trigger&&l.onOpenChange(!1)}),onEscapeKeyDown:Or(s.onEscapeKeyDown,m=>{o.onClose(),m.preventDefault()}),onKeyDown:Or(s.onKeyDown,m=>{var v;const x=m.currentTarget.contains(m.target),g=dEt[o.dir].includes(m.key);x&&g&&(l.onOpenChange(!1),(v=c.trigger)==null||v.focus(),m.preventDefault())})})})})})});JQe.displayName=QQe;function eJe(s){return s?"open":"closed"}function Cue(s){return s==="indeterminate"}function Y4e(s){return Cue(s)?"indeterminate":s?"checked":"unchecked"}function AEt(s){const t=document.activeElement;for(const r of s)if(r===t||(r.focus(),document.activeElement!==t))return}function MEt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}function IEt(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=MEt(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 PEt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=x>n&&r<(m-d)*(n-h)/(x-h)+d&&(a=!a)}return a}function LEt(s,t){if(!t)return!1;const r={x:s.clientX,y:s.clientY};return PEt(r,t)}function eF(s){return t=>t.pointerType==="mouse"?s(t):void 0}var DEt=DQe,REt=q4e,OEt=OQe,FEt=FQe,BEt=W4e,zEt=BQe,$Et=mpe,UEt=$Qe,qEt=qQe,VEt=HQe,HEt=WQe,GEt=KQe,WEt=YQe,KEt=XQe,YEt=JQe,fpe="DropdownMenu",[ZEt]=yd(fpe,[PQe]),Pf=PQe(),[XEt,tJe]=ZEt(fpe),sJe=s=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Pf(t),d=k.useRef(null),[h,m]=Lh({prop:a,defaultProp:i??!1,onChange:l,caller:fpe});return e.jsx(XEt,{scope:t,triggerId:Qu(),triggerRef:d,contentId:Qu(),open:h,onOpenChange:m,onOpenToggle:k.useCallback(()=>m(x=>!x),[m]),modal:o,children:e.jsx(DEt,{...c,open:h,onOpenChange:m,dir:n,modal:o,children:r})})};sJe.displayName=fpe;var rJe="DropdownMenuTrigger",nJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...a}=s,i=tJe(rJe,r),l=Pf(r);return e.jsx(REt,{asChild:!0,...l,children:e.jsx(pn.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:y2(t,i.triggerRef),onPointerDown:Or(s.onPointerDown,o=>{!n&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:Or(s.onKeyDown,o=>{n||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});nJe.displayName=rJe;var QEt="DropdownMenuPortal",aJe=s=>{const{__scopeDropdownMenu:t,...r}=s,n=Pf(t);return e.jsx(OEt,{...n,...r})};aJe.displayName=QEt;var iJe="DropdownMenuContent",oJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=tJe(iJe,r),i=Pf(r),l=k.useRef(!1);return e.jsx(FEt,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...n,ref:t,onCloseAutoFocus:Or(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:Or(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,h=c.button===2||d;(!a.modal||h)&&(l.current=!0)}),style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});oJe.displayName=iJe;var JEt="DropdownMenuGroup",eAt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(BEt,{...a,...n,ref:t})});eAt.displayName=JEt;var tAt="DropdownMenuLabel",lJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(zEt,{...a,...n,ref:t})});lJe.displayName=tAt;var sAt="DropdownMenuItem",cJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx($Et,{...a,...n,ref:t})});cJe.displayName=sAt;var rAt="DropdownMenuCheckboxItem",dJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(UEt,{...a,...n,ref:t})});dJe.displayName=rAt;var nAt="DropdownMenuRadioGroup",aAt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(qEt,{...a,...n,ref:t})});aAt.displayName=nAt;var iAt="DropdownMenuRadioItem",uJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(VEt,{...a,...n,ref:t})});uJe.displayName=iAt;var oAt="DropdownMenuItemIndicator",hJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(HEt,{...a,...n,ref:t})});hJe.displayName=oAt;var lAt="DropdownMenuSeparator",mJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(GEt,{...a,...n,ref:t})});mJe.displayName=lAt;var cAt="DropdownMenuArrow",dAt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(WEt,{...a,...n,ref:t})});dAt.displayName=cAt;var uAt="DropdownMenuSubTrigger",fJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(KEt,{...a,...n,ref:t})});fJe.displayName=uAt;var hAt="DropdownMenuSubContent",pJe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Pf(r);return e.jsx(YEt,{...a,...n,ref:t,style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});pJe.displayName=hAt;var mAt=sJe,fAt=nJe,pAt=aJe,xJe=oJe,gJe=lJe,yJe=cJe,vJe=dJe,bJe=uJe,_Je=hJe,wJe=mJe,jJe=fJe,NJe=pJe;const lu=mAt,cu=fAt,xAt=k.forwardRef(({className:s,inset:t,children:r,...n},a)=>e.jsxs(jJe,{ref:a,className:Bt("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(ya,{className:"ml-auto h-4 w-4"})]}));xAt.displayName=jJe.displayName;const gAt=k.forwardRef(({className:s,...t},r)=>e.jsx(NJe,{ref:r,className:Bt("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}));gAt.displayName=NJe.displayName;const Vd=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(pAt,{children:e.jsx(xJe,{ref:n,sideOffset:t,className:Bt("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})}));Vd.displayName=xJe.displayName;const Da=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(yJe,{ref:n,className:Bt("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}));Da.displayName=yJe.displayName;const yAt=k.forwardRef(({className:s,children:t,checked:r,...n},a)=>e.jsxs(vJe,{ref:a,className:Bt("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(_Je,{children:e.jsx(Hn,{className:"h-4 w-4"})})}),t]}));yAt.displayName=vJe.displayName;const vAt=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(bJe,{ref:n,className:Bt("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(_Je,{children:e.jsx(Bd,{className:"h-2 w-2 fill-current"})})}),t]}));vAt.displayName=bJe.displayName;const Tue=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(gJe,{ref:n,className:Bt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...r}));Tue.displayName=gJe.displayName;const y_=k.forwardRef(({className:s,...t},r)=>e.jsx(wJe,{ref:r,className:Bt("-mx-1 my-1 h-px bg-muted",s),...t}));y_.displayName=wJe.displayName;const bAt=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:a,setActingAsSelf:i}=$4e();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(Bi,{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(fr,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(vn,{className:"h-5 w-5",children:[e.jsx(ga,{src:t.avatar_url||void 0}),e.jsx(bn,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(so,{className:"h-3 w-3"})]})}),e.jsxs(Vd,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Da,{onClick:i,className:"gap-2",children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Ge,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(y_,{}),r.map(o=>e.jsxs(Da,{onClick:()=>n(o),className:"gap-2",children:[e.jsxs(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:o.avatar_url||void 0}),e.jsx(bn,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Ge,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Ge,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},er=({children:s,requireAdmin:t=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=As(),c=sc();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(Qve,{to:"/auth",replace:!0})}return t&&!l?e.jsx(Qve,{to:"/dashboard",replace:!0}):r&&!o&&!l?e.jsx(Qve,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var Z4e={};(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 me=new OffscreenCanvas(1,1),oe=me.getContext("2d");oe.fillRect(0,0,1,1);var ge=me.transferToImageBitmap();oe.createPattern(ge,"no-repeat")}catch{return!1}return!0}();function c(){}function d(me){var oe=r.exports.Promise,ge=oe!==void 0?oe:t.Promise;return typeof ge=="function"?new ge(me):(me(c,c),null)}var h=function(me,oe){return{transform:function(ge){if(me)return ge;if(oe.has(ge))return oe.get(ge);var be=new OffscreenCanvas(ge.width,ge.height),Oe=be.getContext("2d");return Oe.drawImage(ge,0,0),oe.set(ge,be),be},clear:function(){oe.clear()}}}(o,new Map),m=function(){var me=Math.floor(16.666666666666668),oe,ge,be={},Oe=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(oe=function(Me){var Pe=Math.random();return be[Pe]=requestAnimationFrame(function Ee($e){Oe===$e||Oe+me-1<$e?(Oe=$e,delete be[Pe],Me()):be[Pe]=requestAnimationFrame(Ee)}),Pe},ge=function(Me){be[Me]&&cancelAnimationFrame(be[Me])}):(oe=function(Me){return setTimeout(Me,me)},ge=function(Me){return clearTimeout(Me)}),{frame:oe,cancel:ge}}(),x=function(){var me,oe,ge={};function be(Oe){function Me(Pe,Ee){Oe.postMessage({options:Pe||{},callback:Ee})}Oe.init=function(Ee){var $e=Ee.transferControlToOffscreen();Oe.postMessage({canvas:$e},[$e])},Oe.fire=function(Ee,$e,Se){if(oe)return Me(Ee,null),oe;var ze=Math.random().toString(36).slice(2);return oe=d(function(Te){function ye(ct){ct.data.callback===ze&&(delete ge[ze],Oe.removeEventListener("message",ye),oe=null,h.clear(),Se(),Te())}Oe.addEventListener("message",ye),Me(Ee,ze),ge[ze]=ye.bind(null,{data:{callback:ze}})}),oe},Oe.reset=function(){Oe.postMessage({reset:!0});for(var Ee in ge)ge[Ee](),delete ge[Ee]}}return function(){if(me)return me;if(!n&&i){var Oe=["var CONFETTI, SIZE = {}, module = {};","("+s.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(` `);try{me=new Worker(URL.createObjectURL(new Blob([Oe])))}catch(Me){return typeof console<"u"&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",Me),null}be(me)}return me}}(),g={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function v(me,oe){return oe?oe(me):me}function j(me){return me!=null}function b(me,oe,ge){return v(me&&j(me[oe])?me[oe]:g[oe],ge)}function N(me){return me<0?0:Math.floor(me)}function S(me,oe){return Math.floor(Math.random()*(oe-me))+me}function T(me){return parseInt(me,16)}function A(me){return me.map(P)}function P(me){var oe=String(me).replace(/[^0-9a-f]/gi,"");return oe.length<6&&(oe=oe[0]+oe[0]+oe[1]+oe[1]+oe[2]+oe[2]),{r:T(oe.substring(0,2)),g:T(oe.substring(2,4)),b:T(oe.substring(4,6))}}function D(me){var oe=b(me,"origin",Object);return oe.x=b(oe,"x",Number),oe.y=b(oe,"y",Number),oe}function B(me){me.width=document.documentElement.clientWidth,me.height=document.documentElement.clientHeight}function z(me){var oe=me.getBoundingClientRect();me.width=oe.width,me.height=oe.height}function F(me){var oe=document.createElement("canvas");return oe.style.position="fixed",oe.style.top="0px",oe.style.left="0px",oe.style.pointerEvents="none",oe.style.zIndex=me,oe}function $(me,oe,ge,be,Oe,Me,Pe,Ee,$e){me.save(),me.translate(oe,ge),me.rotate(Me),me.scale(be,Oe),me.arc(0,0,1,Pe,Ee,$e),me.restore()}function X(me){var oe=me.angle*(Math.PI/180),ge=me.spread*(Math.PI/180);return{x:me.x,y:me.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:me.startVelocity*.5+Math.random()*me.startVelocity,angle2D:-oe+(.5*ge-Math.random()*ge),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:me.color,shape:me.shape,tick:0,totalTicks:me.ticks,decay:me.decay,drift:me.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:me.gravity*3,ovalScalar:.6,scalar:me.scalar,flat:me.flat}}function K(me,oe){oe.x+=Math.cos(oe.angle2D)*oe.velocity+oe.drift,oe.y+=Math.sin(oe.angle2D)*oe.velocity+oe.gravity,oe.velocity*=oe.decay,oe.flat?(oe.wobble=0,oe.wobbleX=oe.x+10*oe.scalar,oe.wobbleY=oe.y+10*oe.scalar,oe.tiltSin=0,oe.tiltCos=0,oe.random=1):(oe.wobble+=oe.wobbleSpeed,oe.wobbleX=oe.x+10*oe.scalar*Math.cos(oe.wobble),oe.wobbleY=oe.y+10*oe.scalar*Math.sin(oe.wobble),oe.tiltAngle+=.1,oe.tiltSin=Math.sin(oe.tiltAngle),oe.tiltCos=Math.cos(oe.tiltAngle),oe.random=Math.random()+2);var ge=oe.tick++/oe.totalTicks,be=oe.x+oe.random*oe.tiltCos,Oe=oe.y+oe.random*oe.tiltSin,Me=oe.wobbleX+oe.random*oe.tiltCos,Pe=oe.wobbleY+oe.random*oe.tiltSin;if(me.fillStyle="rgba("+oe.color.r+", "+oe.color.g+", "+oe.color.b+", "+(1-ge)+")",me.beginPath(),l&&oe.shape.type==="path"&&typeof oe.shape.path=="string"&&Array.isArray(oe.shape.matrix))me.fill(ce(oe.shape.path,oe.shape.matrix,oe.x,oe.y,Math.abs(Me-be)*.1,Math.abs(Pe-Oe)*.1,Math.PI/10*oe.wobble));else if(oe.shape.type==="bitmap"){var Ee=Math.PI/10*oe.wobble,$e=Math.abs(Me-be)*.1,Se=Math.abs(Pe-Oe)*.1,ze=oe.shape.bitmap.width*oe.scalar,Te=oe.shape.bitmap.height*oe.scalar,ye=new DOMMatrix([Math.cos(Ee)*$e,Math.sin(Ee)*$e,-Math.sin(Ee)*Se,Math.cos(Ee)*Se,oe.x,oe.y]);ye.multiplySelf(new DOMMatrix(oe.shape.matrix));var ct=me.createPattern(h.transform(oe.shape.bitmap),"no-repeat");ct.setTransform(ye),me.globalAlpha=1-ge,me.fillStyle=ct,me.fillRect(oe.x-ze/2,oe.y-Te/2,ze,Te),me.globalAlpha=1}else if(oe.shape==="circle")me.ellipse?me.ellipse(oe.x,oe.y,Math.abs(Me-be)*oe.ovalScalar,Math.abs(Pe-Oe)*oe.ovalScalar,Math.PI/10*oe.wobble,0,2*Math.PI):$(me,oe.x,oe.y,Math.abs(Me-be)*oe.ovalScalar,Math.abs(Pe-Oe)*oe.ovalScalar,Math.PI/10*oe.wobble,0,2*Math.PI);else if(oe.shape==="star")for(var ve=Math.PI/2*3,rt=4*oe.scalar,Re=8*oe.scalar,Qe=oe.x,Ke=oe.y,Ce=5,nt=Math.PI/Ce;Ce--;)Qe=oe.x+Math.cos(ve)*Re,Ke=oe.y+Math.sin(ve)*Re,me.lineTo(Qe,Ke),ve+=nt,Qe=oe.x+Math.cos(ve)*rt,Ke=oe.y+Math.sin(ve)*rt,me.lineTo(Qe,Ke),ve+=nt;else me.moveTo(Math.floor(oe.x),Math.floor(oe.y)),me.lineTo(Math.floor(oe.wobbleX),Math.floor(Oe)),me.lineTo(Math.floor(Me),Math.floor(Pe)),me.lineTo(Math.floor(be),Math.floor(oe.wobbleY));return me.closePath(),me.fill(),oe.tick{const{data:t,error:r}=await H.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 wAt(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function jAt(){const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{error:n}=await H.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 ppe="Dialog",[kJe,SJe]=yd(ppe),[NAt,x0]=kJe(ppe),CJe=s=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=k.useRef(null),c=k.useRef(null),[d,h]=Lh({prop:n,defaultProp:a??!1,onChange:i,caller:ppe});return e.jsx(NAt,{scope:t,triggerRef:o,contentRef:c,contentId:Qu(),titleId:Qu(),descriptionId:Qu(),open:d,onOpenChange:h,onOpenToggle:k.useCallback(()=>h(m=>!m),[h]),modal:l,children:r})};CJe.displayName=ppe;var TJe="DialogTrigger",EJe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=x0(TJe,r),i=Qa(t,a.triggerRef);return e.jsx(pn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":J4e(a.open),...n,ref:i,onClick:Or(s.onClick,a.onOpenToggle)})});EJe.displayName=TJe;var X4e="DialogPortal",[kAt,AJe]=kJe(X4e,{forceMount:void 0}),MJe=s=>{const{__scopeDialog:t,forceMount:r,children:n,container:a}=s,i=x0(X4e,t);return e.jsx(kAt,{scope:t,forceMount:r,children:k.Children.map(n,l=>e.jsx(qd,{present:r||i.open,children:e.jsx(xP,{asChild:!0,container:a,children:l})}))})};MJe.displayName=X4e;var Eue="DialogOverlay",IJe=k.forwardRef((s,t)=>{const r=AJe(Eue,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=x0(Eue,s.__scopeDialog);return i.modal?e.jsx(qd,{present:n||i.open,children:e.jsx(CAt,{...a,ref:t})}):null});IJe.displayName=Eue;var SAt=v2("DialogOverlay.RemoveScroll"),CAt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=x0(Eue,r);return e.jsx(BB,{as:SAt,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(pn.div,{"data-state":J4e(a.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),x5="DialogContent",PJe=k.forwardRef((s,t)=>{const r=AJe(x5,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=x0(x5,s.__scopeDialog);return e.jsx(qd,{present:n||i.open,children:i.modal?e.jsx(TAt,{...a,ref:t}):e.jsx(EAt,{...a,ref:t})})});PJe.displayName=x5;var TAt=k.forwardRef((s,t)=>{const r=x0(x5,s.__scopeDialog),n=k.useRef(null),a=Qa(t,r.contentRef,n);return k.useEffect(()=>{const i=n.current;if(i)return dpe(i)},[]),e.jsx(LJe,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:Or(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:Or(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:Or(s.onFocusOutside,i=>i.preventDefault())})}),EAt=k.forwardRef((s,t)=>{const r=x0(x5,s.__scopeDialog),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(LJe,{...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()}})}),LJe=k.forwardRef((s,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=x0(x5,r),c=k.useRef(null),d=Qa(t,c);return ope(),e.jsxs(e.Fragment,{children:[e.jsx(OB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(F2,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":J4e(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(MAt,{titleId:o.titleId}),e.jsx(PAt,{contentRef:c,descriptionId:o.descriptionId})]})]})}),Q4e="DialogTitle",DJe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=x0(Q4e,r);return e.jsx(pn.h2,{id:a.titleId,...n,ref:t})});DJe.displayName=Q4e;var RJe="DialogDescription",OJe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=x0(RJe,r);return e.jsx(pn.p,{id:a.descriptionId,...n,ref:t})});OJe.displayName=RJe;var FJe="DialogClose",BJe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=x0(FJe,r);return e.jsx(pn.button,{type:"button",...n,ref:t,onClick:Or(s.onClick,()=>a.onOpenChange(!1))})});BJe.displayName=FJe;function J4e(s){return s?"open":"closed"}var zJe="DialogTitleWarning",[AAt,$Je]=jjt(zJe,{contentName:x5,titleName:Q4e,docsSlug:"dialog"}),MAt=({titleId:s})=>{const t=$Je(zJe),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},IAt="DialogDescriptionWarning",PAt=({contentRef:s,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${$Je(IAt).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},xpe=CJe,e3e=EJe,gpe=MJe,SP=IJe,CP=PJe,UB=DJe,qB=OJe,VB=BJe;const vs=xpe,Ni=e3e,LAt=gpe,HUs=VB,UJe=k.forwardRef(({className:s,...t},r)=>e.jsx(SP,{ref:r,className:Bt("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}));UJe.displayName=SP.displayName;const ys=k.forwardRef(({className:s,children:t,overlayClassName:r,...n},a)=>e.jsxs(LAt,{children:[e.jsx(UJe,{className:r}),e.jsxs(CP,{ref:a,className:Bt("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(VB,{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=CP.displayName;const js=({className:s,...t})=>e.jsx("div",{className:Bt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});js.displayName="DialogHeader";const on=({className:s,...t})=>e.jsx("div",{className:Bt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});on.displayName="DialogFooter";const bs=k.forwardRef(({className:s,...t},r)=>e.jsx(UB,{ref:r,className:Bt("text-lg font-semibold leading-none tracking-tight",s),...t}));bs.displayName=UB.displayName;const Fr=k.forwardRef(({className:s,...t},r)=>e.jsx(qB,{ref:r,className:Bt("text-sm text-muted-foreground",s),...t}));Fr.displayName=qB.displayName;const DAt={points_earned:Zi,listing_created:Cn,deal_closed:_l,custom:Qn},fOe={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"},pOe=()=>{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 RAt(){const{user:s}=As(),t=es(),{data:r}=_At(),n=wAt(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=k.useCallback(()=>{const g=Date.now()+3e3,v={startVelocity:30,spread:360,ticks:60,zIndex:9999},j=(N,S)=>Math.random()*(S-N)+N,b=setInterval(()=>{const N=g-Date.now();if(N<=0){clearInterval(b);return}const S=50*(N/3e3);mOe({...v,particleCount:S,origin:{x:j(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),mOe({...v,particleCount:S,origin:{x:j(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);k.useEffect(()=>{pOe()||r&&r.length>0&&!a&&(i(r[0]),o(!0),setTimeout(c,100))},[r,a,c]);const d=async()=>{if(a){const x=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],g=>(g==null?void 0:g.filter(v=>v.id!==x))??[]),await n.mutateAsync(x)}};if(pOe()||!a)return null;const h=DAt[a.celebration_type]||Qn,m=fOe[a.celebration_type]||fOe.custom;return e.jsx(vs,{open:l,onOpenChange:x=>!x&&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(h,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(jr,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(jr,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(jr,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(G,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}const t3e="/assets/levelup-logo-horizontal-DEFNc0ms.png",s3e="/assets/levelup-logo-white-C2RAgAoG.png",OAt="/assets/listings-hero-BI9Ki9Dq.jpg",ke=k.forwardRef(({className:s,type:t,...r},n)=>e.jsx("input",{type:t,className:Bt("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}));ke.displayName="Input";var qJe={exports:{}};(function(s,t){(function(r,n){s.exports=n()})(su,function(){let r,n,a;function i(o,c){if(!r)r=c;else if(!n)n=c;else{const d={};r(void 0,d),a=c(d);const h="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; ("+r+")(undefined, sharedChunk); ("+n+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([h],{type:"text/javascript"})))}}i(["require","exports"],function(o,c){var d=1e-6,h=typeof Float32Array<"u"?Float32Array:Array;function m(y,u){var p=u[0],_=u[1],C=u[2],M=u[3],L=p*M-C*_;return L?(y[0]=M*(L=1/L),y[1]=-_*L,y[2]=-C*L,y[3]=p*L,y):null}function x(){var y=new h(9);return h!=Float32Array&&(y[1]=0,y[2]=0,y[3]=0,y[5]=0,y[6]=0,y[7]=0),y[0]=1,y[4]=1,y[8]=1,y}function g(y,u){var p=u[0],_=u[1],C=u[2],M=u[3],L=u[4],O=u[5],U=u[6],W=u[7],J=u[8];return y[0]=L*J-O*W,y[1]=C*W-_*J,y[2]=_*O-C*L,y[3]=O*U-M*J,y[4]=p*J-C*U,y[5]=C*M-p*O,y[6]=M*W-L*U,y[7]=_*U-p*W,y[8]=p*L-_*M,y}function v(y,u,p){var _=u[0],C=u[1],M=u[2],L=u[3],O=u[4],U=u[5],W=u[6],J=u[7],se=u[8],re=p[0],fe=p[1],xe=p[2],we=p[3],je=p[4],Be=p[5],Ye=p[6],Ue=p[7],tt=p[8];return y[0]=re*_+fe*L+xe*W,y[1]=re*C+fe*O+xe*J,y[2]=re*M+fe*U+xe*se,y[3]=we*_+je*L+Be*W,y[4]=we*C+je*O+Be*J,y[5]=we*M+je*U+Be*se,y[6]=Ye*_+Ue*L+tt*W,y[7]=Ye*C+Ue*O+tt*J,y[8]=Ye*M+Ue*U+tt*se,y}function j(){var y=new h(16);return h!=Float32Array&&(y[1]=0,y[2]=0,y[3]=0,y[4]=0,y[6]=0,y[7]=0,y[8]=0,y[9]=0,y[11]=0,y[12]=0,y[13]=0,y[14]=0),y[0]=1,y[5]=1,y[10]=1,y[15]=1,y}function b(y){var u=new h(16);return u[0]=y[0],u[1]=y[1],u[2]=y[2],u[3]=y[3],u[4]=y[4],u[5]=y[5],u[6]=y[6],u[7]=y[7],u[8]=y[8],u[9]=y[9],u[10]=y[10],u[11]=y[11],u[12]=y[12],u[13]=y[13],u[14]=y[14],u[15]=y[15],u}function N(y){return y[0]=1,y[1]=0,y[2]=0,y[3]=0,y[4]=0,y[5]=1,y[6]=0,y[7]=0,y[8]=0,y[9]=0,y[10]=1,y[11]=0,y[12]=0,y[13]=0,y[14]=0,y[15]=1,y}function S(y,u){var p=u[0],_=u[1],C=u[2],M=u[3],L=u[4],O=u[5],U=u[6],W=u[7],J=u[8],se=u[9],re=u[10],fe=u[11],xe=u[12],we=u[13],je=u[14],Be=u[15],Ye=p*O-_*L,Ue=p*U-C*L,tt=p*W-M*L,ot=_*U-C*O,pt=_*W-M*O,Rt=C*W-M*U,_t=J*we-se*xe,Et=J*je-re*xe,jt=J*Be-fe*xe,At=se*je-re*we,ns=se*Be-fe*we,is=re*Be-fe*je,xs=Ye*is-Ue*ns+tt*At+ot*jt-pt*Et+Rt*_t;return xs?(y[0]=(O*is-U*ns+W*At)*(xs=1/xs),y[1]=(C*ns-_*is-M*At)*xs,y[2]=(we*Rt-je*pt+Be*ot)*xs,y[3]=(re*pt-se*Rt-fe*ot)*xs,y[4]=(U*jt-L*is-W*Et)*xs,y[5]=(p*is-C*jt+M*Et)*xs,y[6]=(je*tt-xe*Rt-Be*Ue)*xs,y[7]=(J*Rt-re*tt+fe*Ue)*xs,y[8]=(L*ns-O*jt+W*_t)*xs,y[9]=(_*jt-p*ns-M*_t)*xs,y[10]=(xe*pt-we*tt+Be*Ye)*xs,y[11]=(se*tt-J*pt-fe*Ye)*xs,y[12]=(O*Et-L*At-U*_t)*xs,y[13]=(p*At-_*Et+C*_t)*xs,y[14]=(we*Ue-xe*ot-je*Ye)*xs,y[15]=(J*ot-se*Ue+re*Ye)*xs,y):null}function T(y,u,p){var _=u[0],C=u[1],M=u[2],L=u[3],O=u[4],U=u[5],W=u[6],J=u[7],se=u[8],re=u[9],fe=u[10],xe=u[11],we=u[12],je=u[13],Be=u[14],Ye=u[15],Ue=p[0],tt=p[1],ot=p[2],pt=p[3];return y[0]=Ue*_+tt*O+ot*se+pt*we,y[1]=Ue*C+tt*U+ot*re+pt*je,y[2]=Ue*M+tt*W+ot*fe+pt*Be,y[3]=Ue*L+tt*J+ot*xe+pt*Ye,y[4]=(Ue=p[4])*_+(tt=p[5])*O+(ot=p[6])*se+(pt=p[7])*we,y[5]=Ue*C+tt*U+ot*re+pt*je,y[6]=Ue*M+tt*W+ot*fe+pt*Be,y[7]=Ue*L+tt*J+ot*xe+pt*Ye,y[8]=(Ue=p[8])*_+(tt=p[9])*O+(ot=p[10])*se+(pt=p[11])*we,y[9]=Ue*C+tt*U+ot*re+pt*je,y[10]=Ue*M+tt*W+ot*fe+pt*Be,y[11]=Ue*L+tt*J+ot*xe+pt*Ye,y[12]=(Ue=p[12])*_+(tt=p[13])*O+(ot=p[14])*se+(pt=p[15])*we,y[13]=Ue*C+tt*U+ot*re+pt*je,y[14]=Ue*M+tt*W+ot*fe+pt*Be,y[15]=Ue*L+tt*J+ot*xe+pt*Ye,y}function A(y,u,p){var _,C,M,L,O,U,W,J,se,re,fe,xe,we=p[0],je=p[1],Be=p[2];return u===y?(y[12]=u[0]*we+u[4]*je+u[8]*Be+u[12],y[13]=u[1]*we+u[5]*je+u[9]*Be+u[13],y[14]=u[2]*we+u[6]*je+u[10]*Be+u[14],y[15]=u[3]*we+u[7]*je+u[11]*Be+u[15]):(C=u[1],M=u[2],L=u[3],O=u[4],U=u[5],W=u[6],J=u[7],se=u[8],re=u[9],fe=u[10],xe=u[11],y[0]=_=u[0],y[1]=C,y[2]=M,y[3]=L,y[4]=O,y[5]=U,y[6]=W,y[7]=J,y[8]=se,y[9]=re,y[10]=fe,y[11]=xe,y[12]=_*we+O*je+se*Be+u[12],y[13]=C*we+U*je+re*Be+u[13],y[14]=M*we+W*je+fe*Be+u[14],y[15]=L*we+J*je+xe*Be+u[15]),y}function P(y,u,p){var _=p[0],C=p[1],M=p[2];return y[0]=u[0]*_,y[1]=u[1]*_,y[2]=u[2]*_,y[3]=u[3]*_,y[4]=u[4]*C,y[5]=u[5]*C,y[6]=u[6]*C,y[7]=u[7]*C,y[8]=u[8]*M,y[9]=u[9]*M,y[10]=u[10]*M,y[11]=u[11]*M,y[12]=u[12],y[13]=u[13],y[14]=u[14],y[15]=u[15],y}function D(y,u,p){var _=Math.sin(p),C=Math.cos(p),M=u[4],L=u[5],O=u[6],U=u[7],W=u[8],J=u[9],se=u[10],re=u[11];return u!==y&&(y[0]=u[0],y[1]=u[1],y[2]=u[2],y[3]=u[3],y[12]=u[12],y[13]=u[13],y[14]=u[14],y[15]=u[15]),y[4]=M*C+W*_,y[5]=L*C+J*_,y[6]=O*C+se*_,y[7]=U*C+re*_,y[8]=W*C-M*_,y[9]=J*C-L*_,y[10]=se*C-O*_,y[11]=re*C-U*_,y}function B(y,u,p){var _=Math.sin(p),C=Math.cos(p),M=u[0],L=u[1],O=u[2],U=u[3],W=u[8],J=u[9],se=u[10],re=u[11];return u!==y&&(y[4]=u[4],y[5]=u[5],y[6]=u[6],y[7]=u[7],y[12]=u[12],y[13]=u[13],y[14]=u[14],y[15]=u[15]),y[0]=M*C-W*_,y[1]=L*C-J*_,y[2]=O*C-se*_,y[3]=U*C-re*_,y[8]=M*_+W*C,y[9]=L*_+J*C,y[10]=O*_+se*C,y[11]=U*_+re*C,y}function z(y,u,p){var _=Math.sin(p),C=Math.cos(p),M=u[0],L=u[1],O=u[2],U=u[3],W=u[4],J=u[5],se=u[6],re=u[7];return u!==y&&(y[8]=u[8],y[9]=u[9],y[10]=u[10],y[11]=u[11],y[12]=u[12],y[13]=u[13],y[14]=u[14],y[15]=u[15]),y[0]=M*C+W*_,y[1]=L*C+J*_,y[2]=O*C+se*_,y[3]=U*C+re*_,y[4]=W*C-M*_,y[5]=J*C-L*_,y[6]=se*C-O*_,y[7]=re*C-U*_,y}function F(y,u){return y[0]=1,y[1]=0,y[2]=0,y[3]=0,y[4]=0,y[5]=1,y[6]=0,y[7]=0,y[8]=0,y[9]=0,y[10]=1,y[11]=0,y[12]=u[0],y[13]=u[1],y[14]=u[2],y[15]=1,y}function $(y,u){return y[0]=u[0],y[1]=0,y[2]=0,y[3]=0,y[4]=0,y[5]=u[1],y[6]=0,y[7]=0,y[8]=0,y[9]=0,y[10]=u[2],y[11]=0,y[12]=0,y[13]=0,y[14]=0,y[15]=1,y}function X(y,u,p){var _,C,M,L=p[0],O=p[1],U=p[2],W=Math.sqrt(L*L+O*O+U*U);return W0&&(M=1/Math.sqrt(M)),y[0]=u[0]*M,y[1]=u[1]*M,y[2]=u[2]*M,y}function ye(y,u){return y[0]*u[0]+y[1]*u[1]+y[2]*u[2]}function ct(y,u,p){var _=u[0],C=u[1],M=u[2],L=p[0],O=p[1],U=p[2];return y[0]=C*U-M*O,y[1]=M*L-_*U,y[2]=_*O-C*L,y}function ve(y,u,p,_){var C=u[0],M=u[1],L=u[2];return y[0]=C+_*(p[0]-C),y[1]=M+_*(p[1]-M),y[2]=L+_*(p[2]-L),y}function rt(y,u,p){var _=u[0],C=u[1],M=u[2],L=p[3]*_+p[7]*C+p[11]*M+p[15];return y[0]=(p[0]*_+p[4]*C+p[8]*M+p[12])/(L=L||1),y[1]=(p[1]*_+p[5]*C+p[9]*M+p[13])/L,y[2]=(p[2]*_+p[6]*C+p[10]*M+p[14])/L,y}function Re(y,u,p){var _=u[0],C=u[1],M=u[2];return y[0]=_*p[0]+C*p[3]+M*p[6],y[1]=_*p[1]+C*p[4]+M*p[7],y[2]=_*p[2]+C*p[5]+M*p[8],y}function Qe(y,u,p){var _=p[0],C=p[1],M=p[2],L=p[3],O=u[0],U=u[1],W=u[2],J=C*W-M*U,se=M*O-_*W,re=_*U-C*O;return y[0]=O+L*(J+=J)+C*(re+=re)-M*(se+=se),y[1]=U+L*se+M*J-_*re,y[2]=W+L*re+_*se-C*J,y}function Ke(y){return y[0]=0,y[1]=0,y[2]=0,y}function Ce(y,u){return y[0]===u[0]&&y[1]===u[1]&&y[2]===u[2]}var nt=oe,$t=ge,lt=ce;function it(){var y=new h(4);return h!=Float32Array&&(y[0]=0,y[1]=0,y[2]=0,y[3]=0),y}function Nt(y,u,p){return y[0]=u[0]*p,y[1]=u[1]*p,y[2]=u[2]*p,y[3]=u[3]*p,y}function Ft(y,u){var p=u[0],_=u[1],C=u[2],M=u[3],L=p*p+_*_+C*C+M*M;return L>0&&(L=1/Math.sqrt(L)),y[0]=p*L,y[1]=_*L,y[2]=C*L,y[3]=M*L,y}function at(y,u,p){var _=u[0],C=u[1],M=u[2],L=u[3];return y[0]=p[0]*_+p[4]*C+p[8]*M+p[12]*L,y[1]=p[1]*_+p[5]*C+p[9]*M+p[13]*L,y[2]=p[2]*_+p[6]*C+p[10]*M+p[14]*L,y[3]=p[3]*_+p[7]*C+p[11]*M+p[15]*L,y}function Ie(){var y=new h(4);return h!=Float32Array&&(y[0]=0,y[1]=0,y[2]=0),y[3]=1,y}function et(y){return y[0]=0,y[1]=0,y[2]=0,y[3]=1,y}function Dt(y,u,p){p*=.5;var _=u[0],C=u[1],M=u[2],L=u[3],O=Math.sin(p),U=Math.cos(p);return y[0]=_*U+L*O,y[1]=C*U+M*O,y[2]=M*U-C*O,y[3]=L*U-_*O,y}function Jt(y,u,p){p*=.5;var _=u[0],C=u[1],M=u[2],L=u[3],O=Math.sin(p),U=Math.cos(p);return y[0]=_*U-M*O,y[1]=C*U+L*O,y[2]=M*U+_*O,y[3]=L*U-C*O,y}ne(),it();var cs,Ht,dt,Qt=Ft,yt=(cs=ne(),Ht=ae(1,0,0),dt=ae(0,1,0),function(y,u,p){var _=ye(u,p);return _<-.999999?(ct(cs,Ht,u),lt(cs)<1e-6&&ct(cs,dt,u),Te(cs,cs),function(C,M,L){L*=.5;var O=Math.sin(L);C[0]=O*M[0],C[1]=O*M[1],C[2]=O*M[2],C[3]=Math.cos(L)}(y,cs,Math.PI),y):_>.999999?(y[0]=0,y[1]=0,y[2]=0,y[3]=1,y):(ct(cs,u,p),y[0]=cs[0],y[1]=cs[1],y[2]=cs[2],y[3]=1+_,Qt(y,y))});function ss(){var y=new h(2);return h!=Float32Array&&(y[0]=0,y[1]=0),y}function Is(y,u){var p=new h(2);return p[0]=y,p[1]=u,p}function fs(y,u,p){return y[0]=u,y[1]=p,y}function ar(y,u,p){return y[0]=u[0]+p[0],y[1]=u[1]+p[1],y}function Er(y,u,p){return y[0]=u[0]-p[0],y[1]=u[1]-p[1],y}function Tr(y,u,p){return y[0]=u[0]*p,y[1]=u[1]*p,y}function Lr(y){var u=y[0],p=y[1];return Math.sqrt(u*u+p*p)}function $r(y,u){var p=u[0],_=u[1],C=p*p+_*_;return C>0&&(C=1/Math.sqrt(C)),y[0]=u[0]*C,y[1]=u[1]*C,y}function kr(y,u){return y[0]*u[0]+y[1]*u[1]}Ie(),Ie(),x();var Sr,hn,zn=Er;function Xs(y){return y&&y.__esModule&&Object.prototype.hasOwnProperty.call(y,"default")?y.default:y}ss();var Ur=function(){if(hn)return Sr;function y(u,p,_,C){this.cx=3*u,this.bx=3*(_-u)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*p,this.by=3*(C-p)-this.cy,this.ay=1-this.cy-this.by,this.p1x=u,this.p1y=p,this.p2x=_,this.p2y=C}return hn=1,Sr=y,y.prototype={sampleCurveX:function(u){return((this.ax*u+this.bx)*u+this.cx)*u},sampleCurveY:function(u){return((this.ay*u+this.by)*u+this.cy)*u},sampleCurveDerivativeX:function(u){return(3*this.ax*u+2*this.bx)*u+this.cx},solveCurveX:function(u,p){if(p===void 0&&(p=1e-6),u<0)return 0;if(u>1)return 1;for(var _=u,C=0;C<8;C++){var M=this.sampleCurveX(_)-u;if(Math.abs(M)M?O=_:U=_,_=.5*(U-O)+O;return _},solve:function(u,p){return this.sampleCurveY(this.solveCurveX(u,p))}},Sr}(),xn=Xs(Ur);function us(y,u){this.x=y,this.y=u}function pr(y,u){if(Array.isArray(y)){if(!Array.isArray(u)||y.length!==u.length)return!1;for(let p=0;p=1)return 1;const u=y*y,p=u*y;return 4*(y<.5?p:3*(y-u)+p-.75)}function kt(y,u,p,_){const C=new xn(y,u,p,_);return function(M){return C.solve(M)}}const Gt=kt(.25,.1,.25,1);function Mt(y,u,p){return Math.min(p,Math.max(u,y))}function Kt(y,u,p){return(p=Mt((p-y)/(u-y),0,1))*p*(3-2*p)}function Es(y,u,p){const _=p-u,C=((y-u)%_+_)%_+u;return C===u?p:C}function Ls(y,u,p){if(!y.length)return p(null,[]);let _=y.length;const C=new Array(y.length);let M=null;y.forEach((L,O)=>{u(L,(U,W)=>{U&&(M=U),C[O]=W,--_===0&&p(M,C)})})}function gr(y,u){const p={};for(let _=0;_{u[p]&&(u[p]=u[p].bind(u))})}function $s(y,u,p){const _={};for(const C in y)_[C]=u.call(this,y[C],C,y);return _}function Kr(y,u,p){const _={};for(const C in y)u.call(this,y[C],C,y)&&(_[C]=y[C]);return _}function In(y){return Array.isArray(y)?y.map(In):typeof y=="object"&&y?$s(y,In):y}function Ja(y,u){for(let p=0;p(u.y-y.y)*(p.x-y.x)}function Qi(y){let u=0;for(let p,_,C=0,M=y.length,L=M-1;C@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(p,_,C,M)=>{const L=C||M;return u[_]=!L||L.toLowerCase(),""}),u["max-age"]){const p=parseInt(u["max-age"],10);isNaN(p)?delete u["max-age"]:u["max-age"]=p}return u}let jo,Pi=null;function Lo(y,u){return[y[4*u],y[4*u+1],y[4*u+2],y[4*u+3]]}function rc(y,u,p,_){for(;u>1;y[C]<_?u=C+1:p=C}return u}function dr(y,u,p,_){for(;u>1;y[C]<=_?u=C+1:p=C}return u}function Jn(y){return y>0?1/(1.001-y):1+y}function uo(y){return y>0?1-1/(1.001-y):-y}function ll(y,u,p){return(y-u.min)*(p.max-p.min)/(u.max-u.min)+p.min}const Va={API_URL:"https://api.mapbox.com",API_URL_REGEX:/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i,API_TILEJSON_REGEX:/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i,API_SPRITE_REGEX:/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i,API_FONTS_REGEX:/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i,API_STYLE_REGEX:/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i,API_CDN_URL_REGEX:/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i,get EVENTS_URL(){if(!Va.API_URL)return null;try{const y=new URL(Va.API_URL);return y.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":y.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/plugins/mapbox-gl-pmtiles-provider/v0.0.2/mapbox-gl-pmtiles-provider.js"})};function Dl(){return new URL(Va.DRACO_URL,Va.API_URL).href}function Wm(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(jo===void 0){if(typeof WebAssembly!="object")return!1;const y=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]);jo=WebAssembly.validate(y)}return jo}()?Va.MESHOPT_SIMD_URL:Va.MESHOPT_URL,Va.API_URL).href}function Lf(){return new URL(Va.BUILDING_GEN_URL,Va.API_URL).href}function Gx(y){return Va.API_URL_REGEX.test(y)}function j0(y){return Va.API_SPRITE_REGEX.test(y)}let F_,E1,Do,vd,iy,N0;function Df(){return F_==null&&(F_=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),F_}const bd={requestIdleCallback:y=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(y);setTimeout(()=>y({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>vd!==void 0?vd:performance.now(),setNow(y){vd=y},restoreNow(){vd=void 0},frame(y){const u=requestAnimationFrame(y);return{cancel:()=>cancelAnimationFrame(u)}},getImageData(y,u=0){const{width:p,height:_}=y;iy||(iy=document.createElement("canvas"));const C=iy.getContext("2d",{willReadFrequently:!0});if(!C)throw new Error("failed to create canvas 2d context");return(p>iy.width||_>iy.height)&&(iy.width=p,iy.height=_),C.clearRect(-u,-u,p+2*u,_+2*u),C.drawImage(y,0,0,p,_),C.getImageData(-u,-u,p+2*u,_+2*u)},resolveURL:y=>(E1||(E1=document.createElement("a")),E1.href=y,E1.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Do==null&&(Do=window.matchMedia("(prefers-reduced-motion: reduce)")),Do.matches)},hasCanvasFingerprintNoise(){if(N0!==void 0)return N0;if(!Df())return N0=!1,!1;const y=new OffscreenCanvas(85,1),u=y.getContext("2d",{willReadFrequently:!0});let p=0;for(let C=0;C0?`?${M}`:""}`}const A1="mapbox-tiles";let oy=500,ly=50;const cy=["language","worldview","jobid"];let Np;function mm(){try{return caches}catch{}}function Rf(){const y=mm();y&&Np==null&&(Np=y.open(A1))}let k0=1/0;const du={supported:!1,testSupport:function(y){!Hd&&fm&&(lN?dy(y):Dc=y)}};let Dc,fm,Hd=!1,lN=!1;const cN=typeof self<"u"?self:{};function dy(y){const u=y.createTexture();y.bindTexture(y.TEXTURE_2D,u);try{if(y.texImage2D(y.TEXTURE_2D,0,y.RGBA,y.RGBA,y.UNSIGNED_BYTE,fm),y.isContextLost())return;du.supported=!0}catch{}y.deleteTexture(u),Hd=!0}cN.document&&(fm=cN.document.createElement("img"),fm.onload=function(){Dc&&dy(Dc),Dc=null,lN=!0},fm.onerror=function(){Hd=!0,Dc=null},fm.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const kp={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(kp);class Sp extends Error{constructor(u,p,_){p===401&&Gx(_)&&(u+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(u),this.status=p,this.url=_}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function M1(y){return typeof y=="object"&&y!==null&&"status"in y&&y.status===404}const I1=ci()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,oT=/^\w+:/,Cp=/[\r\n]+/,S0=function(y,u){return(p=y.url).startsWith("file:")||I1().startsWith("file:")&&!oT.test(p)?function(_,C){const M=new XMLHttpRequest;M.open(_.method||"GET",_.url,!0),_.type==="arrayBuffer"&&(M.responseType="arraybuffer");for(const L in _.headers)M.setRequestHeader(L,_.headers[L]);return _.type==="json"&&(M.responseType="text",M.setRequestHeader("Accept","application/json")),M.withCredentials=_.credentials==="include",M.onerror=()=>{C(new Error(M.statusText))},M.onload=()=>{if((M.status>=200&&M.status<300||M.status===0)&&M.response!==null){let L=M.response;if(_.type==="json")try{L=JSON.parse(M.response)}catch(U){return C(U)}const O=new Headers;M.getAllResponseHeaders().trim().split(Cp).forEach(U=>{const W=U.split(": "),J=W.shift(),se=W.join(": ");O.append(J,se)}),C(null,L,O)}else C(new Sp(M.statusText,M.status,_.url))},M.send(_.body),{cancel:()=>M.abort()}}(y,u):function(_,C){const M=new AbortController,L=new Request(_.url,{method:_.method||"GET",body:_.body,credentials:_.credentials,headers:_.headers,referrer:I1(),referrerPolicy:_.referrerPolicy,signal:M.signal});let O=!1,U=!1;const W=(J=L.url).indexOf("sku=")>0&&Gx(J);var J;_.type==="json"&&L.headers.set("Accept","application/json");const se=(fe,xe,we)=>{if(U)return;if(fe&&fe.message!=="SecurityError"&&ra(fe.toString()),xe&&we)return re(xe);const je=Date.now();fetch(L).then(Be=>{if(Be.ok){const Ye=W?Be.clone():null;return re(Be,Ye,je)}return C(new Sp(Be.statusText,Be.status,_.url))}).catch(Be=>{Be.name!=="AbortError"&&C(new Error(`${Be.message} ${_.url}`))})},re=(fe,xe,we)=>{(_.type==="arrayBuffer"?fe.arrayBuffer():_.type==="json"?fe.json():fe.text()).then(je=>{U||(xe&&we&&function(Be,Ye,Ue){if(Rf(),Np==null)return;const tt=za(Ye.headers.get("cache-control")||"");if(tt["no-store"])return;const ot={status:Ye.status,statusText:Ye.statusText,headers:new Headers};Ye.headers.forEach((jt,At)=>ot.headers.set(At,jt)),tt["max-age"]&&ot.headers.set("Expires",new Date(Ue+1e3*tt["max-age"]).toUTCString());const pt=ot.headers.get("expires");if(!pt||new Date(pt).getTime()-Ue<42e4)return;let Rt=oN(Be.url,{persistentParams:cy});if(Ye.status===206){const jt=Be.headers.get("Range");if(!jt)return;ot.status=200,Rt=iN(Rt,{range:jt})}const _t=new Response((Et=Ye.status)!==200&&Et!==404&&[101,103,204,205,304].includes(Et)?null:Ye.body,ot);var Et;Rf(),Np!=null&&Np.then(jt=>jt.put(Rt,_t)).catch(jt=>ra(jt.message))}(L,xe,we),O=!0,C(null,je,fe.headers))}).catch(je=>{U||C(new Error(je.message))})};return W?function(fe,xe){if(Rf(),Np==null)return xe(null);Np.then(we=>{let je=oN(fe.url,{persistentParams:cy});const Be=fe.headers.get("Range");Be&&(je=iN(je,{range:Be})),we.match(je).then(Ye=>{const Ue=function(tt){if(!tt)return!1;const ot=new Date(tt.headers.get("expires")||0),pt=za(tt.headers.get("cache-control")||"");return Number(ot)>Date.now()&&!pt["no-cache"]}(Ye);we.delete(je).catch(xe),Ue&&we.put(je,Ye.clone()).catch(xe),xe(null,Ye,Ue)}).catch(xe)}).catch(xe)}(L,se):se(null,null),{cancel:()=>{U=!0,O||M.abort()}}}(y,u);var p},P1=function(y,u){return S0(Object.assign(y,{type:"json"}),u)},C0=function(y,u){return S0(Object.assign(y,{type:"arrayBuffer"}),u)};function yL(y){const u=document.createElement("a");return u.href=y,u.protocol===location.protocol&&u.host===location.host}let B_,Gd;B_=[],Gd=0;const dN=function(y,u){if(du.supported&&(y.headers||(y.headers={}),y.headers.accept="image/webp,*/*"),Gd>=Va.MAX_PARALLEL_IMAGE_REQUESTS){const M={requestParameters:y,callback:u,cancelled:!1,cancel(){this.cancelled=!0}};return B_.push(M),M}Gd++;let p=!1;const _=()=>{if(!p)for(p=!0,Gd--;B_.length&&Gd{_(),M?u(M):L&&function(U,W){const J=new Blob([new Uint8Array(U)],{type:"image/png"});createImageBitmap(J).then(se=>{W(null,se)}).catch(se=>{W(new Error(`Could not load image because of ${se.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(L,(U,W)=>u(U,W,O))});return{cancel:()=>{C.cancel(),_()}}};var z_,Wx,L1,T0={exports:{}},$_={exports:{}},lT={exports:{}},cT=function(){if(L1)return T0.exports;L1=1;var y=(z_||(z_=1,$_.exports=function(p,_){var C,M,L,O,U,W,J,se;for(M=p.length-(C=3&p.length),L=_,U=3432918353,W=461845907,se=0;se>>16)*U&65535)<<16)&4294967295)<<15|J>>>17))*W+(((J>>>16)*W&65535)<<16)&4294967295)<<13|L>>>19))+((5*(L>>>16)&65535)<<16)&4294967295))+(((O>>>16)+58964&65535)<<16);switch(J=0,C){case 3:J^=(255&p.charCodeAt(se+2))<<16;case 2:J^=(255&p.charCodeAt(se+1))<<8;case 1:L^=J=(65535&(J=(J=(65535&(J^=255&p.charCodeAt(se)))*U+(((J>>>16)*U&65535)<<16)&4294967295)<<15|J>>>17))*W+(((J>>>16)*W&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}),$_.exports),u=(Wx||(Wx=1,lT.exports=function(p,_){for(var C,M=p.length,L=_^M,O=0;M>=4;)C=1540483477*(65535&(C=255&p.charCodeAt(O)|(255&p.charCodeAt(++O))<<8|(255&p.charCodeAt(++O))<<16|(255&p.charCodeAt(++O))<<24))+((1540483477*(C>>>16)&65535)<<16),L=1540483477*(65535&L)+((1540483477*(L>>>16)&65535)<<16)^(C=1540483477*(65535&(C^=C>>>24))+((1540483477*(C>>>16)&65535)<<16)),M-=4,++O;switch(M){case 3:L^=(255&p.charCodeAt(O+2))<<16;case 2:L^=(255&p.charCodeAt(O+1))<<8;case 1:L=1540483477*(65535&(L^=255&p.charCodeAt(O)))+((1540483477*(L>>>16)&65535)<<16)}return L=1540483477*(65535&(L^=L>>>13))+((1540483477*(L>>>16)&65535)<<16),(L^=L>>>15)>>>0}),lT.exports);return T0.exports=y,T0.exports.murmur3=y,T0.exports.murmur2=u,T0.exports}(),It=Xs(cT);class Gs{constructor(u,...p){Object.assign(this,p[0]||{}),this.type=u}}class hr extends Gs{constructor(u,p={}){super("error",Object.assign({error:u},p))}}function gn(y,u,p){p[y]&&p[y].includes(u)||(p[y]=p[y]||[],p[y].push(u))}function _n(y,u,p){if(p&&p[y]){const _=p[y].indexOf(u);_!==-1&&p[y].splice(_,1)}}class Aa{on(u,p){return this._listeners=this._listeners||{},gn(u,p,this._listeners),this}off(u,p){return _n(u,p,this._listeners),_n(u,p,this._oneTimeListeners),this}once(u,p){return p?(this._oneTimeListeners=this._oneTimeListeners||{},gn(u,p,this._oneTimeListeners),this):new Promise(_=>{this.once(u,_)})}fire(u,p){const _=typeof u=="string"?new Gs(u,p):u,C=_.type;if(this.listens(C)){_.target=this;const M=this._listeners&&this._listeners[C]?this._listeners[C].slice():[];for(const U of M)U.call(this,_);const L=this._oneTimeListeners&&this._oneTimeListeners[C]?this._oneTimeListeners[C].slice():[];for(const U of L)_n(C,U,this._oneTimeListeners),U.call(this,_);const O=this._eventedParent;if(O){const U=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(_,U),O.fire(_)}}else _ instanceof hr&&console.error(_.error);return this}listens(u){return!!(this._listeners&&this._listeners[u]&&this._listeners[u].length>0||this._oneTimeListeners&&this._oneTimeListeners[u]&&this._oneTimeListeners[u].length>0||this._eventedParent&&this._eventedParent.listens(u))}setEventedParent(u,p){return this._eventedParent=u,this._eventedParentData=p,this}}class Gn{constructor(u){typeof u=="string"?this.name=u:(this.name=u.name,this.iconsetId=u.iconsetId)}static from(u){return new Gn(u)}static toString(u){return u.iconsetId?`${u.name}${u.iconsetId}`:u.name}static parse(u){const[p,_]=u.split("");return new Gn({name:p,iconsetId:_})}static isEqual(u,p){return u.name===p.name&&u.iconsetId===p.iconsetId}toString(){return Gn.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var yi,Fh={},Tp=function(){if(yi)return Fh;yi=1;var y={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function u(M){return(M=Math.round(M))<0?0:M>255?255:M}function p(M){return u(M[M.length-1]==="%"?parseFloat(M)/100*255:parseInt(M))}function _(M){return(L=M[M.length-1]==="%"?parseFloat(M)/100:parseFloat(M))<0?0:L>1?1:L;var L}function C(M,L,O){return O<0?O+=1:O>1&&(O-=1),6*O<1?M+(L-M)*O*6:2*O<1?L:3*O<2?M+(L-M)*(2/3-O)*6:M}try{Fh.parseCSSColor=function(M){var L,O=M.replace(/ /g,"").toLowerCase();if(O in y)return y[O].slice();if(O[0]==="#")return O.length===4?(L=parseInt(O.substr(1),16))>=0&&L<=4095?[(3840&L)>>4|(3840&L)>>8,240&L|(240&L)>>4,15&L|(15&L)<<4,1]:null:O.length===7&&(L=parseInt(O.substr(1),16))>=0&&L<=16777215?[(16711680&L)>>16,(65280&L)>>8,255&L,1]:null;var U=O.indexOf("("),W=O.indexOf(")");if(U!==-1&&W+1===O.length){var J=O.substr(0,U),se=O.substr(U+1,W-(U+1)).split(","),re=1;switch(J){case"rgba":if(se.length!==4)return null;re=_(se.pop());case"rgb":return se.length!==3?null:[p(se[0]),p(se[1]),p(se[2]),re];case"hsla":if(se.length!==4)return null;re=_(se.pop());case"hsl":if(se.length!==3)return null;var fe=(parseFloat(se[0])%360+360)%360/360,xe=_(se[1]),we=_(se[2]),je=we<=.5?we*(xe+1):we+xe-we*xe,Be=2*we-je;return[u(255*C(Be,je,fe+1/3)),u(255*C(Be,je,fe)),u(255*C(Be,je,fe-1/3)),re];default:return null}}return null}}catch{}return Fh}();function Jr(y,u,p){return y*(1-p)+u*p}class Wa{constructor(u,p,_,C=1){this.r=u,this.g=p,this.b=_,this.a=C}static parse(u){if(!u)return;if(u instanceof Wa)return u;if(typeof u!="string")return;const p=Tp.parseCSSColor(u);return p?new Wa(p[0]/255,p[1]/255,p[2]/255,p[3]):void 0}toString(){const{r:u,g:p,b:_,a:C}=this;return`rgba(${Math.round(255*u)},${Math.round(255*p)},${Math.round(255*_)},${C})`}toNonPremultipliedRenderColor(u){const{r:p,g:_,b:C,a:M}=this;return new $z(u,p,_,C,M)}toPremultipliedRenderColor(u){const{r:p,g:_,b:C,a:M}=this;return new Uz(u,p*M,_*M,C*M,M)}clone(){return new Wa(this.r,this.g,this.b,this.a)}}class U_{constructor(u,p,_,C,M,L=!1){if(this.premultiplied=!1,this.premultiplied=L,u){const O=u.image.height,U=O*O;this.premultiplied?(p=M===0?0:p/M*(O-1),_=M===0?0:_/M*(O-1),C=M===0?0:C/M*(O-1)):(p*=O-1,_*=O-1,C*=O-1),p=Math.max(0,Math.min(O-1,p)),_=Math.max(0,Math.min(O-1,_)),C=Math.max(0,Math.min(O-1,C));const W=Math.floor(p),J=Math.floor(_),se=Math.floor(C),re=Math.ceil(p),fe=Math.ceil(_),xe=Math.ceil(C),we=p-W,je=_-J,Be=C-se,Ye=u.image.data,Ue=4*(W+J*U+se*O),tt=4*(W+J*U+xe*O),ot=4*(W+fe*U+se*O),pt=4*(W+fe*U+xe*O),Rt=4*(re+J*U+se*O),_t=4*(re+J*U+xe*O),Et=4*(re+fe*U+se*O),jt=4*(re+fe*U+xe*O);this.r=Jr(Jr(Jr(Ye[Ue],Ye[tt],Be),Jr(Ye[ot],Ye[pt],Be),je),Jr(Jr(Ye[Rt],Ye[_t],Be),Jr(Ye[Et],Ye[jt],Be),je),we)/255*(this.premultiplied?M:1),this.g=Jr(Jr(Jr(Ye[Ue+1],Ye[tt+1],Be),Jr(Ye[ot+1],Ye[pt+1],Be),je),Jr(Jr(Ye[Rt+1],Ye[_t+1],Be),Jr(Ye[Et+1],Ye[jt+1],Be),je),we)/255*(this.premultiplied?M:1),this.b=Jr(Jr(Jr(Ye[Ue+2],Ye[tt+2],Be),Jr(Ye[ot+2],Ye[pt+2],Be),je),Jr(Jr(Ye[Rt+2],Ye[_t+2],Be),Jr(Ye[Et+2],Ye[jt+2],Be),je),we)/255*(this.premultiplied?M:1),this.a=M}else this.r=p,this.g=_,this.b=C,this.a=M}toArray(){const{r:u,g:p,b:_,a:C}=this;return[255*u,255*p,255*_,C]}toHslaArray(){let{r:u,g:p,b:_,a:C}=this;if(this.premultiplied){if(C===0)return[0,0,0,0];const xe=1/C;u*=xe,p*=xe,_*=xe}const M=Math.min(Math.max(u,0),1),L=Math.min(Math.max(p,0),1),O=Math.min(Math.max(_,0),1),U=Math.min(M,L,O),W=Math.max(M,L,O),J=W-U,se=.5*(U+W);if(J===0)return[0,0,100*se,C];const re=se>.5?J/(2-W-U):J/(W+U);let fe;switch(W){case M:fe=60*((L-O)/J+(LJr(_,u[C],p))}Wa.black=new Wa(0,0,0,1),Wa.white=new Wa(1,1,1,1),Wa.transparent=new Wa(0,0,0,0),Wa.red=new Wa(1,0,0,1),Wa.blue=new Wa(0,0,1,1);var dT=Object.freeze({__proto__:null,array:qz,color:function(y,u,p){return new Wa(Jr(y.r,u.r,p),Jr(y.g,u.g,p),Jr(y.b,u.b,p),Jr(y.a,u.a,p))},number:Jr});class Ep extends Error{constructor(u,p){super(p),this.message=p,this.key=u}}class uT{constructor(u,p=[]){this.parent=u,this.bindings={};for(const[_,C]of p)this.bindings[_]=C}concat(u){return new uT(this,u)}get(u){if(this.bindings[u])return this.bindings[u];if(this.parent)return this.parent.get(u);throw new Error(`${u} not found in scope.`)}has(u){return!!this.bindings[u]||!!this.parent&&this.parent.has(u)}}const E0={kind:"null"},Gr={kind:"number"},_i={kind:"string"},$a={kind:"boolean"},ah={kind:"color"},Kx={kind:"object"},Si={kind:"value"},A0={kind:"collator"},q_={kind:"formatted"},uN={kind:"resolvedImage"};function uu(y,u){return{kind:"array",itemType:y,N:u}}function ea(y){if(y.kind==="array"){const u=ea(y.itemType);return typeof y.N=="number"?`array<${u}, ${y.N}>`:y.itemType.kind==="value"?"array":`array<${u}>`}return y.kind}const Vz=[E0,Gr,_i,$a,ah,q_,Kx,uu(Si),uN];function V_(y,u){if(u.kind==="error")return null;if(y.kind==="array"){if(u.kind==="array"&&(u.N===0&&u.itemType.kind==="value"||!V_(y.itemType,u.itemType))&&(typeof y.N!="number"||y.N===u.N))return null}else{if(y.kind===u.kind)return null;if(y.kind==="value"){for(const p of Vz)if(!V_(p,u))return null}}return`Expected ${ea(y)} but found ${ea(u)} instead.`}function vL(y,u){return u.some(p=>p.kind===y.kind)}function hN(y,u){return u.some(p=>p==="null"?y===null:p==="array"?Array.isArray(y):p==="object"?y&&!Array.isArray(y)&&typeof y=="object":p===typeof y)}function D1(y,u){return y.kind==="array"&&u.kind==="array"?y.N===u.N&&D1(y.itemType,u.itemType):y.kind===u.kind}class H_{constructor(u,p,_){this.sensitivity=u?p?"variant":"case":p?"accent":"base",this.locale=_,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(u,p){return this.collator.compare(u,p)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class R1{constructor(u,p,_,C,M){this.text=u.normalize?u.normalize():u,this.image=p,this.scale=_,this.fontStack=C,this.textColor=M}}class hu{constructor(u){this.sections=u}static fromString(u){return new hu([new R1(u,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(u=>u.text.length!==0||!!u.image&&u.image.hasPrimary())}static factory(u){return u instanceof hu?u:hu.fromString(u)}toString(){return this.sections.length===0?"":this.sections.map(u=>u.text).join("")}serialize(){const u=["format"];for(const p of this.sections){if(p.image){const C=p.image.getPrimary().id.toString();u.push(["image",C]);continue}u.push(p.text);const _={};p.fontStack&&(_["text-font"]=["literal",p.fontStack.split(",")]),p.scale&&(_["font-scale"]=p.scale),p.textColor&&(_["text-color"]=["rgba"].concat(p.textColor.toNonPremultipliedRenderColor(null).toArray())),u.push(_)}return u}}class Of{constructor(u,p={}){this.id=Gn.from(u),this.params=p.params,this.sx=p.sx||1,this.sy=p.sy||1}toString(){return JSON.stringify(this)}static parse(u){let p,_,C,M;try{({id:p,params:_,sx:C,sy:M}=JSON.parse(u)||{})}catch{return null}return p?new Of(p,{params:_,sx:C,sy:M}):null}scaleSelf(u,p=u){return this.sx*=u,this.sy*=p,this}}class Au{constructor(u,p,_,C,M=!1){this.primaryId=Gn.from(u),this.primaryOptions=p,_&&(this.secondaryId=Gn.from(_)),this.secondaryOptions=C,this.available=M}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Of(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Of(this.secondaryId,this.secondaryOptions):null}static from(u){return typeof u=="string"?Au.build({name:u}):u}static build(u,p,_,C){return!u||typeof u=="object"&&!("name"in u)?null:new Au(u,_,p,C)}}function Hz(y,u,p,_){return typeof y=="number"&&y>=0&&y<=255&&typeof u=="number"&&u>=0&&u<=255&&typeof p=="number"&&p>=0&&p<=255?_===void 0||typeof _=="number"&&_>=0&&_<=1?null:`Invalid rgba value [${[y,u,p,_].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof _=="number"?[y,u,p,_]:[y,u,p]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function G_(y){if(y===null||typeof y=="string"||typeof y=="boolean"||typeof y=="number"||y instanceof Wa||y instanceof H_||y instanceof hu||y instanceof Au)return!0;if(Array.isArray(y)){for(const u of y)if(!G_(u))return!1;return!0}if(typeof y=="object"){for(const u in y)if(!G_(y[u]))return!1;return!0}return!1}function Rl(y){if(y===null)return E0;if(typeof y=="string")return _i;if(typeof y=="boolean")return $a;if(typeof y=="number")return Gr;if(y instanceof Wa)return ah;if(y instanceof H_)return A0;if(y instanceof hu)return q_;if(y instanceof Au)return uN;if(Array.isArray(y)){const u=y.length;let p;for(const _ of y){const C=Rl(_);if(p){if(p===C)continue;p=Si;break}p=C}return uu(p||Si,u)}return Kx}function Ff(y){const u=typeof y;return y===null?"":u==="string"||u==="number"||u==="boolean"?String(y):y instanceof hu||y instanceof Au||y instanceof Wa?y.toString():JSON.stringify(y)}class Ap{constructor(u,p){this.type=u,this.value=p}static parse(u,p){if(u.length!==2)return p.error(`'literal' expression requires exactly one argument, but found ${u.length-1} instead.`);if(!G_(u[1]))return p.error("invalid value");const _=u[1];let C=Rl(_);const M=p.expectedType;return C.kind!=="array"||C.N!==0||!M||M.kind!=="array"||typeof M.N=="number"&&M.N!==0||(C=M),new Ap(C,_)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Wa?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof hu?this.value.serialize():this.value}}class No{constructor(u){this.name="ExpressionEvaluationError",this.message=u}toJSON(){return this.message}}const hT={string:_i,number:Gr,boolean:$a,object:Kx};class Mp{constructor(u,p){this.type=u,this.args=p}static parse(u,p){if(u.length<2)return p.error("Expected at least one argument.");let _,C=1;const M=u[0];if(M==="array"){let O,U;if(u.length>2){const W=u[1];if(typeof W!="string"||!(W in hT)||W==="object")return p.error('The item type argument of "array" must be one of string, number, boolean',1);O=hT[W],C++}else O=Si;if(u.length>3){if(u[2]!==null&&(typeof u[2]!="number"||u[2]<0||u[2]!==Math.floor(u[2])))return p.error('The length argument to "array" must be a positive integer literal',2);U=u[2],C++}_=uu(O,U)}else _=hT[M];const L=[];for(;Cu.outputDefined())}serialize(){const u=this.type,p=[u.kind];if(u.kind==="array"){const _=u.itemType;if(_.kind==="string"||_.kind==="number"||_.kind==="boolean"){p.push(_.kind);const C=u.N;(typeof C=="number"||this.args.length>1)&&p.push(C)}}return p.concat(this.args.map(_=>_.serialize()))}}class W_{constructor(u){this.type=q_,this.sections=u}static parse(u,p){if(u.length<2)return p.error("Expected at least one argument.");const _=u[1];if(!Array.isArray(_)&&typeof _=="object")return p.error("First argument must be an image or text section.");const C=[];let M=!1;for(let L=1;L<=u.length-1;++L){const O=u[L];if(M&&typeof O=="object"&&!Array.isArray(O)){M=!1;let U=null;if(O["font-scale"]&&(U=p.parseObjectValue(O["font-scale"],L,"font-scale",Gr),!U))return null;let W=null;if(O["text-font"]&&(W=p.parseObjectValue(O["text-font"],L,"text-font",uu(_i)),!W))return null;let J=null;if(O["text-color"]&&(J=p.parseObjectValue(O["text-color"],L,"text-color",ah),!J))return null;const se=C.at(-1);se.scale=U,se.font=W,se.textColor=J}else{const U=p.parse(u[L],L,Si);if(!U)return null;const W=U.type.kind;if(W!=="string"&&W!=="value"&&W!=="null"&&W!=="resolvedImage")return p.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");M=!0,C.push({content:U,scale:null,font:null,textColor:null})}}return new W_(C)}evaluate(u){return new hu(this.sections.map(p=>{const _=p.content.evaluate(u);return D1(Rl(_),uN)?new R1("",_,null,null,null):new R1(Ff(_),null,p.scale?p.scale.evaluate(u):null,p.font?p.font.evaluate(u).join(","):null,p.textColor?p.textColor.evaluate(u):null)}))}eachChild(u){for(const p of this.sections)u(p.content),p.scale&&u(p.scale),p.font&&u(p.font),p.textColor&&u(p.textColor)}outputDefined(){return!1}serialize(){const u=["format"];for(const p of this.sections){u.push(p.content.serialize());const _={};p.scale&&(_["font-scale"]=p.scale.serialize()),p.font&&(_["text-font"]=p.font.serialize()),p.textColor&&(_["text-color"]=p.textColor.serialize()),u.push(_)}return u}}class mN{constructor(u,p,_,C){this._imageWarnHistory={},this.type=uN,this.namePrimary=u,this.nameSecondary=p,_&&(this.paramsPrimary=_.params,this.iconsetIdPrimary=_.iconset?_.iconset.id:void 0),C&&(this.paramsSecondary=C.params,this.iconsetIdSecondary=C.iconset?C.iconset.id:void 0)}static parse(u,p){if(u.length<2)return p.error("Expected two or more arguments.");let _=1;const C=[];function M(){if(_Gn.isEqual(L,M)),C.available){const L=C.getSecondary()?C.getSecondary().id:null;L&&(C.available=u.availableImages.some(O=>Gn.isEqual(O,L)))}}return C}eachChild(u){if(u(this.namePrimary),this.paramsPrimary)for(const p in this.paramsPrimary)this.paramsPrimary[p]&&u(this.paramsPrimary[p]);if(this.nameSecondary&&(u(this.nameSecondary),this.paramsSecondary))for(const p in this.paramsSecondary)this.paramsSecondary[p]&&u(this.paramsSecondary[p])}outputDefined(){return!1}serializeOptions(u,p){const _={};if(p&&(_.iconset={id:p}),u){_.params={};for(const C in u)u[C]&&(_.params[C]=u[C].serialize())}return Object.keys(_).length>0?_:void 0}serialize(){const u=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const p=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);p&&u.push(p)}if(this.nameSecondary&&(u.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const p=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);p&&u.push(p)}return u}}function mT(y){return _L(y)?"string":fN(y)?"number":pN(y)?"boolean":Array.isArray(y)?"array":y===null?"null":bL(y)?"object":typeof y}function bL(y){return y!=null&&!Array.isArray(y)&&typeof y!="function"&&!(y instanceof String||y instanceof Number||y instanceof Boolean)&&typeof y=="object"}function _L(y){return typeof y=="string"||y instanceof String}function fN(y){return typeof y=="number"||y instanceof Number}function pN(y){return typeof y=="boolean"||y instanceof Boolean}const K_={"to-boolean":$a,"to-color":ah,"to-number":Gr,"to-string":_i};class Yx{constructor(u,p){this.type=u,this.args=p}static parse(u,p){if(u.length<2)return p.error("Expected at least one argument.");const _=u[0],C=[];let M=E0;if(_==="to-array"){if(!Array.isArray(u[1]))return null;const L=u[1].length;if(p.expectedType){if(p.expectedType.kind!=="array")return p.error(`Expected ${p.expectedType.kind} but found array.`);M=uu(p.expectedType.itemType,L)}else{if(!(L>0&&G_(u[1][0])))return null;M=uu(Rl(u[1][0]),L)}for(let O=0;O4?`Invalid rbga value ${JSON.stringify(p)}: expected an array containing either three or four numeric values.`:Hz(p[0],p[1],p[2],p[3]),!_))return new Wa(p[0]/255,p[1]/255,p[2]/255,p[3])}throw new No(_||`Could not parse color from value '${typeof p=="string"?p:String(JSON.stringify(p))}'`)}if(this.type.kind==="number"){let p=null;for(const _ of this.args){if(p=_.evaluate(u),p===null)return 0;const C=Number(p);if(!isNaN(C))return C}throw new No(`Could not convert ${JSON.stringify(p)} to number.`)}return this.type.kind==="formatted"?hu.fromString(Ff(this.args[0].evaluate(u))):this.type.kind==="resolvedImage"?Au.build(Ff(this.args[0].evaluate(u))):this.type.kind==="array"?this.args.map(p=>p.evaluate(u)):Ff(this.args[0].evaluate(u))}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){if(this.type.kind==="formatted")return new W_([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new mN(this.args[0]).serialize();const u=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(p=>{u.push(p.serialize())}),u}}const Zx=["Unknown","Point","LineString","Polygon"];class wL{constructor(u,p,_){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=u,this.options=p,this.iconImageUseTheme=_}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Zx[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(u){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const u=this.featureDistanceData.center,p=this.featureDistanceData.scale,{x:_,y:C}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(_*p-u[0])+this.featureDistanceData.bearing[1]*(C*p-u[1])}return 0}parseColor(u){let p=this._parseColorCache[u];return p||(p=this._parseColorCache[u]=Wa.parse(u)),p}getConfig(u){return this.options?this.options.get(u):null}}class ih{constructor(u,p,_,C,M){this.name=u,this.type=p,this._evaluate=_,this.args=C,this._overloadIndex=M}evaluate(u){if(!this._evaluate){const p=ih.definitions[this.name];this._evaluate=Array.isArray(p)?p[2]:p.overloads[this._overloadIndex][1]}return this._evaluate(u,this.args)}eachChild(u){this.args.forEach(u)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(u=>u.serialize()))}static parse(u,p){const _=u[0],C=ih.definitions[_];if(!C)return p.error(`Unknown expression "${_}". If you wanted a literal array, use ["literal", [...]].`,0);const M=Array.isArray(C)?C[0]:C.type,L=Array.isArray(C)?[[C[1],C[2]]]:C.overloads,O=[];let U=null,W=-1;for(const[J,se]of L){if(Array.isArray(J)&&J.length!==u.length-1)continue;O.push(J),W++,U===null?U=new pm(p.registry,p.path,null,p.scope,[],p._scope,p.options,p.iconImageUseTheme):U.errors.length=0;const re=[];let fe=!1;for(let xe=1;xere)).map(xN).join(" | "),se=[];for(let re=1;rep;){if(_-p>600){const U=_-p+1,W=u-p+1,J=Math.log(U),se=.5*Math.exp(2*J/3),re=.5*Math.sqrt(J*se*(U-se)/U)*(W-U/2<0?-1:1);Gz(y,u,Math.max(p,Math.floor(u-W*se/U+re)),Math.min(_,Math.floor(u+(U-W)*se/U+re)),C)}const M=y[u];let L=p,O=_;for(gN(y,p,u),C(y[_],M)>0&&gN(y,p,_);L0;)O--}C(y[p],M)===0?gN(y,p,O):(O++,gN(y,O,_)),O<=u&&(p=O+1),u<=O&&(_=O-1)}}function gN(y,u,p){const _=y[u];y[u]=y[p],y[p]=_}function uye(y,u){return yu?1:0}function Wz(y){let u=0;for(let p,_,C=0,M=y.length,L=M-1;C=u[2]||y[1]<=u[1]||y[3]>=u[3])}function fT(y,u,p){const _=y[0]-u[0],C=y[1]-u[1],M=y[0]-p[0],L=y[1]-p[1];return _*L-M*C===0&&_*M<=0&&C*L<=0}function hye(y,u,p){return u[1]>y[1]!=p[1]>y[1]&&y[0]<(p[0]-u[0])*(y[1]-u[1])/(p[1]-u[1])+u[0]}function Y_(y,u,p=!1){let _=!1;for(let C=0,M=u.length;C0&&O<0||L<0&&O>0}function pT(y,u,p,_){return(C=[_[0]-p[0],_[1]-p[1]])[0]*(M=[u[0]-y[0],u[1]-y[1]])[1]-C[1]*M[0]!==0&&!(!Kz(y,u,p,_)||!Kz(p,_,y,u));var C,M}function jL(y){const u=new us(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),p=new us(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const _ of y[0])u.x>_.x&&(u.x=_.x),u.y>_.y&&(u.y=_.y),p.x<_.x&&(p.x=_.x),p.y<_.y&&(p.y=_.y);return{min:u,max:p}}const M0=8192;function mye(y,u){const p=(180+y[0])/360,_=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+y[1]*Math.PI/360)))/360,C=Math.pow(2,u.z);return[Math.round(p*C*M0),Math.round(_*C*M0)]}function Yz(y,u){for(let p=0;pp[2]){const C=.5*_;let M=y[0]-p[0]>C?-_:p[0]-y[0]>C?_:0;M===0&&(M=y[0]-p[2]>C?-_:p[2]-y[0]>C?_:0),y[0]+=M}F1(u,y)}function e7(y,u,p,_){const C=Math.pow(2,_.z)*M0,M=[_.x*M0,_.y*M0],L=[];if(!y)return L;for(const O of y)for(const U of O){const W=[U.x+M[0],U.y+M[1]];Jz(W,u,p,C),L.push(W)}return L}function t7(y,u,p,_){const C=Math.pow(2,_.z)*M0,M=[_.x*M0,_.y*M0],L=[];if(!y)return L;for(const U of y){const W=[];for(const J of U){const se=[J.x+M[0],J.y+M[1]];F1(u,se),W.push(se)}L.push(W)}if(u[2]-u[0]<=C/2){(O=u)[0]=O[1]=1/0,O[2]=O[3]=-1/0;for(const U of L)for(const W of U)Jz(W,u,p,C)}var O;return L}class Xx{constructor(u,p){this.type=$a,this.geojson=u,this.geometries=p}static parse(u,p){if(u.length!==2)return p.error(`'within' expression requires exactly one argument, but found ${u.length-1} instead.`);if(G_(u[1])){const _=u[1];if(_.type==="FeatureCollection")for(let C=0;C<_.features.length;++C){const M=_.features[C].geometry.type;if(M==="Polygon"||M==="MultiPolygon")return new Xx(_,_.features[C].geometry)}else if(_.type==="Feature"){const C=_.geometry.type;if(C==="Polygon"||C==="MultiPolygon")return new Xx(_,_.geometry)}else if(_.type==="Polygon"||_.type==="MultiPolygon")return new Xx(_,_)}return p.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(u){if(u.geometry()!=null&&u.canonicalID()!=null){if(u.geometryType()==="Point")return function(p,_){const C=[1/0,1/0,-1/0,-1/0],M=[1/0,1/0,-1/0,-1/0],L=p.canonicalID();if(!L)return!1;if(_.type==="Polygon"){const O=vN(_.coordinates,M,L),U=e7(p.geometry(),C,M,L);if(!yN(C,M))return!1;for(const W of U)if(!Y_(W,O))return!1}if(_.type==="MultiPolygon"){const O=Qz(_.coordinates,M,L),U=e7(p.geometry(),C,M,L);if(!yN(C,M))return!1;for(const W of U)if(!Yz(W,O))return!1}return!0}(u,this.geometries);if(u.geometryType()==="LineString")return function(p,_){const C=[1/0,1/0,-1/0,-1/0],M=[1/0,1/0,-1/0,-1/0],L=p.canonicalID();if(!L)return!1;if(_.type==="Polygon"){const O=vN(_.coordinates,M,L),U=t7(p.geometry(),C,M,L);if(!yN(C,M))return!1;for(const W of U)if(!Zz(W,O))return!1}if(_.type==="MultiPolygon"){const O=Qz(_.coordinates,M,L),U=t7(p.geometry(),C,M,L);if(!yN(C,M))return!1;for(const W of U)if(!Xz(W,O))return!1}return!0}(u,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}serialize(){return["within",this.geojson]}}const Qx={kilometers:1,miles:1e3/1609.344,nauticalmiles:1e3/1852,meters:1e3,metres:1e3,yards:1e3/.9144,feet:1e3/.3048,inches:1e3/.0254},En=1/298.257223563,Br=En*(2-En),B1=Math.PI/180;class kn{static fromTile(u,p,_){const C=Math.PI*(1-2*(u+.5)/Math.pow(2,p)),M=Math.atan(.5*(Math.exp(C)-Math.exp(-C)))/B1;return new kn(M,_)}static get units(){return Qx}constructor(u,p){if(u===void 0)throw new Error("No latitude given.");if(p&&!Qx[p])throw new Error(`Unknown unit ${p}. Use one of: ${Object.keys(Qx).join(", ")}`);const _=6378.137*B1*(p?Qx[p]:1),C=Math.cos(u*B1),M=1/(1-Br*(1-C*C)),L=Math.sqrt(M);this.kx=_*L*C,this.ky=_*L*M*(1-Br)}distance(u,p){const _=en(u[0]-p[0])*this.kx,C=(u[1]-p[1])*this.ky;return Math.sqrt(_*_+C*C)}bearing(u,p){const _=en(p[0]-u[0])*this.kx;return Math.atan2(_,(p[1]-u[1])*this.ky)/B1}destination(u,p,_){const C=_*B1;return this.offset(u,Math.sin(C)*p,Math.cos(C)*p)}offset(u,p,_){return[u[0]+p/this.kx,u[1]+_/this.ky]}lineDistance(u){let p=0;for(let _=0;_p)return bN(M,L,(p-(_-O))/O)}return u[u.length-1]}pointToSegmentDistance(u,p,_){let[C,M]=p,L=en(_[0]-C)*this.kx,O=(_[1]-M)*this.ky;if(L!==0||O!==0){const U=(en(u[0]-C)*this.kx*L+(u[1]-M)*this.ky*O)/(L*L+O*O);U>1?(C=_[0],M=_[1]):U>0&&(C+=L/this.kx*U,M+=O/this.ky*U)}return L=en(u[0]-C)*this.kx,O=(u[1]-M)*this.ky,Math.sqrt(L*L+O*O)}pointOnLine(u,p){let _=1/0,C=u[0][0],M=u[0][1],L=0,O=0;for(let U=0;U1?(W=u[U+1][0],J=u[U+1][1]):fe>0&&(W+=se/this.kx*fe,J+=re/this.ky*fe)),se=en(p[0]-W)*this.kx,re=(p[1]-J)*this.ky;const xe=se*se+re*re;xe<_&&(_=xe,C=W,M=J,L=U,O=fe)}return{point:[C,M],index:L,t:Math.max(0,Math.min(1,O))}}lineSlice(u,p,_){let C=this.pointOnLine(_,u),M=this.pointOnLine(_,p);if(C.index>M.index||C.index===M.index&&C.t>M.t){const W=C;C=M,M=W}const L=[C.point],O=C.index+1,U=M.index;!xT(_[O],L[0])&&O<=U&&L.push(_[O]);for(let W=O+1;W<=U;W++)L.push(_[W]);return xT(_[U],M.point)||L.push(M.point),L}lineSliceAlong(u,p,_){let C=0;const M=[];for(let L=0;L<_.length-1;L++){const O=_[L],U=_[L+1],W=this.distance(O,U);if(C+=W,C>u&&M.length===0&&M.push(bN(O,U,(u-(C-W))/W)),C>=p)return M.push(bN(O,U,(p-(C-W))/W)),M;C>u&&M.push(U)}return M}bufferPoint(u,p){const _=p/this.ky,C=p/this.kx;return[u[0]-C,u[1]-_,u[0]+C,u[1]+_]}bufferBBox(u,p){const _=p/this.ky,C=p/this.kx;return[u[0]-C,u[1]-_,u[2]+C,u[3]+_]}insideBBox(u,p){return en(u[0]-p[0])>=0&&en(u[0]-p[2])<=0&&u[1]>=p[1]&&u[1]<=p[3]}}function xT(y,u){return y[0]===u[0]&&y[1]===u[1]}function bN(y,u,p){const _=en(u[0]-y[0]);return[y[0]+_*p,y[1]+(u[1]-y[1])*p]}function en(y){for(;y<-180;)y+=360;for(;y>180;)y-=360;return y}class _N{constructor(u=[],p=(_,C)=>_C?1:0){if(this.data=u,this.length=this.data.length,this.compare=p,this.length>0)for(let _=(this.length>>1)-1;_>=0;_--)this._down(_)}push(u){this.data.push(u),this._up(this.length++)}pop(){if(this.length===0)return;const u=this.data[0],p=this.data.pop();return--this.length>0&&(this.data[0]=p,this._down(0)),u}peek(){return this.data[0]}_up(u){const{data:p,compare:_}=this,C=p[u];for(;u>0;){const M=u-1>>1,L=p[M];if(_(C,L)>=0)break;p[u]=L,u=M}p[u]=C}_down(u){const{data:p,compare:_}=this,C=this.length>>1,M=p[u];for(;u=0)break;p[u]=p[L],u=L}p[u]=M}}var mr=8192;function NL(y,u){return u.dist-y.dist}function kL(y){const u=[1/0,1/0,-1/0,-1/0];if(u.length!==y.length)return!1;for(let p=0;p=y[0]&&y[1]y[1])return[null,null];const p=z1(y);if(u){if(p===2)return[y,null];const _=Math.floor(p/2);return[[y[0],y[0]+_],[y[0]+_,y[1]]]}{if(p===1)return[y,null];const _=Math.floor(p/2)-1;return[[y[0],y[0]+_],[y[0]+_+1,y[1]]]}}function Km(y,u){const p=[1/0,1/0,-1/0,-1/0];if(!uy(u,y.length))return p;for(let _=u[0];_<=u[1];++_)F1(p,y[_]);return p}function X_(y){const u=[1/0,1/0,-1/0,-1/0];for(let p=0;pu[2]&&(_=y[0]-u[2]),y[1]>u[3]&&(C=y[1]-u[3]),y[3]=_)return _;if(yN(C,M)){if(a7(y,u))return 0}else if(a7(u,y))return 0;let L=_;for(const O of y)for(let U=0,W=O.length,J=W-1;U=M)continue;const J=W.range1;if(z1(J)<=O){if(!uy(J,y.length))return NaN;if(u){const se=gye(y,J,p,_);if((M=Math.min(M,se))===0)return M}else for(let se=J[0];se<=J[1];++se){const re=xye(y[se],p,_);if((M=Math.min(M,re))===0)return M}}else{const se=wN(J,u);if(se[0]!==null){const re=Ym(Km(y,se[0]),U,_);re=L)continue;const se=J.range1,re=J.range2;if(z1(se)<=U&&z1(re)<=W){if(!uy(se,y.length)||!uy(re,p.length))return NaN;if(u&&_?L=Math.min(L,$1(y,se,p,re,C)):u||_?u&&!_?L=Math.min(L,jN(p,re,y,se,C)):!u&&_&&(L=Math.min(L,jN(y,se,p,re,C))):L=Math.min(L,pye(y,se,p,re,C)),L===0)return L}else{const fe=wN(se,u),xe=wN(re,_);vT(O,L,C,y,p,fe[0],xe[0]),vT(O,L,C,y,p,fe[0],xe[1]),vT(O,L,C,y,p,fe[1],xe[0]),vT(O,L,C,y,p,fe[1],xe[1])}}return L}function TL(y,u,p,_,C=1/0){let M=C;const L=Km(y,[0,y.length-1]);for(const O of p)if(!(M!==1/0&&Ym(L,Km(O,[0,O.length-1]),_)>=M)&&(M=Math.min(M,i7(y,u,O,!0,_,M)),M===0))return M;return M}function NN(y,u,p,_,C=1/0){let M=C;const L=Km(y,[0,y.length-1]);for(const O of p){if(M!==1/0&&Ym(L,X_(O),_)>=M)continue;const U=CL(y,u,O,_,M);if(isNaN(U))return U;if((M=Math.min(M,U))===0)return M}return M}function EL(y){return y==="Point"||y==="MultiPoint"||y==="LineString"||y==="MultiLineString"||y==="Polygon"||y==="MultiPolygon"}class U1{constructor(u,p){this.type=Gr,this.geojson=u,this.geometries=p}static parse(u,p){if(u.length!==2)return p.error(`'distance' expression requires either one argument, but found ' ${u.length-1} instead.`);if(G_(u[1])){const _=u[1];if(_.type==="FeatureCollection"){for(let C=0;C<_.features.length;++C)if(EL(_.features[C].geometry.type))return new U1(_,_.features[C].geometry)}else if(_.type==="Feature"){if(EL(_.geometry.type))return new U1(_,_.geometry)}else if(EL(_.type))return new U1(_,_)}return p.error("'distance' expression needs to be an array with format ['Distance', GeoJSONObj].")}evaluate(u){const p=u.geometry(),_=u.canonicalID();if(p!=null&&_!=null){if(u.geometryType()==="Point")return function(C,M,L){const O=[];for(const W of C)for(const J of W)O.push(gT(J,M));const U=new kn(O[0][1],"meters");return L.type==="Point"||L.type==="MultiPoint"||L.type==="LineString"?i7(O,!1,L.type==="Point"?[L.coordinates]:L.coordinates,L.type==="LineString",U):L.type==="MultiLineString"?TL(O,!1,L.coordinates,U):L.type==="Polygon"||L.type==="MultiPolygon"?NN(O,!1,L.type==="Polygon"?[L.coordinates]:L.coordinates,U):null}(p,_,this.geometries);if(u.geometryType()==="LineString")return function(C,M,L){const O=[];for(const W of C){const J=[];for(const se of W)J.push(gT(se,M));O.push(J)}const U=new kn(O[0][0][1],"meters");if(L.type==="Point"||L.type==="MultiPoint"||L.type==="LineString")return TL(L.type==="Point"?[L.coordinates]:L.coordinates,L.type==="LineString",O,U);if(L.type==="MultiLineString"){let W=1/0;for(let J=0;J{u&&!q1(p)&&(u=!1)}),u}function Bf(y){if(y instanceof ih&&y.name==="feature-state")return!1;let u=!0;return y.eachChild(p=>{u&&!Bf(p)&&(u=!1)}),u}function Jx(y,u){if(y instanceof ih&&u.includes(y.name))return!1;let p=!0;return y.eachChild(_=>{p&&!Jx(_,u)&&(p=!1)}),p}function o7(y,u,p){return[y,u,p].filter(Boolean).join("")}function kN(y,u){switch(y){case"string":return Ff(u);case"number":return+u;case"boolean":return!!u;case"color":return Wa.parse(u);case"formatted":return hu.fromString(Ff(u));case"resolvedImage":return Au.build(Ff(u))}return u}function l7(y,u,p,_){return _!==void 0&&(y=_*Math.round(y/_)),u!==void 0&&yp&&(y=p),y}class V1{constructor(u,p,_,C=!1){this.type=u,this.key=p,this.scope=_,this.featureConstant=C}static parse(u,p){let _=p.expectedType;if(_==null&&(_=Si),u.length<2||u.length>3)return p.error("Invalid number of arguments for 'config' expression.");const C=p.parse(u[1],1);if(!(C instanceof Ap))return p.error("Key name of 'config' expression must be a string literal.");let M,L=!0;const O=Ff(C.value);if(u.length>=3){const U=p.parse(u[2],2);if(!(U instanceof Ap))return p.error("Scope of 'config' expression must be a string literal.");M=Ff(U.value)}if(p.options){const U=o7(O,M,p._scope),W=p.options.get(U);W&&(L=q1(W.value||W.default))}return new V1(_,O,M,L)}evaluate(u){const p=o7(this.key,this.scope,u.scope),_=u.getConfig(p);if(!_)return null;const{type:C,value:M,values:L,minValue:O,maxValue:U,stepValue:W}=_,J=_.default.evaluate(u);let se=J;if(M){const re=u.scope;u.scope=(re||"").split("").slice(1).join(""),se=M.evaluate(u),u.scope=re}return C&&(se=kN(C,se)),se===void 0||O===void 0&&U===void 0&&W===void 0||(typeof se=="number"?se=l7(se,O,U,W):Array.isArray(se)&&(se=se.map(re=>typeof re=="number"?l7(re,O,U,W):re))),M!==void 0&&se!==void 0&&L&&!L.includes(se)&&(se=J,C&&(se=kN(C,se))),(C&&C!==this.type||se!==void 0&&!D1(Rl(se),this.type))&&(se=kN(this.type.kind,se)),se}eachChild(){}outputDefined(){return!1}serialize(){const u=["config",this.key];return this.scope&&u.concat(this.scope),u}}class SN{constructor(u,p){this.type=p.type,this.name=u,this.boundExpression=p}static parse(u,p){if(u.length!==2||typeof u[1]!="string")return p.error("'var' expression requires exactly one string literal argument.");const _=u[1];return p.scope.has(_)?new SN(_,p.scope.get(_)):p.error(`Unknown variable "${_}". Make sure "${_}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(u){return this.boundExpression.evaluate(u)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class pm{constructor(u,p=[],_,C=new uT,M=[],L,O,U){this.registry=u,this.path=p,this.scope=C,this.errors=M,this.expectedType=_,this._scope=L,this.options=O,this.iconImageUseTheme=U}get key(){if(this._key===void 0){const u=this.path;let p="";for(let _=0;_`[${C}]`).join("")}`;this.errors.push(new Ep(_,u))}checkSubtype(u,p,_){const C=V_(u,p);return C&&this.error(C,...typeof _=="number"?[_]:[]),C}}function CN(y){if(y instanceof SN)return CN(y.boundExpression);if(y instanceof ih&&y.name==="error"||y instanceof O1||y instanceof Xx||y instanceof U1||y instanceof V1)return!1;const u=y instanceof Yx||y instanceof Mp;let p=!0;return y.eachChild(_=>{p=u?p&&CN(_):p&&_ instanceof Ap}),!!p&&q1(y)&&Jx(y,["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 TN(y,u){const p=y.length-1;let _,C,M=0,L=p,O=0;for(;M<=L;)if(O=Math.floor((M+L)/2),_=y[O],C=y[O+1],_<=u){if(O===p||uu))throw new No("Input is not a number.");L=O-1}return 0}class Q_{constructor(u,p,_){this.type=u,this.input=p,this.labels=[],this.outputs=[];for(const[C,M]of _)this.labels.push(C),this.outputs.push(M)}static parse(u,p){if(u.length-1<4)return p.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if((u.length-1)%2!=0)return p.error("Expected an even number of arguments.");const _=p.parse(u[1],1,Gr);if(!_)return null;const C=[];let M=null;p.expectedType&&p.expectedType.kind!=="value"&&(M=p.expectedType);for(let L=1;L=O)return p.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',W);const se=p.parse(U,J,M);if(!se)return null;M=M||se.type,C.push([O,se])}return new Q_(M,_,C)}evaluate(u){const p=this.labels,_=this.outputs;if(p.length===1)return _[0].evaluate(u);const C=this.input.evaluate(u);if(C<=p[0])return _[0].evaluate(u);const M=p.length;return C>=p[M-1]?_[M-1].evaluate(u):_[TN(p,C)].evaluate(u)}eachChild(u){u(this.input);for(const p of this.outputs)u(p)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){const u=["step",this.input.serialize()];for(let p=0;p0&&u.push(this.labels[p]),u.push(this.outputs[p].serialize());return u}}const AL=.95047,ML=1.08883,IL=4/29,H1=6/29,bT=3*H1*H1,c7=H1*H1*H1,d7=Math.PI/180,u7=180/Math.PI;function _T(y){return y>c7?Math.pow(y,1/3):y/bT+IL}function wT(y){return y>H1?y*y*y:bT*(y-IL)}function PL(y){return 255*(y<=.0031308?12.92*y:1.055*Math.pow(y,1/2.4)-.055)}function LL(y){return(y/=255)<=.04045?y/12.92:Math.pow((y+.055)/1.055,2.4)}function EN(y){const u=LL(y.r),p=LL(y.g),_=LL(y.b),C=_T((.4124564*u+.3575761*p+.1804375*_)/AL),M=_T((.2126729*u+.7151522*p+.072175*_)/1);return{l:116*M-16,a:500*(C-M),b:200*(M-_T((.0193339*u+.119192*p+.9503041*_)/ML)),alpha:y.a}}function J_(y){let u=(y.l+16)/116,p=isNaN(y.a)?u:u+y.a/500,_=isNaN(y.b)?u:u-y.b/200;return u=1*wT(u),p=AL*wT(p),_=ML*wT(_),new Wa(PL(3.2404542*p-1.5371385*u-.4985314*_),PL(-.969266*p+1.8760108*u+.041556*_),PL(.0556434*p-.2040259*u+1.0572252*_),y.alpha)}function jT(y,u,p){const _=u-y;return y+p*(_>180||_<-180?_-360*Math.round(_/360):_)}const ew={forward:EN,reverse:J_,interpolate:function(y,u,p){return{l:Jr(y.l,u.l,p),a:Jr(y.a,u.a,p),b:Jr(y.b,u.b,p),alpha:Jr(y.alpha,u.alpha,p)}}},tw={forward:function(y){const{l:u,a:p,b:_}=EN(y),C=Math.atan2(_,p)*u7;return{h:C<0?C+360:C,c:Math.sqrt(p*p+_*_),l:u,alpha:y.a}},reverse:function(y){const u=y.h*d7,p=y.c;return J_({l:y.l,a:Math.cos(u)*p,b:Math.sin(u)*p,alpha:y.alpha})},interpolate:function(y,u,p){return{h:jT(y.h,u.h,p),c:Jr(y.c,u.c,p),l:Jr(y.l,u.l,p),alpha:Jr(y.alpha,u.alpha,p)}}};var DL=Object.freeze({__proto__:null,hcl:tw,lab:ew});class xm{constructor(u,p,_,C,M){this.type=u,this.operator=p,this.interpolation=_,this.input=C,this.labels=[],this.outputs=[];for(const[L,O]of M)this.labels.push(L),this.outputs.push(O)}static interpolationFactor(u,p,_,C){let M=0;if(u.name==="exponential")M=RL(p,u.base,_,C);else if(u.name==="linear")M=RL(p,1,_,C);else if(u.name==="cubic-bezier"){const L=u.controlPoints;M=new xn(L[0],L[1],L[2],L[3]).solve(RL(p,1,_,C))}return M}static parse(u,p){let[_,C,M,...L]=u;if(!Array.isArray(C)||C.length===0)return p.error("Expected an interpolation type expression.",1);if(C[0]==="linear")C={name:"linear"};else if(C[0]==="exponential"){const W=C[1];if(typeof W!="number")return p.error("Exponential interpolation requires a numeric base.",1,1);C={name:"exponential",base:W}}else{if(C[0]!=="cubic-bezier")return p.error(`Unknown interpolation type ${String(C[0])}`,1,0);{const W=C.slice(1);if(W.length!==4||W.some(J=>typeof J!="number"||J<0||J>1))return p.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);C={name:"cubic-bezier",controlPoints:W}}}if(u.length-1<4)return p.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length-1>3&&(u.length-1)%2!=0)return p.error("Expected an even number of arguments.");if(M=p.parse(M,2,Gr),!M)return null;const O=[];let U=null;_==="interpolate-hcl"||_==="interpolate-lab"?U=ah:p.expectedType&&p.expectedType.kind!=="value"&&(U=p.expectedType);for(let W=0;W=J)return p.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',re);const xe=p.parse(se,fe,U);if(!xe)return null;U=U||xe.type,O.push([J,xe])}return U.kind==="number"||U.kind==="color"||U.kind==="array"&&U.itemType.kind==="number"&&typeof U.N=="number"?new xm(U,_,C,M,O):p.error(`Type ${ea(U)} is not interpolatable.`)}evaluate(u){const p=this.labels,_=this.outputs;if(p.length===1)return _[0].evaluate(u);const C=this.input.evaluate(u);if(C<=p[0])return _[0].evaluate(u);const M=p.length;if(C>=p[M-1])return _[M-1].evaluate(u);const L=TN(p,C),O=xm.interpolationFactor(this.interpolation,C,p[L],p[L+1]),U=_[L].evaluate(u),W=_[L+1].evaluate(u);return this.operator==="interpolate"?dT[this.type.kind.toLowerCase()](U,W,O):this.operator==="interpolate-hcl"?tw.reverse(tw.interpolate(tw.forward(U),tw.forward(W),O)):ew.reverse(ew.interpolate(ew.forward(U),ew.forward(W),O))}eachChild(u){u(this.input);for(const p of this.outputs)u(p)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){let u;u=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const p=[this.operator,u,this.input.serialize()];for(let _=0;_V_(C,O.type));return new NT(L?Si:_,M)}evaluate(u){let p,_=null,C=0;for(const M of this.args){if(C++,_=M.evaluate(u),_&&_ instanceof Au&&!_.available&&(p||(p=_),_=null,C===this.args.length))return p;if(_!==null)break}return _}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){const u=["coalesce"];return this.eachChild(p=>{u.push(p.serialize())}),u}}const yye=/[^a-zA-Z0-9_]/;class hy{constructor(u,p){this.type=p.type,this.bindings=[].concat(u),this.result=p}evaluate(u){return this.result.evaluate(u)}eachChild(u){for(const p of this.bindings)u(p[1]);u(this.result)}static parse(u,p){if(u.length<4)return p.error(`Expected at least 3 arguments, but found ${u.length-1} instead.`);const _=[];for(let M=1;M=_.length)throw new No("Array index out of bounds: index exceeds array size");if(p!==Math.floor(p))throw new No("Array index must be an integer. Use at-interpolated for fractional indices");return _[p]}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class ka{constructor(u,p,_){this.type=u,this.index=p,this.input=_}static parse(u,p){if(u.length!==3)return p.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const _=p.parse(u[1],1,Gr),C=p.parse(u[2],2,uu(p.expectedType||Si));return _&&C?new ka(C.type.itemType,_,C):null}evaluate(u){const p=this.index.evaluate(u),_=this.input.evaluate(u);if(p<0)throw new No(`Array index out of bounds: ${p} < 0.`);if(p>_.length-1)throw new No(`Array index out of bounds: ${p} > ${_.length-1}.`);if(p===Math.floor(p))return _[p];const C=Math.floor(p),M=Math.ceil(p),L=_[C],O=_[M];if(typeof L!="number"||typeof O!="number")throw new No(`Cannot interpolate between non-number values at index ${p}.`);const U=p-C;return L*(1-U)+O*U}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class OL{constructor(u,p){this.type=$a,this.needle=u,this.haystack=p}static parse(u,p){if(u.length!==3)return p.error(`Expected 2 arguments, but found ${u.length-1} instead.`),null;const _=p.parse(u[1],1,Si),C=p.parse(u[2],2,Si);return _&&C?vL(_.type,[$a,_i,Gr,E0,Si])?new OL(_,C):(p.error(`Expected first argument to be of type boolean, string, number or null, but found ${ea(_.type)} instead`),null):null}evaluate(u){const p=this.needle.evaluate(u),_=this.haystack.evaluate(u);if(_==null)return!1;if(!hN(p,["boolean","string","number","null"]))throw new No(`Expected first argument to be of type boolean, string, number or null, but found ${ea(Rl(p))} instead.`);if(!hN(_,["string","array"]))throw new No(`Expected second argument to be of type array or string, but found ${ea(Rl(_))} instead.`);return _.includes(p)}eachChild(u){u(this.needle),u(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class ST{constructor(u,p,_){this.type=Gr,this.needle=u,this.haystack=p,this.fromIndex=_}static parse(u,p){if(u.length<=2||u.length>=5)return p.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const _=p.parse(u[1],1,Si),C=p.parse(u[2],2,Si);if(!_||!C)return null;if(!vL(_.type,[$a,_i,Gr,E0,Si]))return p.error(`Expected first argument to be of type boolean, string, number or null, but found ${ea(_.type)} instead`),null;if(u.length===4){const M=p.parse(u[3],3,Gr);return M?new ST(_,C,M):null}return new ST(_,C)}evaluate(u){const p=this.needle.evaluate(u),_=this.haystack.evaluate(u);if(!hN(p,["boolean","string","number","null"]))throw new No(`Expected first argument to be of type boolean, string, number or null, but found ${ea(Rl(p))} instead.`);if(!hN(_,["string","array"]))throw new No(`Expected second argument to be of type array or string, but found ${ea(Rl(_))} instead.`);if(this.fromIndex){const C=this.fromIndex.evaluate(u);return _.indexOf(p,C)}return _.indexOf(p)}eachChild(u){u(this.needle),u(this.haystack),this.fromIndex&&u(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const u=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),u]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class FL{constructor(u,p,_,C,M,L){this.inputType=u,this.type=p,this.input=_,this.cases=C,this.outputs=M,this.otherwise=L}static parse(u,p){if(u.length<5)return p.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length%2!=1)return p.error("Expected an even number of arguments.");let _,C;p.expectedType&&p.expectedType.kind!=="value"&&(C=p.expectedType);const M={},L=[];for(let W=2;WNumber.MAX_SAFE_INTEGER)return re.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof xe=="number"&&Math.floor(xe)!==xe)return re.error("Numeric branch labels must be integer values.");if(_){if(re.checkSubtype(_,Rl(xe)))return null}else _=Rl(xe);if(M[String(xe)]!==void 0)return re.error("Branch labels must be unique.");M[String(xe)]=L.length}const fe=p.parse(se,W,C);if(!fe)return null;C=C||fe.type,L.push(fe)}const O=p.parse(u[1],1,Si);if(!O)return null;const U=p.parse(u.at(-1),u.length-1,C);return U?O.type.kind!=="value"&&p.concat(1).checkSubtype(_,O.type)?null:new FL(_,C,O,M,L,U):null}evaluate(u){const p=this.input.evaluate(u);return(D1(Rl(p),this.inputType)&&this.outputs[this.cases[p]]||this.otherwise).evaluate(u)}eachChild(u){u(this.input),this.outputs.forEach(u),u(this.otherwise)}outputDefined(){return this.outputs.every(u=>u.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["match",this.input.serialize()],p=Object.keys(this.cases).sort(),_=[],C={};for(const L of p){const O=C[this.cases[L]];O===void 0?(C[this.cases[L]]=_.length,_.push([this.cases[L],[L]])):_[O][1].push(L)}const M=L=>this.inputType.kind==="number"?Number(L):L;for(const[L,O]of _)u.push(O.length===1?M(O[0]):O.map(M)),u.push(this.outputs[L].serialize());return u.push(this.otherwise.serialize()),u}}class CT{constructor(u,p,_){this.type=u,this.branches=p,this.otherwise=_}static parse(u,p){if(u.length<4)return p.error(`Expected at least 3 arguments, but found only ${u.length-1}.`),null;if(u.length%2!=0)return p.error("Expected an odd number of arguments."),null;let _;p.expectedType&&p.expectedType.kind!=="value"&&(_=p.expectedType);const C=[];for(let L=1;Lp.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["case"];return this.eachChild(p=>{u.push(p.serialize())}),u}}class TT{constructor(u,p,_,C){this.type=u,this.input=p,this.beginIndex=_,this.endIndex=C}static parse(u,p){if(u.length<=2||u.length>=5)return p.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const _=p.parse(u[1],1,Si),C=p.parse(u[2],2,Gr);if(!_||!C)return null;if(!vL(_.type,[uu(Si),_i,Si]))return p.error(`Expected first argument to be of type array or string, but found ${ea(_.type)} instead`),null;if(u.length===4){const M=p.parse(u[3],3,Gr);return M?new TT(_.type,_,C,M):null}return new TT(_.type,_,C)}evaluate(u){const p=this.input.evaluate(u),_=this.beginIndex.evaluate(u);if(!hN(p,["string","array"]))throw new No(`Expected first argument to be of type array or string, but found ${ea(Rl(p))} instead.`);if(this.endIndex){const C=this.endIndex.evaluate(u);return p.slice(_,C)}return p.slice(_)}eachChild(u){u(this.input),u(this.beginIndex),this.endIndex&&u(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const u=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),u]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class vo{constructor(u,p){this.type=uu(_i),this.str=u,this.delimiter=p}static parse(u,p){if(u.length!==3)return p.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const _=p.parse(u[1],1,_i),C=p.parse(u[2],2,_i);return _&&C?new vo(_,C):void 0}evaluate(u){const p=this.str.evaluate(u),_=this.delimiter.evaluate(u);return p.split(_)}eachChild(u){u(this.str),u(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function h7(y,u){return y==="=="||y==="!="?u.kind==="boolean"||u.kind==="string"||u.kind==="number"||u.kind==="null"||u.kind==="value":u.kind==="string"||u.kind==="number"||u.kind==="value"}function m7(y,u,p,_){return _.compare(u,p)===0}function sw(y,u,p){const _=y!=="=="&&y!=="!=";return class VJe{constructor(M,L,O){this.type=$a,this.lhs=M,this.rhs=L,this.collator=O,this.hasUntypedArgument=M.type.kind==="value"||L.type.kind==="value"}static parse(M,L){if(M.length!==3&&M.length!==4)return L.error("Expected two or three arguments.");const O=M[0];let U=L.parse(M[1],1,Si);if(!U)return null;if(!h7(O,U.type))return L.concat(1).error(`"${O}" comparisons are not supported for type '${ea(U.type)}'.`);let W=L.parse(M[2],2,Si);if(!W)return null;if(!h7(O,W.type))return L.concat(2).error(`"${O}" comparisons are not supported for type '${ea(W.type)}'.`);if(U.type.kind!==W.type.kind&&U.type.kind!=="value"&&W.type.kind!=="value")return L.error(`Cannot compare types '${ea(U.type)}' and '${ea(W.type)}'.`);_&&(U.type.kind==="value"&&W.type.kind!=="value"?U=new Mp(W.type,[U]):U.type.kind!=="value"&&W.type.kind==="value"&&(W=new Mp(U.type,[W])));let J=null;if(M.length===4){if(U.type.kind!=="string"&&W.type.kind!=="string"&&U.type.kind!=="value"&&W.type.kind!=="value")return L.error("Cannot use collator to compare non-string types.");if(J=L.parse(M[3],3,A0),!J)return null}return new VJe(U,W,J)}evaluate(M){const L=this.lhs.evaluate(M),O=this.rhs.evaluate(M);if(_&&this.hasUntypedArgument){const U=Rl(L),W=Rl(O);if(U.kind!==W.kind||U.kind!=="string"&&U.kind!=="number")throw new No(`Expected arguments for "${y}" to be (string, string) or (number, number), but found (${U.kind}, ${W.kind}) instead.`)}if(this.collator&&!_&&this.hasUntypedArgument){const U=Rl(L),W=Rl(O);if(U.kind!=="string"||W.kind!=="string")return u(M,L,O)}return this.collator?p(M,L,O,this.collator.evaluate(M)):u(M,L,O)}eachChild(M){M(this.lhs),M(this.rhs),this.collator&&M(this.collator)}outputDefined(){return!0}serialize(){const M=[y];return this.eachChild(L=>{M.push(L.serialize())}),M}}}const vye=sw("==",function(y,u,p){return u===p},m7),bye=sw("!=",function(y,u,p){return u!==p},function(y,u,p,_){return!m7(0,u,p,_)}),_ye=sw("<",function(y,u,p){return u",function(y,u,p){return u>p},function(y,u,p,_){return _.compare(u,p)>0}),jye=sw("<=",function(y,u,p){return u<=p},function(y,u,p,_){return _.compare(u,p)<=0}),Nye=sw(">=",function(y,u,p){return u>=p},function(y,u,p,_){return _.compare(u,p)>=0});class BL{constructor(u,p,_,C,M,L){this.type=_i,this.number=u,this.locale=p,this.currency=_,this.unit=C,this.minFractionDigits=M,this.maxFractionDigits=L}static parse(u,p){if(u.length!==3)return p.error("Expected two arguments.");const _=p.parse(u[1],1,Gr);if(!_)return null;const C=u[2];if(typeof C!="object"||Array.isArray(C))return p.error("NumberFormat options argument must be an object.");let M=null;if(C.locale&&(M=p.parseObjectValue(C.locale,2,"locale",_i),!M))return null;let L=null;if(C.currency&&(L=p.parseObjectValue(C.currency,2,"currency",_i),!L))return null;let O=null;if(C.unit&&(O=p.parseObjectValue(C.unit,2,"unit",_i),!O))return null;let U=null;if(C["min-fraction-digits"]&&(U=p.parseObjectValue(C["min-fraction-digits"],2,"min-fraction-digits",Gr),!U))return null;let W=null;return C["max-fraction-digits"]&&(W=p.parseObjectValue(C["max-fraction-digits"],2,"max-fraction-digits",Gr),!W)?null:new BL(_,M,L,O,U,W)}evaluate(u){return new Intl.NumberFormat(this.locale?this.locale.evaluate(u):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(u):void 0,unit:this.unit?this.unit.evaluate(u):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(u):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(u):void 0}).format(this.number.evaluate(u))}eachChild(u){u(this.number),this.locale&&u(this.locale),this.currency&&u(this.currency),this.unit&&u(this.unit),this.minFractionDigits&&u(this.minFractionDigits),this.maxFractionDigits&&u(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const u={};return this.locale&&(u.locale=this.locale.serialize()),this.currency&&(u.currency=this.currency.serialize()),this.unit&&(u.unit=this.unit.serialize()),this.minFractionDigits&&(u["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(u["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),u]}}class zL{constructor(u){this.type=Gr,this.input=u}static parse(u,p){if(u.length!==2)return p.error(`Expected 1 argument, but found ${u.length-1} instead.`),null;const _=p.parse(u[1],1);return _?_.type.kind!=="array"&&_.type.kind!=="string"&&_.type.kind!=="value"?(p.error(`Expected argument of type string or array, but found ${ea(_.type)} instead.`),null):new zL(_):null}evaluate(u){const p=this.input.evaluate(u);if(typeof p=="string"||Array.isArray(p))return p.length;throw new No(`Expected value to be of type string or array, but found ${ea(Rl(p))} instead.`)}eachChild(u){u(this.input)}outputDefined(){return!1}serialize(){const u=["length"];return this.eachChild(p=>{u.push(p.serialize())}),u}}function $L(y){return function(){y=1831565813+(y|=0)|0;let u=Math.imul(y^y>>>15,1|y);return u=u+Math.imul(u^u>>>7,61|u)^u,((u^u>>>14)>>>0)/4294967296}}const rw={"==":vye,"!=":bye,">":wye,"<":_ye,">=":Nye,"<=":jye,array:Mp,at:kT,"at-interpolated":ka,boolean:Mp,case:CT,coalesce:NT,collator:O1,format:W_,image:mN,in:OL,"index-of":ST,interpolate:xm,"interpolate-hcl":xm,"interpolate-lab":xm,length:zL,let:hy,literal:Ap,match:FL,number:Mp,"number-format":BL,object:Mp,slice:TT,step:Q_,string:Mp,"to-boolean":Yx,"to-color":Yx,"to-number":Yx,"to-string":Yx,var:SN,within:Xx,distance:U1,config:V1,split:vo};function f7(y,[u,p,_,C]){u=u.evaluate(y),p=p.evaluate(y),_=_.evaluate(y);const M=C?C.evaluate(y):1,L=Hz(u,p,_,M);if(L)throw new No(L);return new Wa(u/255,p/255,_/255,M)}function p7(y,[u,p,_,C]){u=u.evaluate(y),p=p.evaluate(y),_=_.evaluate(y);const M=C?C.evaluate(y):1,L=function(W,J,se,re){return typeof W=="number"&&W>=0&&W<=360?typeof J=="number"&&J>=0&&J<=100&&typeof se=="number"&&se>=0&&se<=100?re===void 0||typeof re=="number"&&re>=0&&re<=1?null:`Invalid hsla value [${[W,J,se,re].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof re=="number"?[W,J,se,re]:[W,J,se]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof re=="number"?[W,J,se,re]:[W,J,se]).join(", ")}]: 'h' must be between 0 and 360.`}(u,p,_,M);if(L)throw new No(L);const O=`hsla(${u}, ${p}%, ${_}%, ${M})`,U=Wa.parse(O);if(!U)throw new No(`Failed to parse HSLA color: ${O}`);return U}function x7(y,u){return y in u}function UL(y,u){const p=u[y];return p===void 0?null:p}function I0(y){return{type:y}}function ET(y){if(y instanceof V1)return new Set([y.key]);let u=new Set;return y.eachChild(p=>{u=new Set([...u,...ET(p)])}),u}function AT(y){if(y instanceof ih&&y.name==="is-active-floor")return!0;let u=!1;return y.eachChild(p=>{!u&&AT(p)&&(u=!0)}),u}function g7(y){return{result:"success",value:y}}function P0(y){return{result:"error",value:y}}function qL(y,u){return!!y&&!!y.parameters&&y.parameters.includes(u)}function MT(y){return y["property-type"]==="data-driven"}function y7(y){return qL(y.expression,"measure-light")}function v7(y){return qL(y.expression,"zoom")}function VL(y){return!!y.expression&&y.expression.interpolated}function HL(y){return typeof y=="object"&&y!==null&&!Array.isArray(y)}function kye(y){return y}function b7(y,u){const p=u.type==="color",_=y.stops&&typeof y.stops[0][0]=="object",C=_||!(_||y.property!==void 0),M=y.type||(VL(u)?"exponential":"interval");if(p&&((y=Object.assign({},y)).stops&&(y.stops=y.stops.map(W=>[W[0],Wa.parse(W[1])])),y.default=Wa.parse(y.default?y.default:u.default)),y.colorSpace&&y.colorSpace!=="rgb"&&!DL[y.colorSpace])throw new Error(`Unknown color space: ${y.colorSpace}`);let L,O,U;if(M==="exponential")L=WL;else if(M==="interval")L=IT;else if(M==="categorical"){L=GL,O=Object.create(null);for(const W of y.stops)O[W[0]]=W[1];U=typeof y.stops[0][0]}else{if(M!=="identity")throw new Error(`Unknown function type "${M}"`);L=Sye}if(_){const W={},J=[];for(let fe=0;fefe[0]),evaluate:({zoom:fe},xe)=>WL({stops:se,base:y.base},u,fe).evaluate(fe,xe)}}if(C){const W=M==="exponential"?{name:"exponential",base:y.base!==void 0?y.base:1}:null;return{kind:"camera",interpolationType:W,interpolationFactor:xm.interpolationFactor.bind(void 0,W),zoomStops:y.stops.map(J=>J[0]),evaluate:({zoom:J})=>L(y,u,J,O,U)}}return{kind:"source",evaluate(W,J){const se=J&&J.properties?J.properties[y.property]:void 0;return se===void 0?AN(y.default,u.default):L(y,u,se,O,U)}}}function AN(y,u,p){return y!==void 0?y:u!==void 0?u:p!==void 0?p:void 0}function GL(y,u,p,_,C){return AN(typeof p===C?_[p]:void 0,y.default,u.default)}function IT(y,u,p){if(!fN(p))return AN(y.default,u.default);const _=y.stops.length;if(_===1||p<=y.stops[0][0])return y.stops[0][1];if(p>=y.stops[_-1][0])return y.stops[_-1][1];const C=TN(y.stops.map(M=>M[0]),p);return y.stops[C][1]}function WL(y,u,p){const _=y.base!==void 0?y.base:1;if(!fN(p))return AN(y.default,u.default);const C=y.stops.length;if(C===1||p<=y.stops[0][0])return y.stops[0][1];if(p>=y.stops[C-1][0])return y.stops[C-1][1];const M=TN(y.stops.map(J=>J[0]),p),L=function(J,se,re,fe){const xe=fe-re,we=J-re;return xe===0?0:se===1?we/xe:(Math.pow(se,we)-1)/(Math.pow(se,xe)-1)}(p,_,y.stops[M][0],y.stops[M+1][0]),O=y.stops[M][1],U=y.stops[M+1][1];let W=dT[u.type]||kye;if(y.colorSpace&&y.colorSpace!=="rgb"){const J=DL[y.colorSpace];W=(se,re)=>J.reverse(J.interpolate(J.forward(se),J.forward(re),L))}return typeof O.evaluate=="function"?{evaluate(...J){const se=O.evaluate.apply(void 0,J),re=U.evaluate.apply(void 0,J);if(se!==void 0&&re!==void 0)return W(se,re,L)}}:W(O,U,L)}function Sye(y,u,p){return u.type==="color"?p=Wa.parse(p):u.type==="formatted"?p=hu.fromString(p.toString()):u.type==="resolvedImage"?p=Au.build(p.toString()):mT(p)===u.type||u.type==="enum"&&u.values[p]||(p=void 0),AN(p,y.default,u.default)}ih.register(rw,{error:[{kind:"error"},[_i],(y,[u])=>{throw new No(u.evaluate(y))}],typeof:[_i,[Si],(y,[u])=>ea(Rl(u.evaluate(y)))],"to-rgba":[uu(Gr,4),[ah],(y,[u])=>u.evaluate(y).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[uu(Gr,4),[ah],(y,[u])=>u.evaluate(y).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[ah,[Gr,Gr,Gr],f7],rgba:[ah,[Gr,Gr,Gr,Gr],f7],hsl:[ah,[Gr,Gr,Gr],p7],hsla:[ah,[Gr,Gr,Gr,Gr],p7],has:{type:$a,overloads:[[[_i],(y,[u])=>x7(u.evaluate(y),y.properties())],[[_i,Kx],(y,[u,p])=>x7(u.evaluate(y),p.evaluate(y))]]},get:{type:Si,overloads:[[[_i],(y,[u])=>UL(u.evaluate(y),y.properties())],[[_i,Kx],(y,[u,p])=>UL(u.evaluate(y),p.evaluate(y))]]},"feature-state":[Si,[_i],(y,[u])=>UL(u.evaluate(y),y.featureState||{})],properties:[Kx,[],y=>y.properties()],"geometry-type":[_i,[],y=>y.geometryType()],worldview:[_i,[],y=>y.globals.worldview||""],"is-active-floor":[$a,I0(_i),(y,u)=>{if(!(y.globals&&y.globals.activeFloors&&y.globals.activeFloors.size>0))return!1;if(u.length===0)return!0;const p=y.globals.activeFloors;return u.some(_=>{const C=_.evaluate(y);return p.has(C)})}],id:[Si,[],y=>y.id()],zoom:[Gr,[],y=>y.globals.zoom],pitch:[Gr,[],y=>y.globals.pitch||0],"distance-from-center":[Gr,[],y=>y.distanceFromCenter()],"measure-light":[Gr,[_i],(y,[u])=>y.measureLight(u.evaluate(y))],"heatmap-density":[Gr,[],y=>y.globals.heatmapDensity||0],"line-progress":[Gr,[],y=>y.globals.lineProgress||0],"raster-value":[Gr,[],y=>y.globals.rasterValue||0],"raster-particle-speed":[Gr,[],y=>y.globals.rasterParticleSpeed||0],"sky-radial-progress":[Gr,[],y=>y.globals.skyRadialProgress||0],accumulated:[Si,[],y=>y.globals.accumulated===void 0?null:y.globals.accumulated],"+":[Gr,I0(Gr),(y,u)=>{let p=0;for(const _ of u)p+=_.evaluate(y);return p}],"*":[Gr,I0(Gr),(y,u)=>{let p=1;for(const _ of u)p*=_.evaluate(y);return p}],"-":{type:Gr,overloads:[[[Gr,Gr],(y,[u,p])=>u.evaluate(y)-p.evaluate(y)],[[Gr],(y,[u])=>-u.evaluate(y)]]},"/":[Gr,[Gr,Gr],(y,[u,p])=>u.evaluate(y)/p.evaluate(y)],"%":[Gr,[Gr,Gr],(y,[u,p])=>u.evaluate(y)%p.evaluate(y)],ln2:[Gr,[],()=>Math.LN2],pi:[Gr,[],()=>Math.PI],e:[Gr,[],()=>Math.E],"^":[Gr,[Gr,Gr],(y,[u,p])=>Math.pow(u.evaluate(y),p.evaluate(y))],sqrt:[Gr,[Gr],(y,[u])=>Math.sqrt(u.evaluate(y))],log10:[Gr,[Gr],(y,[u])=>Math.log(u.evaluate(y))/Math.LN10],ln:[Gr,[Gr],(y,[u])=>Math.log(u.evaluate(y))],log2:[Gr,[Gr],(y,[u])=>Math.log2(u.evaluate(y))],sin:[Gr,[Gr],(y,[u])=>Math.sin(u.evaluate(y))],cos:[Gr,[Gr],(y,[u])=>Math.cos(u.evaluate(y))],tan:[Gr,[Gr],(y,[u])=>Math.tan(u.evaluate(y))],asin:[Gr,[Gr],(y,[u])=>Math.asin(u.evaluate(y))],acos:[Gr,[Gr],(y,[u])=>Math.acos(u.evaluate(y))],atan:[Gr,[Gr],(y,[u])=>Math.atan(u.evaluate(y))],min:[Gr,I0(Gr),(y,u)=>Math.min(...u.map(p=>p.evaluate(y)))],max:[Gr,I0(Gr),(y,u)=>Math.max(...u.map(p=>p.evaluate(y)))],abs:[Gr,[Gr],(y,[u])=>Math.abs(u.evaluate(y))],round:[Gr,[Gr],(y,[u])=>{const p=u.evaluate(y);return p<0?-Math.round(-p):Math.round(p)}],floor:[Gr,[Gr],(y,[u])=>Math.floor(u.evaluate(y))],ceil:[Gr,[Gr],(y,[u])=>Math.ceil(u.evaluate(y))],"filter-==":[$a,[_i,Si],(y,[u,p])=>y.properties()[u.value]===p.value],"filter-id-==":[$a,[Si],(y,[u])=>y.id()===u.value],"filter-type-==":[$a,[_i],(y,[u])=>y.geometryType()===u.value],"filter-<":[$a,[_i,Si],(y,[u,p])=>{const _=y.properties()[u.value],C=p.value;return typeof _==typeof C&&_{const p=y.id(),_=u.value;return typeof p==typeof _&&p<_}],"filter->":[$a,[_i,Si],(y,[u,p])=>{const _=y.properties()[u.value],C=p.value;return typeof _==typeof C&&_>C}],"filter-id->":[$a,[Si],(y,[u])=>{const p=y.id(),_=u.value;return typeof p==typeof _&&p>_}],"filter-<=":[$a,[_i,Si],(y,[u,p])=>{const _=y.properties()[u.value],C=p.value;return typeof _==typeof C&&_<=C}],"filter-id-<=":[$a,[Si],(y,[u])=>{const p=y.id(),_=u.value;return typeof p==typeof _&&p<=_}],"filter->=":[$a,[_i,Si],(y,[u,p])=>{const _=y.properties()[u.value],C=p.value;return typeof _==typeof C&&_>=C}],"filter-id->=":[$a,[Si],(y,[u])=>{const p=y.id(),_=u.value;return typeof p==typeof _&&p>=_}],"filter-has":[$a,[Si],(y,[u])=>u.value in y.properties()],"filter-has-id":[$a,[],y=>y.id()!==null&&y.id()!==void 0],"filter-type-in":[$a,[uu(_i)],(y,[u])=>u.value.includes(y.geometryType())],"filter-id-in":[$a,[uu(Si)],(y,[u])=>u.value.includes(y.id())],"filter-in-small":[$a,[_i,uu(Si)],(y,[u,p])=>p.value.includes(y.properties()[u.value])],"filter-in-large":[$a,[_i,uu(Si)],(y,[u,p])=>function(_,C,M,L){for(;M<=L;){const O=M+L>>1;if(C[O]===_)return!0;C[O]>_?L=O-1:M=O+1}return!1}(y.properties()[u.value],p.value,0,p.value.length-1)],all:{type:$a,overloads:[[[$a,$a],(y,[u,p])=>u.evaluate(y)&&p.evaluate(y)],[I0($a),(y,u)=>{for(const p of u)if(!p.evaluate(y))return!1;return!0}]]},any:{type:$a,overloads:[[[$a,$a],(y,[u,p])=>u.evaluate(y)||p.evaluate(y)],[I0($a),(y,u)=>{for(const p of u)if(p.evaluate(y))return!0;return!1}]]},"!":[$a,[$a],(y,[u])=>!u.evaluate(y)],"is-supported-script":[$a,[_i],(y,[u])=>{const p=y.globals&&y.globals.isSupportedScript;return!p||p(u.evaluate(y))}],upcase:[_i,[_i],(y,[u])=>u.evaluate(y).toUpperCase()],downcase:[_i,[_i],(y,[u])=>u.evaluate(y).toLowerCase()],concat:[_i,I0(Si),(y,u)=>u.map(p=>Ff(p.evaluate(y))).join("")],"resolved-locale":[_i,[A0],(y,[u])=>u.evaluate(y).resolvedLocale()],random:[Gr,[Gr,Gr,Si],(y,u)=>{const[p,_,C]=u.map(L=>L.evaluate(y));if(p>_||p===_)return p;let M;if(typeof C=="string")M=function(L){let O=0;if(L.length===0)return O;for(let U=0;UJSON.stringify(se)).join(", ")}, but found ${JSON.stringify(J)} instead.`);return J}catch(J){const se=J;return this._warningHistory[se.message]||(this._warningHistory[se.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${se.message}`)),this._defaultValue}}}function PT(y){return Array.isArray(y)&&y.length>0&&typeof y[0]=="string"&&y[0]in rw}function L0(y,u,p,_,C){const M=new pm(rw,[],u?function(O){const U={color:ah,string:_i,number:Gr,enum:_i,boolean:$a,formatted:q_,resolvedImage:uN};return O.type==="array"?uu(U[O.value]||Si,O.length):U[O.type]}(u):void 0,void 0,void 0,p,_,C),L=M.parse(y,void 0,void 0,void 0,u&&u.type==="string"?{typeAnnotation:"coerce"}:void 0);return L?g7(new KL(L,u,p,_,C)):P0(M.errors)}class MN{constructor(u,p,_,C){this.kind=u,this._styleExpression=p,this.isLightConstant=_,this.isLineProgressConstant=C,this.isStateDependent=u!=="constant"&&!Bf(p.expression),this.configDependencies=ET(p.expression),this.isIndoorDependent=AT(p.expression)}evaluateWithoutErrorHandling(u,p,_,C,M,L){return this._styleExpression.evaluateWithoutErrorHandling(u,p,_,C,M,L)}evaluate(u,p,_,C,M,L,O){return this._styleExpression.evaluate(u,p,_,C,M,L,void 0,void 0,O)}}class eg{constructor(u,p,_,C,M,L){this.kind=u,this.zoomStops=_,this._styleExpression=p,this.isStateDependent=u!=="camera"&&!Bf(p.expression),this.isIndoorDependent=AT(p.expression),this.isLightConstant=M,this.isLineProgressConstant=L,this.configDependencies=ET(p.expression),this.interpolationType=C}evaluateWithoutErrorHandling(u,p,_,C,M,L){return this._styleExpression.evaluateWithoutErrorHandling(u,p,_,C,M,L)}evaluate(u,p,_,C,M,L){return this._styleExpression.evaluate(u,p,_,C,M,L)}interpolationFactor(u,p,_){return this.interpolationType?xm.interpolationFactor(this.interpolationType,u,p,_):0}}function YL(y,u,p,_,C){if((y=L0(y,u,p,_,C)).result==="error")return y;const M=y.value.expression,L=q1(M);if(!L&&!MT(u))return P0([new Ep("","data expressions not supported")]);const O=Jx(M,["zoom","pitch","distance-from-center"]);if(!O&&!v7(u))return P0([new Ep("","zoom expressions not supported")]);const U=Jx(M,["measure-light"]);if(!U&&!y7(u))return P0([new Ep("","measure-light expression not supported")]);const W=Jx(M,["line-progress"]);if(!W&&!function(re){return qL(re.expression,"line-progress")}(u))return P0([new Ep("","line-progress expression not supported")]);const J=u.expression&&u.expression.relaxZoomRestriction,se=nw(M);return se||O||J?se instanceof Ep?P0([se]):se instanceof xm&&!VL(u)?P0([new Ep("",'"interpolate" expressions cannot be used with this property')]):g7(se?new eg(L&&W?"camera":"composite",y.value,se.labels,se instanceof xm?se.interpolation:void 0,U,W):new MN(L&&W?"constant":"source",y.value,U,W)):P0([new Ep("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class LT{constructor(u,p){this._parameters=u,this._specification=p,Object.assign(this,b7(this._parameters,this._specification))}static deserialize(u){return new LT(u._parameters,u._specification)}static serialize(u){return{_parameters:u._parameters,_specification:u._specification}}}function nw(y){let u=null;if(y instanceof hy)u=nw(y.result);else if(y instanceof NT){for(const p of y.args)if(u=nw(p),u)break}else(y instanceof Q_||y instanceof xm)&&y.input instanceof ih&&y.input.name==="zoom"&&(u=y);return u instanceof Ep||y.eachChild(p=>{const _=nw(p);_ instanceof Ep?u=_:u&&_&&u!==_&&(u=new Ep("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),u}class G1{constructor(u,p,_){if(this.boxSeen=new Uint32Array(0),this.circleSeen=new Uint32Array(0),this.generation=0,u instanceof ArrayBuffer){const C=new Int32Array(u);this.width=C[0],this.height=C[1],this.xCellCount=C[2],this.yCellCount=C[3],this.boxUid=C[4],this.circleUid=C[5];const M=this.xCellCount*this.yCellCount,L=[];for(let J=0;Jthis.width||C<0||p>this.height)return L;const O=this._nextGen(),{boxCells:U,circleCells:W,boxKeys:J,circleKeys:se,bboxes:re,circles:fe,boxSeen:xe,circleSeen:we,xCellCount:je}=this,Be=this._xCell(u),Ye=this._yCell(p),Ue=this._xCell(_),tt=this._yCell(C);for(let ot=Be;ot<=Ue;ot++)for(let pt=Ye;pt<=tt;pt++){const Rt=je*pt+ot,_t=U[Rt];if(_t)for(let jt=0;jt<_t.length;jt++){const At=_t[jt];if(xe[At]===O)continue;xe[At]=O;const ns=4*At,is=re[ns],xs=re[ns+1],ks=re[ns+2],ws=re[ns+3];u<=ks&&p<=ws&&_>=is&&C>=xs&&(!M||M(J[At]))&&L.push({key:J[At],x1:is,y1:xs,x2:ks,y2:ws})}const Et=W[Rt];if(Et)for(let jt=0;jtthis.width||C<0||p>this.height)return L;const O=this._nextGen(),{boxCells:U,boxKeys:W,bboxes:J,boxSeen:se,xCellCount:re,xScale:fe,yScale:xe}=this,we=this._xCell(u),je=this._yCell(p),Be=this._xCell(_),Ye=this._yCell(C);for(let Ue=we;Ue<=Be;Ue++)for(let tt=je;tt<=Ye;tt++){if(M&&!M(Ue/fe,tt/xe,(Ue+1)/fe,(tt+1)/xe))continue;const ot=U[re*tt+Ue];if(ot)for(let pt=0;pt=Et&&C>=jt)&&L.push(W[Rt])}}return L}hitTest(u,p,_,C,M){if(_<0||u>this.width||C<0||p>this.height)return!1;const L=this._nextGen(),{boxCells:O,circleCells:U,boxKeys:W,circleKeys:J,bboxes:se,circles:re,boxSeen:fe,circleSeen:xe,xCellCount:we}=this,je=this._xCell(u),Be=this._yCell(p),Ye=this._xCell(_),Ue=this._yCell(C);for(let tt=je;tt<=Ye;tt++)for(let ot=Be;ot<=Ue;ot++){const pt=we*ot+tt,Rt=O[pt];if(Rt)for(let Et=0;Et=se[At]&&C>=se[At+1]&&(!M||M(W[jt])))return!0}const _t=U[pt];if(_t)for(let Et=0;Et<_t.length;Et++){const jt=_t[Et];if(xe[jt]===L)continue;xe[jt]=L;const At=3*jt;if(this._circleAndRectCollide(re[At],re[At+1],re[At+2],u,p,_,C)&&(!M||M(J[jt])))return!0}}return!1}hitTestCircle(u,p,_,C){const M=u-_,L=p-_,O=u+_,U=p+_;if(O<0||M>this.width||U<0||L>this.height)return!1;const W=this._nextGen(),{boxCells:J,circleCells:se,boxKeys:re,circleKeys:fe,bboxes:xe,circles:we,boxSeen:je,circleSeen:Be,xCellCount:Ye}=this,Ue=this._xCell(M),tt=this._yCell(L),ot=this._xCell(O),pt=this._yCell(U);for(let Rt=Ue;Rt<=ot;Rt++)for(let _t=tt;_t<=pt;_t++){const Et=Ye*_t+Rt,jt=J[Et];if(jt)for(let ns=0;ns>>0,this.generation===0&&(this.boxSeen.fill(0),this.circleSeen.fill(0),this.generation=1),this.generation}_circlesCollide(u,p,_,C,M,L){const O=C-u,U=M-p,W=_+L;return W*W>O*O+U*U}_circleAndRectCollide(u,p,_,C,M,L,O){const U=(L-C)/2,W=Math.abs(u-(C+U));if(W>U+_)return!1;const J=(O-M)/2,se=Math.abs(p-(M+J));if(se>J+_)return!1;if(W<=U||se<=J)return!0;const re=W-U,fe=se-J;return re*re+fe*fe<=_*_}}const aw={};function Mr(y,u,p={}){Object.defineProperty(y,"_classRegistryKey",{value:u,writable:!1}),aw[u]={klass:y,omit:p.omit||[]}}Mr(Object,"Object"),Mr(G1,"Grid"),delete us.prototype.constructor,Mr(Wa,"Color"),Mr(Error,"Error"),Mr(hu,"Formatted"),Mr(R1,"FormattedSection"),Mr(Sp,"AJAXError"),Mr(Au,"ResolvedImage"),Mr(LT,"StylePropertyFunction"),Mr(KL,"StyleExpression",{omit:["_evaluator"]}),Mr(Gn,"ImageId"),Mr(Of,"ImageVariant"),Mr(eg,"ZoomDependentExpression"),Mr(MN,"ZoomConstantExpression"),Mr(ih,"CompoundExpression",{omit:["_evaluate"]});for(const y in rw)aw[rw[y]._classRegistryKey]||Mr(rw[y],`Expression${y}`);function _7(y){return y&&(y instanceof ArrayBuffer||y.constructor&&y.constructor.name==="ArrayBuffer")}function my(y,u){if(y===null)return null;const p=typeof y;if(p!=="object")return p==="bigint"?{$name:"BigInt",value:y.toString()}:y;if(Array.isArray(y)){const L=y.length,O=[];O.length=L;for(let U=0;Uy>=1536&&y<=1791,j7=y=>y>=1872&&y<=1919,N7=y=>y>=2208&&y<=2303,ZL=y=>y>=11904&&y<=12031,XL=y=>y>=12032&&y<=12255,IN=y=>y>=12272&&y<=12287,DT=y=>y>=12288&&y<=12351,RT=y=>y>=12352&&y<=12447,OT=y=>y>=12448&&y<=12543,k7=y=>y>=12544&&y<=12591,QL=y=>y>=12704&&y<=12735,JL=y=>y>=12736&&y<=12783,S7=y=>y>=12784&&y<=12799,C7=y=>y>=12800&&y<=13055,T7=y=>y>=13056&&y<=13311,e6=y=>y>=13312&&y<=19903,iw=y=>y>=19968&&y<=40959,E7=y=>y>=40960&&y<=42127,A7=y=>y>=42128&&y<=42191,M7=y=>y>=44032&&y<=55215,FT=y=>y>=63744&&y<=64255,t6=y=>y>=64336&&y<=65023,I7=y=>y>=65040&&y<=65055,BT=y=>y>=65072&&y<=65103,s6=y=>y>=65104&&y<=65135,r6=y=>y>=65136&&y<=65279,zT=y=>y>=65280&&y<=65519;function n6(y){for(const u of y)if($T(u.charCodeAt(0)))return!0;return!1}function P7(y){for(const u of y)if(!L7(u.charCodeAt(0)))return!1;return!0}function L7(y){return!(w7(y)||j7(y)||N7(y)||t6(y)||r6(y))}function D7(y){return!(y<11904||!(QL(y)||k7(y)||BT(y)||FT(y)||T7(y)||ZL(y)||JL(y)||DT(y)||e6(y)||iw(y)||C7(y)||zT(y)||RT(y)||IN(y)||XL(y)||S7(y)||OT(y)||I7(y)||A7(y)||E7(y)))}function $T(y){return!(y!==746&&y!==747&&(y<4352||!(QL(y)||k7(y)||BT(y)&&!(y>=65097&&y<=65103)||FT(y)||T7(y)||ZL(y)||JL(y)||!(!DT(y)||y>=12296&&y<=12305||y>=12308&&y<=12319||y===12336)||e6(y)||iw(y)||C7(y)||(u=>u>=12592&&u<=12687)(y)||(u=>u>=43360&&u<=43391)(y)||(u=>u>=55216&&u<=55295)(y)||(u=>u>=4352&&u<=4607)(y)||M7(y)||RT(y)||IN(y)||(u=>u>=12688&&u<=12703)(y)||XL(y)||S7(y)||OT(y)&&y!==12540||!(!zT(y)||y===65288||y===65289||y===65293||y>=65306&&y<=65310||y===65339||y===65341||y===65343||y>=65371&&y<=65503||y===65507||y>=65512&&y<=65519)||!(!s6(y)||y>=65112&&y<=65118||y>=65123&&y<=65126)||(u=>u>=5120&&u<=5759)(y)||(u=>u>=6320&&u<=6399)(y)||I7(y)||(u=>u>=19904&&u<=19967)(y)||E7(y)||A7(y))))}function a6(y){return y===12312||y===12313||y===12316||y===12540||y===12448}function UT(y){return!($T(y)||function(u){return!!((p=>p>=128&&p<=255)(u)&&(u===167||u===169||u===174||u===177||u===188||u===189||u===190||u===215||u===247)||(p=>p>=8192&&p<=8303)(u)&&(u===8214||u===8224||u===8225||u===8240||u===8241||u===8251||u===8252||u===8258||u===8263||u===8264||u===8265||u===8273)||(p=>p>=8448&&p<=8527)(u)||(p=>p>=8528&&p<=8591)(u)||(p=>p>=8960&&p<=9215)(u)&&(u>=8960&&u<=8967||u>=8972&&u<=8991||u>=8996&&u<=9e3||u===9003||u>=9085&&u<=9114||u>=9150&&u<=9165||u===9167||u>=9169&&u<=9179||u>=9186&&u<=9215)||(p=>p>=9216&&p<=9279)(u)&&u!==9251||(p=>p>=9280&&p<=9311)(u)||(p=>p>=9312&&p<=9471)(u)||(p=>p>=9632&&p<=9727)(u)||(p=>p>=9728&&p<=9983)(u)&&!(u>=9754&&u<=9759)||(p=>p>=11008&&p<=11263)(u)&&(u>=11026&&u<=11055||u>=11088&&u<=11097||u>=11192&&u<=11243)||DT(u)||OT(u)||(p=>p>=57344&&p<=63743)(u)||BT(u)||s6(u)||zT(u)||u===8734||u===8756||u===8757||u>=9984&&u<=10087||u>=10102&&u<=10131||u===65532||u===65533)}(y))}function R7(y){return w7(y)||j7(y)||N7(y)||t6(y)||r6(y)}function O7(y){return y>=1424&&y<=2303||t6(y)||r6(y)}function D0(y,u){return!(!u&&O7(y)||y>=2304&&y<=3583||y>=3840&&y<=4255||(p=>p>=6016&&p<=6143)(y))}function Cye(y){for(const u of y)if(O7(u.charCodeAt(0)))return!0;return!1}const gm={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let R0=null,oh=gm.unavailable,Ip=null;const i6=function(y){y&&(oh=gm.error),R0&&R0(y)};function ow(){qT.fire(new Gs("pluginStateChange",{pluginStatus:oh,pluginURL:Ip}))}const qT=new Aa,o6=function(){return oh},F7=function(){if(oh!==gm.deferred||!Ip)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");oh=gm.loading,ow(),Ip&&C0({url:Ip},y=>{y?i6(y):(oh=gm.loaded,ow())})},Pp={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>oh===gm.loaded||Pp.applyArabicShaping!=null,isLoading:()=>oh===gm.loading,setState(y){oh=y.pluginStatus,Ip=y.pluginURL},isParsing:()=>oh===gm.parsing,isParsed:()=>oh===gm.parsed,getPluginURL:()=>Ip},l6=function(){Pp.isLoading()||Pp.isLoaded()||o6()!=="deferred"||F7()};class fi{constructor(u,p){this.zoom=u,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(u){return function(p,_){for(const C of p)if(!D0(C.charCodeAt(0),_))return!1;return!0}(u,Pp.isLoaded())}}class PN{constructor(u,p,_,C,M){this.property=u,this.value=p,this.expression=function(L,O,U,W,J){if(HL(L))return new LT(L,O);if(PT(L)||Array.isArray(L)&&L.length>0){const se=YL(L,O,U,W,J);if(se.result==="error")throw new Error(se.value.map(re=>`${re.key}: ${re.message}`).join(", "));return se.value}{let se=L;return typeof L=="string"&&O.type==="color"&&(se=Wa.parse(L)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>se}}}(p===void 0?u.specification.default:p,u.specification,_,C,M)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(u,p,_,C){return this.property.possiblyEvaluate(this,u,p,_,C)}}class c6{constructor(u,p,_,C){this.property=u,this.value=new PN(u,void 0,p,_,C)}transitioned(u,p){return new DN(this.property,this.value,p,Object.assign({},u.transition,this.transition),u.now)}untransitioned(){return new DN(this.property,this.value,null,{},0)}}class LN{constructor(u,p,_,C){this._properties=u,this._values=Object.create(u.defaultTransitionablePropertyValues),this._scope=p,this._options=_,this._iconImageUseTheme=C,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(u){return In(this._values[u].value.value)}setValue(u,p){Object.hasOwn(this._values,u)||(this._values[u]=new c6(this._values[u].property,this._scope,this._options,this._iconImageUseTheme)),this._values[u].value=new PN(this._values[u].property,p===null?void 0:In(p),this._scope,this._options,this._iconImageUseTheme),this._values[u].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[u].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[u].value.isIndoorDependent())}setTransitionOrValue(u,p){p&&(this._options=p);const _=this._properties.properties;if(u)for(const C in u){const M=u[C];if(C.endsWith("-transition")){const L=C.slice(0,-11);_[L]&&this.setTransition(L,M)}else Object.hasOwn(_,C)&&this.setValue(C,M)}}getTransition(u){return In(this._values[u].transition)}setTransition(u,p){Object.hasOwn(this._values,u)||(this._values[u]=new c6(this._values[u].property)),this._values[u].transition=In(p)||void 0}serialize(){const u={};for(const p of Object.keys(this._values)){const _=this.getValue(p);_!==void 0&&(u[p]=_);const C=this.getTransition(p);C!==void 0&&(u[`${p}-transition`]=C)}return u}transitioned(u,p){const _=new VT(this._properties);for(const C of Object.keys(this._values))_._values[C]=this._values[C].transitioned(u,p._values[C]);return _}untransitioned(){const u=new VT(this._properties);for(const p of Object.keys(this._values))u._values[p]=this._values[p].untransitioned();return u}isIndoorDependent(){return this._isIndoorDependent}}class DN{constructor(u,p,_,C,M){const L=C.delay||0,O=C.duration||0;M=M||0,this.property=u,this.value=p,this.begin=M+L,this.end=this.begin+O,u.specification.transition&&(C.delay||C.duration)&&(this.prior=_)}possiblyEvaluate(u,p,_){const C=u.now||0,M=this.value.possiblyEvaluate(u,p,_),L=this.prior;if(L){if(C>this.end)return this.prior=null,M;if(this.value.isDataDriven())return this.prior=null,M;if(C":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"fill-extrusion-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}},"line-blend-additive-clamp":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":true,"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 d6(y){return y instanceof Number||y instanceof String||y instanceof Boolean?y.valueOf():y}function lw(y){if(Array.isArray(y))return y.map(lw);if(y instanceof Object&&!(y instanceof Number||y instanceof String||y instanceof Boolean)){const u={};for(const p in y)u[p]=lw(y[p]);return u}return d6(y)}function Lp(y){if(y===!0||y===!1)return!0;if(!Array.isArray(y)||y.length===0)return!1;switch(y[0]){case"has":return y.length>=2&&y[1]!=="$id"&&y[1]!=="$type";case"in":return y.length>=3&&(typeof y[1]!="string"||Array.isArray(y[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return y.length!==3||Array.isArray(y[1])||Array.isArray(y[2]);case"any":case"all":for(const u of y.slice(1))if(!Lp(u)&&typeof u!="boolean")return!1;return!0;default:return!0}}function GT(y,u="",p=null,_="fill"){if(y==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};Lp(y)||(y=WT(y));const C=y;let M=!0;try{M=function(J){if(!cw(J))return J;let se=lw(J);return z7(se),se=B7(se),se}(C)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(C,null,2)} `)}let L=null,O=null;if(_!=="background"&&_!=="sky"&&_!=="slot"){O=Yt[`filter_${_}`];const J=L0(M,O,u,p);if(J.result==="error")throw new Error(J.value.map(se=>`${se.key}: ${se.message}`).join(", "));L=(se,re,fe)=>J.value.evaluate(se,re,{},fe)}let U=null,W=null;if(M!==C){const J=L0(C,O,u,p);if(J.result==="error")throw new Error(J.value.map(se=>`${se.key}: ${se.message}`).join(", "));U=(se,re,fe,xe,we)=>J.value.evaluate(se,re,{},fe,void 0,void 0,xe,we),W=!q1(J.value.expression)}return{filter:L,dynamicFilter:U||void 0,needGeometry:U7(M),needFeature:!!W}}function B7(y){if(!Array.isArray(y))return y;const u=function(p){if($7.has(p[0])){for(let _=1;_B7(p))}function z7(y){let u=!1;const p=[];if(y[0]==="case"){for(let _=1;_",">=","<","<=","to-boolean"]);function Tye(y,u){return yu?1:0}function U7(y){if(!Array.isArray(y))return!1;if(y[0]==="within"||y[0]==="distance")return!0;for(let u=1;u"||u==="<="||u===">="?KT(y[1],y[2],u):u==="any"?(p=y.slice(1),["any"].concat(p.map(WT))):u==="all"?["all"].concat(y.slice(1).map(WT)):u==="none"?["all"].concat(y.slice(1).map(WT).map(ON)):u==="in"?W1(y[1],y.slice(2)):u==="!in"?ON(W1(y[1],y.slice(2))):u==="has"?RN(y[1]):u!=="!has"||ON(RN(y[1]));var p}function KT(y,u,p){switch(y){case"$type":return[`filter-type-${p}`,u];case"$id":return[`filter-id-${p}`,u];default:return[`filter-${p}`,y,u]}}function W1(y,u){if(u.length===0)return!1;switch(y){case"$type":return["filter-type-in",["literal",u]];case"$id":return["filter-id-in",["literal",u]];default:return u.length>200&&!u.some(p=>typeof p!=typeof u[0])?["filter-in-large",y,["literal",u.sort(Tye)]]:["filter-in-small",y,["literal",u]]}}function RN(y){switch(y){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",y]}}function ON(y){return["!",y]}const tg="";function u6(y,u){return u?`${y}${tg}${u}`:y}function q7(y){const u=y.indexOf(tg);return u>=0?y.slice(u+1):""}let V7;const H7=()=>V7||(V7=new ko({"icon-size":new lr(Yt.layout_symbol["icon-size"]),"icon-image":new lr(Yt.layout_symbol["icon-image"]),"icon-rotate":new lr(Yt.layout_symbol["icon-rotate"]),"icon-offset":new lr(Yt.layout_symbol["icon-offset"]),"text-size":new lr(Yt.layout_symbol["text-size"]),"text-rotate":new lr(Yt.layout_symbol["text-rotate"]),"text-offset":new lr(Yt.layout_symbol["text-offset"])}));let G7;const W7=()=>G7||(G7=new ko({"icon-opacity":new lr(Yt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new lr(Yt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new lr(Yt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new lr(Yt.paint_symbol["text-emissive-strength"]),"icon-color":new lr(Yt.paint_symbol["icon-color"]),"icon-halo-color":new lr(Yt.paint_symbol["icon-halo-color"]),"icon-halo-width":new lr(Yt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new lr(Yt.paint_symbol["icon-halo-blur"]),"icon-translate":new lr(Yt.paint_symbol["icon-translate"]),"text-opacity":new lr(Yt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new lr(Yt.paint_symbol["text-occlusion-opacity"]),"text-color":new lr(Yt.paint_symbol["text-color"],{runtimeType:ah,getOverride:y=>y.textColor,hasOverride:y=>!!y.textColor}),"text-halo-color":new lr(Yt.paint_symbol["text-halo-color"]),"text-halo-width":new lr(Yt.paint_symbol["text-halo-width"]),"text-halo-blur":new lr(Yt.paint_symbol["text-halo-blur"]),"text-translate":new lr(Yt.paint_symbol["text-translate"]),"symbol-z-offset":new lr(Yt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}));class Eye{constructor(u,p,_,C,M,L){this._conditionSpec=u,this._propertiesSpec=_;const O=L0(u,Yt.appearance.condition);if(O.result==="success"&&(this.condition=O.value),this.name=p,_){this.layoutProperties=new py(H7()),this.unevaluatedLayout=new HT(H7(),C,M,L),this.paintProperties=new py(W7()),this.unevaluatedPaint=new HT(W7(),C,M,"");for(const U in _)U in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(U,_[U]):U in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(U,_[U])}}isActive(u){return!(this.condition||!u.isHidden||this.name!=="hidden")||this.condition.evaluate(u.globals,u.feature,u.featureState,u.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(u){return this.layoutProperties.get(u)}getPaintProperty(u){return this.paintProperties.get(u)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(u){return this.unevaluatedLayout._values[u]}getUnevaluatedPaintProperty(u){return this.unevaluatedPaint._values[u]}recalculate(u,p,_){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(u,void 0,p,_)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(u,void 0,p,""))}serialize(){const u={};u.condition=this.condition.expression.serialize(),this.name&&(u.name=this.name);const p=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},_=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},C=Object.assign({},p,_);return Object.keys(C).length>0&&(u.properties=C),u}hasIconLayoutProperties(){const u=this.hasLayoutProperty("icon-image"),p=this.hasLayoutProperty("icon-size"),_=this.hasLayoutProperty("icon-offset"),C=this.hasLayoutProperty("icon-rotate");return u||p||_||C}hasTextLayoutProperties(){const u=this.hasLayoutProperty("text-size"),p=this.hasLayoutProperty("text-offset"),_=this.hasLayoutProperty("text-rotate");return u||p||_}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("icon-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("text-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasLayoutProperty(u){return this.unevaluatedLayout&&this.unevaluatedLayout._values[u].value!==void 0}hasPaintProperty(u){return this.unevaluatedPaint&&this.unevaluatedPaint._values[u].value!==void 0}}const h6="-transition",Aye=new Set(["fill","line","background","hillshade","raster"]);class lh extends Aa{constructor(u,p,_,C,M,L){if(super(),this.id=u.id,this.fqid=u6(this.id,_),this.type=u.type,this.scope=_,this.lut=C,this.options=M,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},u.type!=="custom"){if(this.metadata=u.metadata,this.minzoom=u.minzoom,this.maxzoom=u.maxzoom,u.type&&u.type!=="background"&&u.type!=="sky"&&u.type!=="slot"){this.source=u.source,this.sourceLayer=u["source-layer"],this.filter=u.filter;const O=L0(this.filter,Yt[`filter_${u.type}`]);O.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...O.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||O.value.isIndoorDependent)}if(u.slot&&(this.slot=u.slot),u.appearances&&this.setAppearances(u.appearances),p.layout&&(this._unevaluatedLayout=new HT(p.layout,this.scope,M,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),p.paint){this._transitionablePaint=new LN(p.paint,this.scope,M);for(const O in u.paint)this.setPaintProperty(O,u.paint[O]);for(const O in u.layout)this.setLayoutProperty(O,u.layout[O]);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 py(p.paint)}}}onAdd(u){}onRemove(u){}isDraped(u){return!this.is3D(!0)&&Aye.has(this.type)}getLayoutProperty(u){return u==="visibility"?this.visibility:this._unevaluatedLayout.getValue(u)}setLayoutProperty(u,p){if(this.type==="custom"&&u==="visibility")return void(this.visibility=p);const _=this._unevaluatedLayout;_._properties.properties[u]&&(_.setValue(u,p),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,..._.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||_.isIndoorDependent(),u==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(u){this.appearances=[],u.forEach(p=>{this.appearances.push(new Eye(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(u){return u.endsWith(h6)?this._transitionablePaint.getTransition(u.slice(0,-11)):this._transitionablePaint.getValue(u)}isPaintProperty(u){return!!this._transitionablePaint._properties.properties[u]}setPaintProperty(u,p){const _=this._transitionablePaint,C=_._properties.properties;if(u.endsWith(h6)){const se=u.slice(0,-11);return C[se]&&_.setTransition(se,p||void 0),!1}if(!C[u])return!1;const M=_._values[u],L=M.value.isDataDriven(),O=M.value;_.setValue(u,p),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,..._.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||_.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(u);const U=_._values[u].value,W=U.isDataDriven(),J=u.endsWith("pattern")||u==="line-dasharray";return W||L||J||this._handleOverridablePaintPropertyUpdate(u,O,U)}_handleSpecialPaintPropertyUpdate(u){}getProgramIds(){return null}getDefaultProgramParams(u,p,_){return null}_handleOverridablePaintPropertyUpdate(u,p,_){return!1}isHidden(u){return!!(this.minzoom&&u=this.maxzoom)||this.visibility==="none"}updateTransitions(u){this._transitioningPaint=this._transitionablePaint.transitioned(u,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(u,p){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(u,void 0,p,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(u,void 0,p)}serialize(){const u={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(u.appearances=this.appearances.map(p=>p.serialize())),Kr(u,(p,_)=>!(p===void 0||_==="layout"&&!Object.keys(p).length||_==="paint"&&!Object.keys(p).length))}is3D(u){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const u in this.paint._values){const p=this.paint.get(u);if(p instanceof O0&&MT(p.property.specification)&&(p.value.kind==="source"||p.value.kind==="composite")&&p.value.isStateDependent)return!0}for(const u of this.appearances)if(!Bf(u.condition.expression))return!0;return!1}compileFilter(u){this._filterCompiled||(this._featureFilter=GT(this.filter,this.scope,u),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(u){this._stats&&(u.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(u,p,_){return{}}queryRadius(u){}queryIntersectsFeature(u,p,_,C,M,L,O,U,W,J){}}const Mye={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class FN{constructor(u,p){this._structArray=u,this._pos1=p*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Iye=new ArrayBuffer(0);class Ji{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(u,p){return u._trim(),p&&u.arrayBuffer&&p.add(u.arrayBuffer),{length:u.length,arrayBuffer:u.arrayBuffer}}static deserialize(u){const p=Object.create(this.prototype);return p.arrayBuffer=u.arrayBuffer,p.length=u.length,u.arrayBuffer?p.capacity=u.arrayBuffer.byteLength/p.bytesPerElement:(p.capacity=0,p.arrayBuffer=Iye),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(u){this.reserve(u),this.length=u}reserve(u){if(u>this.capacity){this._reallocCount++,this.capacity=Math.max(u,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const p=this.uint8;this._refreshViews(),p&&this.uint8.set(p)}}reserveForAdditional(u){this.reserve(this.length+u)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...u){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...u){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function fa(y,u=1){let p=0,_=0;return{members:y.map(C=>{const M=Mye[C.type].BYTES_PER_ELEMENT,L=p=xy(p,Math.max(u,M)),O=C.components||1;return _=Math.max(_,M),p+=M*O,{name:C.name,type:C.type,components:O,offset:L}}),size:xy(p,Math.max(_,u)),alignment:u}}function xy(y,u){return Math.ceil(y/u)*u}class zf extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p){const _=this.length;return this.resize(_+1),this.emplace(_,u,p)}emplace(u,p,_){const C=2*u;return this.int16[C+0]=p,this.int16[C+1]=_,u}}zf.prototype.bytesPerElement=4,Mr(zf,"StructArrayLayout2i4");class K1 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,p,_)}emplace(u,p,_,C){const M=3*u;return this.int16[M+0]=p,this.int16[M+1]=_,this.int16[M+2]=C,u}}K1.prototype.bytesPerElement=6,Mr(K1,"StructArrayLayout3i6");class Y1 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,p,_,C)}emplace(u,p,_,C,M){const L=4*u;return this.int16[L+0]=p,this.int16[L+1]=_,this.uint16[L+2]=C,this.uint16[L+3]=M,u}}Y1.prototype.bytesPerElement=8,Mr(Y1,"StructArrayLayout2i2ui8");class Wd extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u){const p=this.length;return this.resize(p+1),this.emplace(p,u)}emplace(u,p){return this.float32[1*u+0]=p,u}}Wd.prototype.bytesPerElement=4,Mr(Wd,"StructArrayLayout1f4");class YT extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,p,_)}emplace(u,p,_,C){const M=4*u,L=2*u;return this.int16[M+0]=p,this.int16[M+1]=_,this.float32[L+1]=C,u}}YT.prototype.bytesPerElement=8,Mr(YT,"StructArrayLayout2i1f8");class BN extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,p,_)}emplace(u,p,_,C){const M=4*u;return this.int16[M+0]=p,this.int16[M+1]=_,this.int16[M+2]=C,u}}BN.prototype.bytesPerElement=8,Mr(BN,"StructArrayLayout3i8");class m6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,p,_,C)}emplace(u,p,_,C,M){const L=4*u;return this.int16[L+0]=p,this.int16[L+1]=_,this.int16[L+2]=C,this.int16[L+3]=M,u}}m6.prototype.bytesPerElement=8,Mr(m6,"StructArrayLayout4i8");class f6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M){const L=this.length;return this.resize(L+1),this.emplace(L,u,p,_,C,M)}emplace(u,p,_,C,M,L){const O=5*u;return this.int16[O+0]=p,this.int16[O+1]=_,this.int16[O+2]=C,this.int16[O+3]=M,this.int16[O+4]=L,u}}f6.prototype.bytesPerElement=10,Mr(f6,"StructArrayLayout5i10");class p6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O){const U=this.length;return this.resize(U+1),this.emplace(U,u,p,_,C,M,L,O)}emplace(u,p,_,C,M,L,O,U){const W=6*u,J=12*u,se=3*u;return this.int16[W+0]=p,this.int16[W+1]=_,this.uint8[J+4]=C,this.uint8[J+5]=M,this.uint8[J+6]=L,this.uint8[J+7]=O,this.float32[se+2]=U,u}}p6.prototype.bytesPerElement=12,Mr(p6,"StructArrayLayout2i4ub1f12");class Zm extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,p,_)}emplace(u,p,_,C){const M=3*u;return this.float32[M+0]=p,this.float32[M+1]=_,this.float32[M+2]=C,u}}Zm.prototype.bytesPerElement=12,Mr(Zm,"StructArrayLayout3f12");class B0 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M){const L=this.length;return this.resize(L+1),this.emplace(L,u,p,_,C,M)}emplace(u,p,_,C,M,L){const O=6*u,U=3*u;return this.uint16[O+0]=p,this.uint16[O+1]=_,this.uint16[O+2]=C,this.uint16[O+3]=M,this.float32[U+2]=L,u}}B0.prototype.bytesPerElement=12,Mr(B0,"StructArrayLayout4ui1f12");class dw extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,p,_,C)}emplace(u,p,_,C,M){const L=4*u;return this.uint16[L+0]=p,this.uint16[L+1]=_,this.uint16[L+2]=C,this.uint16[L+3]=M,u}}dw.prototype.bytesPerElement=8,Mr(dw,"StructArrayLayout4ui8");class ZT extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L){const O=this.length;return this.resize(O+1),this.emplace(O,u,p,_,C,M,L)}emplace(u,p,_,C,M,L,O){const U=6*u;return this.int16[U+0]=p,this.int16[U+1]=_,this.int16[U+2]=C,this.int16[U+3]=M,this.int16[U+4]=L,this.int16[U+5]=O,u}}ZT.prototype.bytesPerElement=12,Mr(ZT,"StructArrayLayout6i12");class x6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se,re){const fe=this.length;return this.resize(fe+1),this.emplace(fe,u,p,_,C,M,L,O,U,W,J,se,re)}emplace(u,p,_,C,M,L,O,U,W,J,se,re,fe){const xe=12*u;return this.int16[xe+0]=p,this.int16[xe+1]=_,this.int16[xe+2]=C,this.int16[xe+3]=M,this.uint16[xe+4]=L,this.uint16[xe+5]=O,this.uint16[xe+6]=U,this.uint16[xe+7]=W,this.int16[xe+8]=J,this.int16[xe+9]=se,this.int16[xe+10]=re,this.int16[xe+11]=fe,u}}x6.prototype.bytesPerElement=24,Mr(x6,"StructArrayLayout4i4ui4i24");class g6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L){const O=this.length;return this.resize(O+1),this.emplace(O,u,p,_,C,M,L)}emplace(u,p,_,C,M,L,O){const U=10*u,W=5*u;return this.int16[U+0]=p,this.int16[U+1]=_,this.int16[U+2]=C,this.float32[W+2]=M,this.float32[W+3]=L,this.float32[W+4]=O,u}}g6.prototype.bytesPerElement=20,Mr(g6,"StructArrayLayout3i3f20");class gy extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,p,_,C)}emplace(u,p,_,C,M){const L=4*u;return this.float32[L+0]=p,this.float32[L+1]=_,this.float32[L+2]=C,this.float32[L+3]=M,u}}gy.prototype.bytesPerElement=16,Mr(gy,"StructArrayLayout4f16");class XT extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(u){const p=this.length;return this.resize(p+1),this.emplace(p,u)}emplace(u,p){return this.uint32[1*u+0]=p,u}}XT.prototype.bytesPerElement=4,Mr(XT,"StructArrayLayout1ul4");class Bh extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p){const _=this.length;return this.resize(_+1),this.emplace(_,u,p)}emplace(u,p,_){const C=2*u;return this.uint16[C+0]=p,this.uint16[C+1]=_,u}}Bh.prototype.bytesPerElement=4,Mr(Bh,"StructArrayLayout2ui4");class y6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se,re,fe){const xe=this.length;return this.resize(xe+1),this.emplace(xe,u,p,_,C,M,L,O,U,W,J,se,re,fe)}emplace(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe){const we=20*u,je=10*u;return this.int16[we+0]=p,this.int16[we+1]=_,this.int16[we+2]=C,this.int16[we+3]=M,this.int16[we+4]=L,this.float32[je+3]=O,this.float32[je+4]=U,this.float32[je+5]=W,this.float32[je+6]=J,this.int16[we+14]=se,this.uint32[je+8]=re,this.uint16[we+18]=fe,this.uint16[we+19]=xe,u}}y6.prototype.bytesPerElement=40,Mr(y6,"StructArrayLayout5i4f1i1ul2ui40");class QT extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O){const U=this.length;return this.resize(U+1),this.emplace(U,u,p,_,C,M,L,O)}emplace(u,p,_,C,M,L,O,U){const W=8*u;return this.int16[W+0]=p,this.int16[W+1]=_,this.int16[W+2]=C,this.int16[W+4]=M,this.int16[W+5]=L,this.int16[W+6]=O,this.int16[W+7]=U,u}}QT.prototype.bytesPerElement=16,Mr(QT,"StructArrayLayout3i2i2i16");class sg extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M){const L=this.length;return this.resize(L+1),this.emplace(L,u,p,_,C,M)}emplace(u,p,_,C,M,L){const O=4*u,U=8*u;return this.float32[O+0]=p,this.float32[O+1]=_,this.float32[O+2]=C,this.int16[U+6]=M,this.int16[U+7]=L,u}}sg.prototype.bytesPerElement=16,Mr(sg,"StructArrayLayout2f1f2i16");class JT extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L){const O=this.length;return this.resize(O+1),this.emplace(O,u,p,_,C,M,L)}emplace(u,p,_,C,M,L,O){const U=20*u,W=5*u;return this.uint8[U+0]=p,this.uint8[U+1]=_,this.float32[W+1]=C,this.float32[W+2]=M,this.float32[W+3]=L,this.float32[W+4]=O,u}}JT.prototype.bytesPerElement=20,Mr(JT,"StructArrayLayout2ub4f20");class Go extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,p,_)}emplace(u,p,_,C){const M=3*u;return this.uint16[M+0]=p,this.uint16[M+1]=_,this.uint16[M+2]=C,u}}Go.prototype.bytesPerElement=6,Mr(Go,"StructArrayLayout3ui6");class v6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot){const pt=this.length;return this.resize(pt+1),this.emplace(pt,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot)}emplace(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot,pt){const Rt=30*u,_t=15*u,Et=60*u;return this.int16[Rt+0]=p,this.int16[Rt+1]=_,this.int16[Rt+2]=C,this.float32[_t+2]=M,this.float32[_t+3]=L,this.uint16[Rt+8]=O,this.uint16[Rt+9]=U,this.uint32[_t+5]=W,this.uint32[_t+6]=J,this.uint32[_t+7]=se,this.uint16[Rt+16]=re,this.uint16[Rt+17]=fe,this.uint16[Rt+18]=xe,this.float32[_t+10]=we,this.float32[_t+11]=je,this.uint8[Et+48]=Be,this.uint8[Et+49]=Ye,this.uint8[Et+50]=Ue,this.uint32[_t+13]=tt,this.int16[Rt+28]=ot,this.uint8[Et+58]=pt,u}}v6.prototype.bytesPerElement=60,Mr(v6,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class b6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot,pt,Rt,_t,Et,jt,At,ns,is,xs,ks,ws,Ks){const ds=this.length;return this.resize(ds+1),this.emplace(ds,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot,pt,Rt,_t,Et,jt,At,ns,is,xs,ks,ws,Ks)}emplace(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot,pt,Rt,_t,Et,jt,At,ns,is,xs,ks,ws,Ks,ds){const gs=20*u,Cs=40*u,Bs=80*u;return this.float32[gs+0]=p,this.float32[gs+1]=_,this.int16[Cs+4]=C,this.int16[Cs+5]=M,this.int16[Cs+6]=L,this.int16[Cs+7]=O,this.int16[Cs+8]=U,this.int16[Cs+9]=W,this.int16[Cs+10]=J,this.int16[Cs+11]=se,this.int16[Cs+12]=re,this.uint16[Cs+13]=fe,this.uint16[Cs+14]=xe,this.uint16[Cs+15]=we,this.uint16[Cs+16]=je,this.uint16[Cs+17]=Be,this.uint16[Cs+18]=Ye,this.uint16[Cs+19]=Ue,this.uint16[Cs+20]=tt,this.uint16[Cs+21]=ot,this.uint16[Cs+22]=pt,this.uint16[Cs+23]=Rt,this.uint16[Cs+24]=_t,this.uint16[Cs+25]=Et,this.uint16[Cs+26]=jt,this.uint16[Cs+27]=At,this.uint32[gs+14]=ns,this.float32[gs+15]=is,this.float32[gs+16]=xs,this.float32[gs+17]=ks,this.float32[gs+18]=ws,this.uint8[Bs+76]=Ks,this.uint16[Cs+39]=ds,u}}b6.prototype.bytesPerElement=80,Mr(b6,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class _6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L){const O=this.length;return this.resize(O+1),this.emplace(O,u,p,_,C,M,L)}emplace(u,p,_,C,M,L,O){const U=6*u;return this.float32[U+0]=p,this.float32[U+1]=_,this.float32[U+2]=C,this.float32[U+3]=M,this.float32[U+4]=L,this.float32[U+5]=O,u}}_6.prototype.bytesPerElement=24,Mr(_6,"StructArrayLayout6f24");class Z1 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M){const L=this.length;return this.resize(L+1),this.emplace(L,u,p,_,C,M)}emplace(u,p,_,C,M,L){const O=5*u;return this.float32[O+0]=p,this.float32[O+1]=_,this.float32[O+2]=C,this.float32[O+3]=M,this.float32[O+4]=L,u}}Z1.prototype.bytesPerElement=20,Mr(Z1,"StructArrayLayout5f20");class w6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O){const U=this.length;return this.resize(U+1),this.emplace(U,u,p,_,C,M,L,O)}emplace(u,p,_,C,M,L,O,U){const W=7*u;return this.float32[W+0]=p,this.float32[W+1]=_,this.float32[W+2]=C,this.float32[W+3]=M,this.float32[W+4]=L,this.float32[W+5]=O,this.float32[W+6]=U,u}}w6.prototype.bytesPerElement=28,Mr(w6,"StructArrayLayout7f28");class zh extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se){const re=this.length;return this.resize(re+1),this.emplace(re,u,p,_,C,M,L,O,U,W,J,se)}emplace(u,p,_,C,M,L,O,U,W,J,se,re){const fe=11*u;return this.float32[fe+0]=p,this.float32[fe+1]=_,this.float32[fe+2]=C,this.float32[fe+3]=M,this.float32[fe+4]=L,this.float32[fe+5]=O,this.float32[fe+6]=U,this.float32[fe+7]=W,this.float32[fe+8]=J,this.float32[fe+9]=se,this.float32[fe+10]=re,u}}zh.prototype.bytesPerElement=44,Mr(zh,"StructArrayLayout11f44");class $f extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W){const J=this.length;return this.resize(J+1),this.emplace(J,u,p,_,C,M,L,O,U,W)}emplace(u,p,_,C,M,L,O,U,W,J){const se=9*u;return this.float32[se+0]=p,this.float32[se+1]=_,this.float32[se+2]=C,this.float32[se+3]=M,this.float32[se+4]=L,this.float32[se+5]=O,this.float32[se+6]=U,this.float32[se+7]=W,this.float32[se+8]=J,u}}$f.prototype.bytesPerElement=36,Mr($f,"StructArrayLayout9f36");class z0 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p){const _=this.length;return this.resize(_+1),this.emplace(_,u,p)}emplace(u,p,_){const C=2*u;return this.float32[C+0]=p,this.float32[C+1]=_,u}}z0.prototype.bytesPerElement=8,Mr(z0,"StructArrayLayout2f8");class j6 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,p,_,C)}emplace(u,p,_,C,M){const L=6*u;return this.uint32[3*u+0]=p,this.uint16[L+2]=_,this.uint16[L+3]=C,this.uint16[L+4]=M,u}}j6.prototype.bytesPerElement=12,Mr(j6,"StructArrayLayout1ul3ui12");class yy extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u){const p=this.length;return this.resize(p+1),this.emplace(p,u)}emplace(u,p){return this.uint16[1*u+0]=p,u}}yy.prototype.bytesPerElement=2,Mr(yy,"StructArrayLayout1ui2");class eE extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je){const Be=this.length;return this.resize(Be+1),this.emplace(Be,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je)}emplace(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be){const Ye=16*u;return this.float32[Ye+0]=p,this.float32[Ye+1]=_,this.float32[Ye+2]=C,this.float32[Ye+3]=M,this.float32[Ye+4]=L,this.float32[Ye+5]=O,this.float32[Ye+6]=U,this.float32[Ye+7]=W,this.float32[Ye+8]=J,this.float32[Ye+9]=se,this.float32[Ye+10]=re,this.float32[Ye+11]=fe,this.float32[Ye+12]=xe,this.float32[Ye+13]=we,this.float32[Ye+14]=je,this.float32[Ye+15]=Be,u}}eE.prototype.bytesPerElement=64,Mr(eE,"StructArrayLayout16f64");class X1 extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,p,_,C,M,L,O){const U=this.length;return this.resize(U+1),this.emplace(U,u,p,_,C,M,L,O)}emplace(u,p,_,C,M,L,O,U){const W=10*u,J=5*u;return this.uint16[W+0]=p,this.uint16[W+1]=_,this.uint16[W+2]=C,this.uint16[W+3]=M,this.float32[J+2]=L,this.float32[J+3]=O,this.float32[J+4]=U,u}}X1.prototype.bytesPerElement=20,Mr(X1,"StructArrayLayout4ui3f20");class uw extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u){const p=this.length;return this.resize(p+1),this.emplace(p,u)}emplace(u,p){return this.int16[1*u+0]=p,u}}uw.prototype.bytesPerElement=2,Mr(uw,"StructArrayLayout1i2");class zN extends Ji{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(u){const p=this.length;return this.resize(p+1),this.emplace(p,u)}emplace(u,p){return this.uint8[1*u+0]=p,u}}zN.prototype.bytesPerElement=1,Mr(zN,"StructArrayLayout1ub1");class tE extends FN{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]}}tE.prototype.size=40;class Q1 extends y6{get(u){return new tE(this,u)}}Mr(Q1,"CollisionBoxArray");class N6 extends FN{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(u){this._structArray.uint8[this._pos1+49]=u}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(u){this._structArray.uint8[this._pos1+50]=u}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(u){this._structArray.uint32[this._pos4+13]=u}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(u){this._structArray.uint8[this._pos1+58]=u}}N6.prototype.size=60;class K7 extends v6{get(u){return new N6(this,u)}}Mr(K7,"PlacedSymbolArray");class Y7 extends FN{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(u){this._structArray.uint32[this._pos4+14]=u}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(u){this._structArray.float32[this._pos4+18]=u}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}Y7.prototype.size=80;class k6 extends b6{get(u){return new Y7(this,u)}}Mr(k6,"SymbolInstanceArray");class Z7 extends Wd{getoffsetX(u){return this.float32[1*u+0]}}Mr(Z7,"GlyphOffsetArray");class Dp extends zf{getx(u){return this.int16[2*u+0]}gety(u){return this.int16[2*u+1]}}Mr(Dp,"SymbolLineVertexArray");class X7 extends FN{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]}}X7.prototype.size=12;class S6 extends j6{get(u){return new X7(this,u)}}Mr(S6,"FeatureIndexArray");class Q7 extends Bh{geta_centroid_pos0(u){return this.uint16[2*u+0]}geta_centroid_pos1(u){return this.uint16[2*u+1]}}Mr(Q7,"FillExtrusionCentroidArray");class J7 extends FN{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]}}J7.prototype.size=6;class e9 extends K1{get(u){return new J7(this,u)}}Mr(e9,"FillExtrusionWallArray");const Pye=fa([{name:"a_pos",components:2,type:"Int16"}],4),Lye=fa([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),Dye=fa([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Gi{constructor(u=[]){this.segments=u}_prepareSegment(u,p,_,C,M){let L=this.segments.at(-1);return u>Gi.MAX_VERTEX_ARRAY_LENGTH&&ra(`Max vertices per segment is ${Gi.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${u}`),(!L||L.vertexLength+u>Gi.MAX_VERTEX_ARRAY_LENGTH||L.sortKey!==C||M!==void 0&&L&&L.batchIndex!==void 0&&L.batchIndex!==M)&&(L={vertexOffset:p,primitiveOffset:_,vertexLength:0,primitiveLength:0},C!==void 0&&(L.sortKey=C),M!==void 0&&(L.batchIndex=M),this.segments.push(L)),L}prepareSegment(u,p,_,C,M){return this._prepareSegment(u,p.length,_.length,C,M)}get(){return this.segments}destroy(){for(const u of this.segments)for(const p in u.vaos)u.vaos[p].destroy()}static simpleSegment(u,p,_,C){return new Gi([{vertexOffset:u,primitiveOffset:p,vertexLength:_,primitiveLength:C,vaos:{},sortKey:0}])}}function hw(y,u){return 256*(y=Mt(Math.floor(y),0,255))+Mt(Math.floor(u),0,255)}Gi.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Mr(Gi,"SegmentVector");const sE=fa([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),C6=fa([{name:"a_pattern_b",components:4,type:"Uint16"}]),t9=fa([{name:"a_dash",components:4,type:"Uint16"}]);class mw{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(u,p,_,C){this.ids.push(s9(u)),this.positions.push(p,_,C)}eachPosition(u,p){const _=s9(u);let C=0,M=this.ids.length-1;for(;C>1;this.ids[L]>=_?M=L:C=L+1}for(;this.ids[C]===_;)p(this.positions[3*C],this.positions[3*C+1],this.positions[3*C+2]),C++}static serialize(u,p){const _=new Float64Array(u.ids),C=new Uint32Array(u.positions);return rE(_,C,0,_.length-1),p&&(p.add(_.buffer),p.add(C.buffer)),{ids:_,positions:C}}static deserialize(u){const p=new mw;let _;p.ids=u.ids,p.positions=u.positions;for(const C of p.ids)C!==_&&p.uniqueIds.push(C),_=C;return p.indexed=!0,p}}function s9(y){const u=+y;return Number.isSafeInteger(u)?u:It(String(y))}function rE(y,u,p,_){for(;p<_;){const C=y[p+_>>1];let M=p-1,L=_+1;for(;;){do M++;while(y[M]C);if(M>=L)break;nE(y,M,L),nE(u,3*M,3*L),nE(u,3*M+1,3*L+1),nE(u,3*M+2,3*L+2)}L-p<_-L?(rE(y,u,p,L),p=L+1):(rE(y,u,L+1,_),_=L)}}function nE(y,u,p){const _=y[u];y[u]=y[p],y[p]=_}Mr(mw,"FeaturePositionMap");class rg{constructor(u){this.gl=u.gl,this.initialized=!1}fetchUniformLocation(u,p){return this.location||this.initialized||(this.location=this.gl.getUniformLocation(u,p),this.initialized=!0),!!this.location}set(u,p,_){throw new Error("Uniform#set() must be implemented by each concrete Uniform")}}class $N extends rg{constructor(u){super(u),this.current=0}set(u,p,_){this.fetchUniformLocation(u,p)&&this.current!==_&&(this.current=_,this.gl.uniform1i(this.location,_))}}class wl extends rg{constructor(u){super(u),this.current=0}set(u,p,_){this.fetchUniformLocation(u,p)&&this.current!==_&&(this.current=_,this.gl.uniform1f(this.location,_))}}class Uf extends rg{constructor(u){super(u),this.current=[0,0]}set(u,p,_){this.fetchUniformLocation(u,p)&&(_[0]===this.current[0]&&_[1]===this.current[1]||(this.current=_,this.gl.uniform2f(this.location,_[0],_[1])))}}class UN extends rg{constructor(u){super(u),this.current=[0,0,0]}set(u,p,_){this.fetchUniformLocation(u,p)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]||(this.current=_,this.gl.uniform3f(this.location,_[0],_[1],_[2])))}}class Rye extends rg{constructor(u){super(u),this.current=[0,0,0,0]}set(u,p,_){this.fetchUniformLocation(u,p)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]&&_[3]===this.current[3]||(this.current=_,this.gl.uniform4ui(this.location,_[0],_[1],_[2],_[3])))}}class T6 extends rg{constructor(u){super(u),this.current=[0,0,0,0]}set(u,p,_){this.fetchUniformLocation(u,p)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]&&_[3]===this.current[3]||(this.current=_,this.gl.uniform4f(this.location,_[0],_[1],_[2],_[3])))}}class r9 extends rg{constructor(u){super(u),this.current=Wa.transparent.toPremultipliedRenderColor(null)}set(u,p,_){this.fetchUniformLocation(u,p)&&(_.r===this.current.r&&_.g===this.current.g&&_.b===this.current.b&&_.a===this.current.a||(this.current=_,this.gl.uniform4f(this.location,_.r,_.g,_.b,_.a)))}}class $0 extends rg{constructor(u){super(u),this.current=new Float32Array(16)}set(u,p,_){if(!this.fetchUniformLocation(u,p))return;const C=this.current;if(_[12]!==C[12]||_[0]!==C[0])return C.set(_),void this.gl.uniformMatrix4fv(this.location,!1,C);for(let M=1;M<16;M++)if(_[M]!==C[M]){C.set(_),this.gl.uniformMatrix4fv(this.location,!1,C);break}}}class fw extends rg{constructor(u){super(u),this.current=new Float32Array(4)}set(u,p,_){if(!this.fetchUniformLocation(u,p))return;const C=this.current;for(let M=0;M<4;M++)if(_[M]!==C[M]){C.set(_),this.gl.uniformMatrix2fv(this.location,!1,C);break}}}function $h(y){return[hw(255*y.r,255*y.g),hw(255*y.b,255*y.a)]}function J1(y,u,p,_,C,M,L,O){return!!y&&(y.kind==="composite"||y.kind==="source"?y.evaluate(new fi(0,{brightness:M,worldview:O}),u,p,C,_,L)==="none":y.value==="none")}class aE{constructor(u,p,_,C){this.value=u,this.uniformNames=p.map(M=>`u_${M}`),this.type=_,this.context=C}setUniform(u,p,_,C,M){const L=C.constantOr(this.value);p.set(u,M,L instanceof Wa?L.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):L)}getBinding(u,p){return this.type==="color"?new r9(u):new wl(u)}}class qN{constructor(u,p){this.uniformNames=p.map(_=>`u_${_}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(u,p){this.pixelRatio=u.pixelRatio||1,this.pattern=u.tl.concat(u.br),this.patternTransition=p?p.tl.concat(p.br):this.pattern}setUniform(u,p,_,C,M){let L=null;M!=="u_pattern"&&M!=="u_dash"||(L=this.pattern),M==="u_pattern_b"&&(L=this.patternTransition),M==="u_pixel_ratio"&&(L=this.pixelRatio),L&&p.set(u,M,L)}getBinding(u,p){return p==="u_pattern"||p==="u_pattern_b"||p==="u_dash"?new Rye(u):new wl(u)}}class vy{constructor(u,p,_,C){this.expression=u,this.type=_,this.maxValue=0,this.paintVertexAttributes=p.map(M=>({name:`a_${M}`,type:"Float32",components:_==="color"?2:1,offset:0})),this.paintVertexArray=new C}populatePaintArray(u,p,_,C,M,L,O,U){const W=this.paintVertexArray.length,J=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new fi(0,{brightness:L,worldview:U}),p,{},M,C,O):this.expression.kind==="constant"&&this.expression.value,se=J1(this.lutExpression,p,{},C,M,L,O,U);this.paintVertexArray.resize(u),this._setPaintValue(W,u,J,se?null:this.context.lut)}updatePaintArray(u,p,_,C,M,L,O,U){const W=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:O,worldview:U},_,C,void 0,M):this.expression.kind==="constant"&&this.expression.value,J=J1(this.lutExpression,_,C,M,void 0,O,void 0,U);this._setPaintValue(u,p,W,J?null:this.context.lut)}_setPaintValue(u,p,_,C){if(this.type==="color"){const M=$h(_.toPremultipliedRenderColor(C));for(let L=u;L`u_${O}_t`),this.type=_,this.useIntegerZoom=C,this.context=M,this.maxValue=0,this.paintVertexAttributes=p.map(O=>({name:`a_${O}`,type:"Float32",components:_==="color"?4:2,offset:0})),this.paintVertexArray=new L}populatePaintArray(u,p,_,C,M,L,O,U){const W=this.expression.evaluate(new fi(this.context.zoom,{brightness:L,worldview:U}),p,{},M,C,O),J=this.expression.evaluate(new fi(this.context.zoom+1,{brightness:L,worldview:U}),p,{},M,C,O),se=J1(this.lutExpression,p,{},C,M,L,O,U),re=this.paintVertexArray.length;this.paintVertexArray.resize(u),this._setPaintValue(re,u,W,J,se?null:this.context.lut)}updatePaintArray(u,p,_,C,M,L,O,U){const W=this.expression.evaluate({zoom:this.context.zoom,brightness:O,worldview:U},_,C,void 0,M),J=this.expression.evaluate({zoom:this.context.zoom+1,brightness:O,worldview:U},_,C,void 0,M),se=J1(this.lutExpression,_,C,M,void 0,O,void 0,U);this._setPaintValue(u,p,W,J,se?null:this.context.lut)}_setPaintValue(u,p,_,C,M){if(this.type==="color"){const L=$h(_.toPremultipliedRenderColor(M)),O=$h(C.toPremultipliedRenderColor(M));for(let U=u;U!0){this.binders={},this._buffers=[],this.context=p;const C=[],M=u;for(const L in u.paint._values){const O=M.paint.get(L);if(L.endsWith("-use-theme")||!_(L)||!(O instanceof O0&&MT(O.property.specification)))continue;const U=Fye(L,u.type),W=O.value,J=O.property.specification.type,se=!!O.property.useIntegerZoom,re=L==="line-dasharray"||L.endsWith("pattern"),fe=M.paint.get(`${L}-use-theme`),xe=L==="line-dasharray"&&M.layout.get("line-cap").value.kind!=="constant"||fe&&fe.value.kind!=="constant";if(W.kind!=="constant"||xe)if(W.kind==="source"||xe||re){const we=E6(L,J,"source");this.binders[L]=re?new qf(W,U,J,we,u.id):new vy(W,U,J,we),C.push(`/a_${L}`)}else{const we=E6(L,J,"composite");this.binders[L]=new ng(W,U,J,se,p,we),C.push(`/z_${L}`)}else this.binders[L]=re?new qN(W.value,U):new aE(W.value,U,J,p),C.push(`/u_${L}`);fe&&(this.binders[L].lutExpression=fe.value)}this.cacheKey=C.sort().join("")}updateExpressions(u){const p=u;for(const _ in this.binders){const C=this.binders[_];if(C instanceof vy||C instanceof ng||C instanceof qf){const M=p.paint.get(_);C.expression=M.value}}}getMaxValue(u){const p=this.binders[u];return p instanceof vy||p instanceof ng?p.maxValue:0}populatePaintArrays(u,p,_,C,M,L,O,U){for(const W in this.binders){const J=this.binders[W];J.context=this.context,(J instanceof vy||J instanceof ng||J instanceof qf)&&J.populatePaintArray(u,p,_,C,M,L,O,U)}}setConstantPatternPositions(u,p){for(const _ in this.binders){const C=this.binders[_];C instanceof qN&&C.setConstantPatternPositions(u,p)}}getPatternTransitionVertexBuffer(u){const p=this.binders[u];return p instanceof qf?p.paintTransitionVertexBuffer:null}updatePaintArrays(u,p,_,C,M,L,O,U,W,J){let se=!1;const re=Object.keys(u),fe=re.length!==0&&!U,xe=fe?re:p.uniqueIds;this.context.lut=M.lut;for(const we in this.binders){const je=this.binders[we];if(je.context=this.context,(je instanceof vy||je instanceof ng||je instanceof qf)&&je.expression&&je.expression.kind&&je.expression.kind!=="constant"&&(je.expression.isStateDependent===!0||je.expression.isLightConstant===!1)){const Be=M.paint.get(we);je.expression=Be.value;for(const Ye of xe){const Ue=u[Ye.toString()];p.eachPosition(Ye,(tt,ot,pt)=>{const Rt=C.feature(tt);je.updatePaintArray(ot,pt,Rt,Ue,L,O,W,J)})}if(!fe)for(const Ye of _.uniqueIds){const Ue=u[Ye.toString()];_.eachPosition(Ye,(tt,ot,pt)=>{const Rt=C.feature(tt);je.updatePaintArray(ot,pt,Rt,Ue,L,O,W,J)})}se=!0}}return se}defines(){const u=[];for(const p in this.binders){const _=this.binders[p];(_ instanceof aE||_ instanceof qN)&&u.push(..._.uniformNames.map(C=>`#define HAS_UNIFORM_${C}`))}return u}getPaintVertexBuffers(){return this._buffers}getUniforms(u){const p=[];for(const _ in this.binders){const C=this.binders[_];if(C instanceof aE||C instanceof qN||C instanceof ng)for(const M of C.uniformNames)p.push({name:M,property:_,binding:C.getBinding(u,M)})}return p}setUniforms(u,p,_,C,M){for(const{name:L,property:O,binding:U}of _)this.binders[O].setUniform(u,U,M,C.get(O),L)}updatePaintBuffers(){this._buffers=[];for(const u in this.binders){const p=this.binders[u];(p instanceof vy||p instanceof ng||p instanceof qf)&&p.paintVertexBuffer&&this._buffers.push(p.paintVertexBuffer),p instanceof qf&&p.paintTransitionVertexBuffer&&this._buffers.push(p.paintTransitionVertexBuffer)}}upload(u){for(const p in this.binders){const _=this.binders[p];(_ instanceof vy||_ instanceof ng||_ instanceof qf)&&_.upload(u)}this.updatePaintBuffers()}destroy(){for(const u in this.binders){const p=this.binders[u];(p instanceof vy||p instanceof ng||p instanceof qf)&&p.destroy()}}}class Xm{constructor(u,p,_=()=>!0){this.programConfigurations={};for(const C of u)this.programConfigurations[C.id]=new eb(C,p,_);this.needsUpload=!1,this._featureMap=new mw,this._featureMapWithoutIds=new mw,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(u,p,_,C,M,L,O,U,W){for(const J in this.programConfigurations)this.programConfigurations[J].populatePaintArrays(u,p,C,M,L,O,U,W);p.id!==void 0?this._featureMap.add(p.id,_,this._bufferOffset,u):(this._featureMapWithoutIds.add(this._idlessCounter,_,this._bufferOffset,u),this._idlessCounter+=1),this._bufferOffset=u,this.needsUpload=!0}updatePaintArrays(u,p,_,C,M,L,O,U){for(const W of _)this.needsUpload=this.programConfigurations[W.id].updatePaintArrays(u,this._featureMap,this._featureMapWithoutIds,p,W,C,M,L,O||0,U)||this.needsUpload}get(u){return this.programConfigurations[u]}upload(u){if(this.needsUpload){for(const p in this.programConfigurations)this.programConfigurations[p].upload(u);this.needsUpload=!1}}destroy(){for(const u in this.programConfigurations)this.programConfigurations[u].destroy()}updateExpressions(u){const p=new Set;for(const _ of u){const C=this.programConfigurations[_.id];C&&(C.updateExpressions(_),p.add(_.id))}for(const _ in this.programConfigurations)p.has(_)||delete this.programConfigurations[_]}}const Oye={"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 Fye(y,u){return Oye[y]||[y.replace(`${u}-`,"").replace(/-/g,"_")]}const Bye={"line-pattern":{source:B0,composite:B0},"fill-pattern":{source:B0,composite:B0},"fill-extrusion-pattern":{source:B0,composite:B0},"line-dasharray":{source:dw,composite:dw}},zye={color:{source:z0,composite:gy},number:{source:Wd,composite:z0}};function E6(y,u,p){const _=Bye[y];return _&&_[p]||zye[u][p]}Mr(aE,"ConstantBinder"),Mr(qN,"PatternConstantBinder"),Mr(vy,"SourceExpressionBinder",{omit:["expression"]}),Mr(qf,"PatternCompositeBinder",{omit:["expression"]}),Mr(ng,"CompositeExpressionBinder",{omit:["expression"]}),Mr(eb,"ProgramConfiguration",{omit:["_buffers"]}),Mr(Xm,"ProgramConfigurationSet");const mu=mr/Math.PI/2,pw=64,iE=[pw,32,16],Qm=-mu,Vf=mu;function U0(y,u,p,_=mu){return p=We(p),[y*Math.sin(p)*_,-u*_,y*Math.cos(p)*_]}function ag(y,u,p){return U0(Math.cos(We(y)),Math.sin(We(y)),u,p)}const tb=63710088e-1,A6=2*Math.PI*tb;class di{constructor(u,p){if(isNaN(u)||isNaN(p))throw new Error(`Invalid LngLat object: (${u}, ${p})`);if(this.lng=+u,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 di(Es(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(u){const p=Math.PI/180,_=this.lat*p,C=u.lat*p,M=Math.sin(_)*Math.sin(C)+Math.cos(_)*Math.cos(C)*Math.cos((u.lng-this.lng)*p);return tb*Math.acos(Math.min(M,1))}toBounds(u=0){const p=360*u/40075017,_=p/Math.cos(Math.PI/180*this.lat);return new q0({lng:this.lng-_,lat:this.lat-p},{lng:this.lng+_,lat:this.lat+p})}toEcef(u){return ag(this.lat,this.lng,mu+u*mu/tb)}static convert(u){if(u instanceof di)return u;if(Array.isArray(u)&&(u.length===2||u.length===3))return new di(Number(u[0]),Number(u[1]));if(!Array.isArray(u)&&typeof u=="object"&&u!==null)return new di(Number("lng"in u?u.lng:u.lon),Number(u.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class q0{constructor(u,p){u&&(p?this.setSouthWest(u).setNorthEast(p):Array.isArray(u)&&u.length===4?this.setSouthWest([u[0],u[1]]).setNorthEast([u[2],u[3]]):this.setSouthWest(u[0]).setNorthEast(u[1]))}setNorthEast(u){return this._ne=u instanceof di?new di(u.lng,u.lat):di.convert(u),this}setSouthWest(u){return this._sw=u instanceof di?new di(u.lng,u.lat):di.convert(u),this}extend(u){const p=this._sw,_=this._ne;let C,M;if(u instanceof di)C=u,M=u;else{if(!(u instanceof q0))return Array.isArray(u)?u.length===4||u.every(Array.isArray)?this.extend(q0.convert(u)):this.extend(di.convert(u)):typeof u=="object"&&u!==null&&Object.hasOwn(u,"lat")&&(Object.hasOwn(u,"lon")||Object.hasOwn(u,"lng"))?this.extend(di.convert(u)):this;if(C=u._sw,M=u._ne,!C||!M)return this}return p||_?(p.lng=Math.min(C.lng,p.lng),p.lat=Math.min(C.lat,p.lat),_.lng=Math.max(M.lng,_.lng),_.lat=Math.max(M.lat,_.lat)):(this._sw=new di(C.lng,C.lat),this._ne=new di(M.lng,M.lat)),this}getCenter(){return new di((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 di(this.getWest(),this.getNorth())}getSouthEast(){return new di(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(u){const{lng:p,lat:_}=di.convert(u);let C=this._sw.lng<=p&&p<=this._ne.lng;return this._sw.lng>this._ne.lng&&(C=this._sw.lng>=p&&p>=this._ne.lng),this._sw.lat<=_&&_<=this._ne.lat&&C}static convert(u){if(u)return u instanceof q0?u:new q0(u)}}function VN(y){return A6*Math.cos(y*Math.PI/180)}function by(y){return(180+y)/360}function ig(y){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+y*Math.PI/360)))/360}function ch(y,u){return y/VN(u)}function ym(y){return 360*y-180}function Xc(y){return 360/Math.PI*Math.atan(Math.exp((180-360*y)*Math.PI/180))-90}function M6(y,u){return y*VN(Xc(u))}const vm=85.051129;function n9(y){return Math.cos(We(Mt(y,-85.051129,vm)))}function sb(y,u){const p=Mt(u,0,25.5),_=Math.pow(2,p);return n9(y)*A6/(512*_)}function a9(y){return 1/Math.cos(y*Math.PI/180)}function Jm(y,u=0){const p=Math.exp(Math.PI*(1-(y.y+u/mr)/(1<=U?(I6(y,u,p,W,J,M,se,O,U),I6(y,W,J,_,C,se,L,O,U)):y.push(L)}function i9(y,u,p){let _=y[0],C=_.x,M=_.y;u(_);const L=[_];for(let O=1;Oy.x+1||_y.y+1)&&ra("Geometry exceeds allowed extent, reduce your vector tile buffer size"),y}function bm(y,u,p){const _=y.loadGeometry(),C=y.extent,M=mr/C;if(u&&p&&p.projection.isReprojectedInTileSpace){const L=1<{const fe=ym((u.x+re.x/C)/L),xe=Xc((u.y+re.y/C)/L),we=J.project(fe,xe);re.x=(we.x*O-U)*C,re.y=(we.y*O-W)*C};for(let re=0;re<_.length;re++)if(y.type!==1)_[re]=i9(_[re],se,1);else{const fe=[];for(const xe of _[re])xe.x<0||xe.x>=C||xe.y<0||xe.y>=C||(se(xe),fe.push(xe));_[re]=fe}}for(const L of _)for(const O of L)Uye(O,M);return _}function Hf(y,u){return{type:y.type,id:y.id,properties:y.properties,geometry:u?bm(y):[]}}class V0{constructor(u,p,_,C,M){this.properties={},this.extent=_,this.type=0,this.id=void 0,this._pbf=u,this._geometry=-1,this._keys=C,this._values=M,u.readFields(o9,this,p)}loadGeometry(){const u=this._pbf;u.pos=this._geometry;const p=u.readVarint()+u.pos,_=[];let C,M=1,L=0,O=0,U=0;for(;u.pos>3}if(L--,M===1||M===2)O+=u.readSVarint(),U+=u.readSVarint(),M===1&&(C&&_.push(C),C=[]),C&&C.push(new us(O,U));else{if(M!==7)throw new Error(`unknown command ${M}`);C&&C.push(C[0].clone())}}return C&&_.push(C),_}bbox(){const u=this._pbf;u.pos=this._geometry;const p=u.readVarint()+u.pos;let _=1,C=0,M=0,L=0,O=1/0,U=-1/0,W=1/0,J=-1/0;for(;u.pos>3}if(C--,_===1||_===2)M+=u.readSVarint(),L+=u.readSVarint(),MU&&(U=M),LJ&&(J=L);else if(_!==7)throw new Error(`unknown command ${_}`)}return[O,W,U,J]}toGeoJSON(u,p,_){const C=this.extent*Math.pow(2,_),M=this.extent*u,L=this.extent*p,O=this.loadGeometry();function U(re){return[360*(re.x+M)/C-180,360/Math.PI*Math.atan(Math.exp((1-2*(re.y+L)/C)*Math.PI))-90]}function W(re){return re.map(U)}let J;if(this.type===1){const re=[];for(const xe of O)re.push(xe[0]);const fe=W(re);J=re.length===1?{type:"Point",coordinates:fe[0]}:{type:"MultiPoint",coordinates:fe}}else if(this.type===2){const re=O.map(W);J=re.length===1?{type:"LineString",coordinates:re[0]}:{type:"MultiLineString",coordinates:re}}else{if(this.type!==3)throw new Error("unknown feature type");{const re=function(xe){const we=xe.length;if(we<=1)return[xe];const je=[];let Be,Ye;for(let Ue=0;Ue=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[u];const p=this._pbf.readVarint()+this._pbf.pos;return new V0(this._pbf,p,this.extent,this._keys,this._values)}}function qye(y,u,p){y===15?u.version=p.readVarint():y===1?u.name=p.readString():y===5?u.extent=p.readVarint():y===2?u._features.push(p.pos):y===3?u._keys.push(p.readString()):y===4&&u._values.push(function(_){let C=null;const M=_.readVarint()+_.pos;for(;_.pos>3;C=L===1?_.readString():L===2?_.readFloat():L===3?_.readDouble():L===4?_.readVarint64():L===5?_.readVarint():L===6?_.readSVarint():L===7?_.readBoolean():null}if(C==null)throw new Error("unknown feature value");return C}(p))}class L6{constructor(u,p){this.layers=u.readFields(d9,{},p)}}function d9(y,u,p){if(y===3){const _=new c9(p,p.readVarint()+p.pos);_.length&&(u[_.name]=_)}}const rb="3d_elevation_id",u9="level";class Vye{constructor(){this._valid=!1}reset(u){return this.feature=u,this._valid=!0,this._geometry=u.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(u,p){return this._valid&&u(p(this._geometry)),this}require(u,p,_){return this.get(u,!0,p,_)}optional(u,p,_){return this.get(u,!1,p,_)}success(){return this._valid}get(u,p,_,C){const M=Object.hasOwn(this.feature.properties,u)?+this.feature.properties[u]:void 0;return this._valid&&M!==void 0&&!Number.isNaN(M)?_(C?C(M):M):p&&(this._valid=!1),this}}class h9{constructor(u,p){this.featureFunc=u,this.vertexFunc=p}parseFeature(u,p,_){return this.featureFunc(u,p,_)}parseVertex(u,p,_){return this.vertexFunc(u,p,_)}}const Hye=new h9((y,u,p)=>y.reset(u).require(rb,_=>{p.id=_}).optional("fixed_height_relative",_=>{p.constantHeight=_},og.decodeRelativeHeight).geometry(_=>{p.bounds=_},jL).success(),(y,u,p)=>y.reset(u).require(rb,_=>{p.id=_}).require("elevation_idx",_=>{p.idx=_}).require("extent",_=>{p.extent=_}).require("height_relative",_=>{p.height=_},og.decodeRelativeHeight).geometry(_=>{p.position=_},og.getPoint).success()),Gye=new h9((y,u,p)=>y.reset(u).require(rb,_=>{p.id=_}).optional("fixed_height",_=>{p.constantHeight=_},og.decodeMetricHeight).geometry(_=>{p.bounds=_},jL).success(),(y,u,p)=>y.reset(u).require(rb,_=>{p.id=_}).require("elevation_idx",_=>{p.idx=_}).require("extent",_=>{p.extent=_}).require("height",_=>{p.height=_},og.decodeMetricHeight).geometry(_=>{p.position=_},og.getPoint).success());class og{static getPoint(u){return Is(u[0][0].x,u[0][0].y)}static decodeRelativeHeight(u){return 1e-4*u*5}static decodeMetricHeight(u){return 1e-4*u}static getVersionSchema(u){return u?u==="1.0.1"?Gye:void 0:Hye}static parse(u){const p=[],_=[],C=u.length,M=new Vye;for(let L=0;Lse&&(se=xe)}return _[0]=J,_[1]=se,_}function O6(y,u){let p=!0;for(let _=0;_=0);if(M===0)return 0;M!==u.length&&(p=!1)}return p?2:1}const Wye=[0,0];function m9(y,u){for(const p of y.projections){const _=GN(u,y.points[0],p.axis,Wye);if(p.projection[1]<_[0]||p.projection[0]>_[1])return 0}return 1}function f9(y,u){const p=u[0],_=u[1],C=u[2],M=u[3];for(let L=0;L=0)return!0}return!1}class F6{constructor(u,p){this.points=u||new Array(8).fill([0,0,0]),this.planes=p||new Array(6).fill([0,0,0,0]),this.bounds=So.fromPoints(this.points),this.projections=[],this.frustumEdges=[nt([],this.points[2],this.points[3]),nt([],this.points[0],this.points[3]),nt([],this.points[4],this.points[0]),nt([],this.points[5],this.points[1]),nt([],this.points[6],this.points[2]),nt([],this.points[7],this.points[3])];for(const _ of this.frustumEdges){const C=[0,-_[2],_[1]],M=[_[2],0,-_[0]];this.projections.push({axis:C,projection:GN(this.points,this.points[0],C,[0,0])}),this.projections.push({axis:M,projection:GN(this.points,this.points[0],M,[0,0])})}}static fromInvProjectionMatrix(u,p,_,C){const M=Math.pow(2,_),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(W=>{const J=at([],W,u),se=1/J[3]/p*M;return(re=J)[0]=(fe=J)[0]*(xe=[se,se,C?1/J[3]:se,se])[0],re[1]=fe[1]*xe[1],re[2]=fe[2]*xe[2],re[3]=fe[3]*xe[3],re;var re,fe,xe}),O=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(W=>{const J=Te([],ct([],nt([],L[W[0]],L[W[1]]),nt([],L[W[2]],L[W[1]]))),se=-ye(J,L[W[1]]);return J.concat(se)}),U=[];for(let W=0;Wxe&&(xe=Ue)}let we=1/0,je=-1/0;for(let Be=0;Beje&&(je=Ue)}if(fe>je||we>xe)return 0}return 1}containsPoint(u){for(const p of this.planes){const _=p[3];if(ye([p[0],p[1],p[2]],u)+_<0)return!1}return!0}}class So{static fromPoints(u){const p=[1/0,1/0,1/0],_=[-1/0,-1/0,-1/0];for(const C of u)be(p,p,C),Oe(_,_,C);return new So(p,_)}static fromTileIdAndHeight(u,p,_){const C=1<u.max[p]||u.min[p]>this.max[p])return!1;return!0}intersectsAabbXY(u){return!(this.min[0]>u.max[0]||u.min[0]>this.max[0]||this.min[1]>u.max[1]||u.min[1]>this.max[1])}encapsulate(u){for(let p=0;p<3;p++)this.min[p]=Math.min(this.min[p],u.min[p]),this.max[p]=Math.max(this.max[p],u.max[p])}encapsulatePoint(u){for(let p=0;p<3;p++)this.min[p]=Math.min(this.min[p],u[p]),this.max[p]=Math.max(this.max[p],u[p])}closestPoint(u){return[Math.max(Math.min(this.max[0],u[0]),this.min[0]),Math.max(Math.min(this.max[1],u[1]),this.min[1]),Math.max(Math.min(this.max[2],u[2]),this.min[2])]}}Mr(So,"Aabb");class B6{constructor(u,p){this.feature=u,this.metersToTile=p,this.index=0}get(){const u=this.feature.vertices[this.index],p=this.feature.vertexProps[this.index].dir,_=p[1],C=-p[0],M=(u.extent+1)*this.metersToTile;return[new us(Math.trunc(u.position[0]+_*M),Math.trunc(u.position[1]+C*M)),new us(Math.trunc(u.position[0]-_*M),Math.trunc(u.position[1]-C*M))]}next(){this.index++}valid(){return this.index{return O.a0?Me(U,U,1/W):ie(U,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(u){if(this.edges.length===0)return;let p=0,_=Number.POSITIVE_INFINITY,C=0;const[M,L,O,U,W,J,se]=this._tmpVec2;fs(se,u.x,u.y);const re=new D6(se,null);for(let fe=0;fe0?kr(U,O)/tt:0,pt=Mt(ot,0,1),Rt=Math.abs((ot-pt)*this.edgeProps[fe].len);Er(W,se,je),fs(J,we[1],-we[0]);const _t=Rt+Math.abs(kr(W,J));_t<_&&(p=fe,_=_t,C=pt)}return[p,C]}tessellate(u){const p=ne(),_=ne(),C=ne(),M=ne();for(let L=this.edges.length-1;L>=0;--L){const O=this.edges[L].a,U=this.edges[L].b,{position:W,height:J,extent:se}=this.vertices[O],{position:re,height:fe,extent:xe}=this.vertices[U],we=this.vertexProps[O].dir,je=this.vertexProps[U].dir;if(ie(p,W[0]/u,W[1]/u,J),ie(_,re[0]/u,re[1]/u,fe),ie(C,we[1],-we[0],0),Me(C,C,se),ie(M,je[1],-je[0],0),Me(M,M,xe),this.distSqLines(ae(p[0]+.5*C[0],p[1]+.5*C[1],p[2]+.5*C[2]),ae(_[0]-.5*M[0],_[1]-.5*M[1],_[2]-.5*M[2]),ae(p[0]-.5*C[0],p[1]-.5*C[1],p[2]-.5*C[2]),ae(_[0]+.5*M[0],_[1]+.5*M[1],_[2]+.5*M[2]))<=.0025000000000000005)continue;const Be=this.vertices.length,Ye=ar(ss(),W,re);this.vertices.push({position:Tr(Ye,Ye,.5),height:.5*(J+fe),extent:.5*(se+xe)});const Ue=ar(ss(),we,je);this.vertexProps.push({dir:$r(Ue,Ue)}),this.edges.splice(L,1),this.edgeProps.splice(L,1),this.edges.push({a:O,b:Be}),this.edges.push({a:Be,b:U});const tt=Er(ss(),this.vertices[Be].position,W),ot=Lr(tt),pt={vec:tt,dir:Tr(ss(),tt,1/ot),len:ot};this.edgeProps.push(pt),this.edgeProps.push(pt)}}distSqLines(u,p,_,C){const M=oe(ne(),p,u),L=oe(ne(),C,_),O=oe(ne(),u,_),U=ye(M,M),W=ye(M,L),J=ye(M,O),se=ye(L,L),re=ye(L,O),fe=U*se-W*W;if(fe===0)return $e(ve(M,_,C,ye(O,L)/ye(L,L)),u);const xe=(U*re-W*J)/fe;return $e(ve(M,u,p,(W*re-J*se)/fe),ve(L,_,C,xe))}}class E{static parseFrom(u,p){const _=og.parse(u);if(!_)return[];let{vertices:C,features:M}=_;const L=1/Jm(p);M.sort((J,se)=>J.id-se.id),C.sort((J,se)=>J.id-se.id||J.idx-se.idx),C=C.filter((J,se,re)=>se===re.findIndex(fe=>fe.id===J.id&&fe.idx===J.idx));const O=new Array;let U=0;const W=C.length;for(const J of M){if(J.constantHeight){O.push(new p9(J.id,J.bounds,J.constantHeight));continue}for(;U!==W&&C[U].idC.id===_)}}class f{constructor(u,p){this.zScale=1,this.xOffset=0,this.yOffset=0,u.equals(p)||(this.zScale=Math.pow(2,p.z-u.z),this.xOffset=(u.x*this.zScale-p.x)*mr,this.yOffset=(u.y*this.zScale-p.y)*mr)}constantElevation(u,p){if(u.constantHeight!=null)return this.computeBiasedHeight(u.constantHeight,p)}pointElevation(u,p,_){const C=this.constantElevation(p,_);return C??(u.x=u.x*this.zScale+this.xOffset,u.y=u.y*this.zScale+this.yOffset,this.computeBiasedHeight(p.pointElevation(u),_))}computeBiasedHeight(u,p){return p<=0?u:u+p*Kt(0,p,u>=0?u:Math.abs(.5*u))}}function w(y){if(y===0)return[0,0,0];const u=$L(y);return[u(),u(),u()]}Mr(p9,"ElevationFeature");class I{constructor(u){this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=u.index,this.hasPattern=!1,this.projection=u.projection,this.layoutVertexArray=new zf,this.indexArray=new Go,this.segments=new Gi,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.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 Wd),this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,p){}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){const M=this.layers[0],L=[];let O=null;M.type==="circle"&&(O=M.layout.get("circle-sort-key"));for(const{feature:W,id:J,index:se,sourceLayerIndex:re}of u){const fe=this.layers[0]._featureFilter.needGeometry,xe=Hf(W,fe);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),xe,_))continue;const we=O?O.evaluate(xe,{},_):void 0,je={id:J,properties:W.properties,type:W.type,sourceLayerIndex:re,index:se,geometry:fe?xe.geometry:bm(W,_,C),patterns:{},sortKey:we};L.push(je)}O&&L.sort((W,J)=>W.sortKey-J.sortKey);let U=null;C.projection.name==="globe"&&(this.globeExtVertexArray=new ZT,U=C.projection);for(const W of L){const{geometry:J,index:se,sourceLayerIndex:re}=W,fe=u[se].feature;this.addFeature(W,J,se,p.availableImages,_,U,p.brightness,p.elevationFeatures),p.featureIndex.insert(fe,J,se,re,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(u,p,_,C,M,L,O){this.programConfigurations.updatePaintArrays(u,p,M,_,C,L,O,this.worldview)}updateExpressions(u){this.programConfigurations.updateExpressions(u)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Pye.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,Dye.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,Lye.members))),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(u,p,_,C,M,L,O,U){let W;this.elevationMode!=="none"&&(W=E.getElevationFeature(u,U));for(const J of p)for(const se of J){const re=se.x,fe=se.y;if(re<0||re>=mr||fe<0||fe>=mr)continue;if(L){const je=L.projectTilePoint(re,fe,M),Be=L.upVector(M,re,fe);this.addGlobeExtVertex(je,Be),this.addGlobeExtVertex(je,Be),this.addGlobeExtVertex(je,Be),this.addGlobeExtVertex(je,Be)}const xe=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,u.sortKey),we=xe.vertexLength;if(this.addCircleVertex(re,fe,-1,-1),this.addCircleVertex(re,fe,1,-1),this.addCircleVertex(re,fe,1,1),this.addCircleVertex(re,fe,-1,1),this.elevationMode!=="none"){const je=W?W.pointElevation(new us(re,fe)):0;this.hasElevation=this.hasElevation||je!==0;for(let Be=0;Be<4;Be++)this.elevatedLayoutVertexArray.emplaceBack(je)}this.indexArray.emplaceBack(we,we+1,we+2),this.indexArray.emplaceBack(we,we+2,we+3),xe.vertexLength+=4,xe.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,_,{},C,M,O,void 0,this.worldview)}addCircleVertex(u,p,_,C){this.layoutVertexArray.emplaceBack(2*u+(_+1)/2,2*p+(C+1)/2)}addGlobeExtVertex(u,p){this.globeExtVertexArray.emplaceBack(u.x,u.y,u.z,p[0]*16384,p[1]*16384,p[2]*16384)}}function R(y,u){for(let p=0;p1){if(te(y,u))return!0;for(let _=0;_1?p:p.sub(u)._mult(C)._add(u))}function Ve(y,u){let p,_,C,M=!1;for(let L=0;Lu.y!=C.y>u.y&&u.x<(C.x-_.x)*(u.y-_.y)/(C.y-_.y)+_.x&&(M=!M)}return M}function qe(y,u){let p=!1;for(let _=0,C=y.length-1;_u.y!=L.y>u.y&&u.x<(L.x-M.x)*(u.y-M.y)/(L.y-M.y)+M.x&&(p=!p)}return p}function Ze(y,u,p,_,C){for(const L of y)if(u<=L.x&&p<=L.y&&_>=L.x&&C>=L.y)return!0;const M=[new us(u,p),new us(u,C),new us(_,C),new us(_,p)];if(y.length>2){for(const L of M)if(qe(y,L))return!0}for(let L=0;LC.x&&u.x>C.x||y.y<_.y&&u.y<_.y||y.y>C.y&&u.y>C.y)return!1;const M=ki(y,u,p[0]);return M!==ki(y,u,p[1])||M!==ki(y,u,p[2])||M!==ki(y,u,p[3])}function ht(y,u,p,_,C,M){let L=u.y-y.y,O=y.x-u.x;if(M=M||0){const U=L*L+O*O;if(U===0)return!0;const W=Math.sqrt(U);L/=W,O/=W}return!((p.x-y.x)*L+(p.y-y.y)*O-M<0||(_.x-y.x)*L+(_.y-y.y)*O-M<0||(C.x-y.x)*L+(C.y-y.y)*O-M<0)}function vt(y,u,p,_,C,M,L){return!(ht(y,u,_,C,M,L)||ht(u,p,_,C,M,L)||ht(p,y,_,C,M,L)||ht(_,C,y,u,p,L)||ht(C,M,y,u,p,L)||ht(M,_,y,u,p,L))}function st(y,u,p){const _=u.paint.get(y).value;return _.kind==="constant"?_.value:p.programConfigurations.get(u.id).getMaxValue(y)}function Ut(y){return Math.sqrt(y[0]*y[0]+y[1]*y[1])}function Pt(y,u,p,_,C){if(!u[0]&&!u[1])return y;const M=us.convert(u)._mult(C);p==="viewport"&&M._rotate(-_);const L=[];for(let O=0;O>p&&u.y===this.y>>p}url(u,p){const _=function(M,L,O){const U=2**O,W=2*Math.PI*6378137,J=W*(M/U-.5),se=W*(.5-(L+1)/U);return`${J},${se},${J+W/U},${se+W/U}`}(this.x,this.y,this.z),C=function(M,L,O){let U,W="";for(let J=M;J>0;J--)U=1<this.canonical.z?new Wt(u,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wt(u,this.wrap,u,this.canonical.x>>p,this.canonical.y>>p)}calculateScaledKey(u,p=!0){if(this.overscaledZ===u&&p)return this.key;if(u>this.canonical.z)return hs(this.wrap*+p,u,this.canonical.z,this.canonical.x,this.canonical.y);{const _=this.canonical.z-u;return hs(this.wrap*+p,u,u,this.canonical.x>>_,this.canonical.y>>_)}}isChildOf(u){if(u.wrap!==this.wrap)return!1;const p=this.canonical.z-u.canonical.z;return u.overscaledZ===0||u.overscaledZ>p&&u.canonical.y===this.canonical.y>>p}children(u){if(this.overscaledZ>=u)return[new Wt(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const p=this.canonical.z+1,_=2*this.canonical.x,C=2*this.canonical.y;return[new Wt(p,this.wrap,p,_,C),new Wt(p,this.wrap,p,_+1,C),new Wt(p,this.wrap,p,_,C+1),new Wt(p,this.wrap,p,_+1,C+1)]}isLessThan(u){return this.wrapu.wrap)&&(this.overscaledZu.overscaledZ)&&(this.canonical.xu.canonical.x)&&this.canonical.y{let u=y.canonical.x-1,p=y.wrap;return u<0&&(u=(1<{let u=y.canonical.x+1,p=y.wrap;return u===1<new Wt(y.overscaledZ,y.wrap,y.canonical.z,y.canonical.x,(y.canonical.y===0?1<new Wt(y.overscaledZ,y.wrap,y.canonical.z,y.canonical.x,y.canonical.y===(1<1?null:function(_,C,M,L){const O=Math.sin(M);return _*(Math.sin((1-L)*M)/O)+C*(Math.sin(L*M)/O)}(y.a[u],y.b[u],y.angle,Mt(p,0,1))+y.center[u]}function Js(y){if(y.z<=1)return Ms[y.z+2*y.y+y.x];const u=mn(Rr(y));return So.fromPoints(u)}function Ys(y,u,p){return Me(y,y,1-p),Pe(y,y,u,p)}function Wr(y,u){const p=Li(u.zoom);if(p===0)return Js(y);const _=Rr(y),C=mn(_),M=by(_.getWest())*u.worldSize,L=by(_.getEast())*u.worldSize,O=ig(_.getNorth())*u.worldSize,U=ig(_.getSouth())*u.worldSize,W=[M,O,0],J=[L,O,0],se=[M,U,0],re=[L,U,0],fe=S([],u.globeMatrix);return rt(W,W,fe),rt(J,J,fe),rt(se,se,fe),rt(re,re,fe),C[0]=Ys(C[0],se,p),C[1]=Ys(C[1],re,p),C[2]=Ys(C[2],J,p),C[3]=Ys(C[3],W,p),So.fromPoints(C)}function Vr(y,u,p){for(const _ of y)rt(_,_,u),Me(_,_,p)}function Ir(y,u,p,_){const C=u/y.worldSize,M=y.globeMatrix;if(p.z<=1){const Et=Js(p).getCorners();return Vr(Et,M,C),So.fromPoints(Et)}const L=Rr(p,_),O=mn(L,mu+Ps(y._tileCoverLift));Vr(O,M,C);const U=Number.MAX_VALUE,W=[-U,-U,-U],J=[U,U,U];if(L.contains(y.center)){for(const At of O)be(J,J,At),Oe(W,W,At);W[2]=0;const Et=y.point,jt=[Et.x*C,Et.y*C,0];return be(J,J,jt),Oe(W,W,jt),new So(J,W)}if(y._tileCoverLift>0){for(const Et of O)be(J,J,Et),Oe(W,W,Et);return new So(J,W)}const se=[M[12]*C,M[13]*C,M[14]*C],re=L.getCenter(),fe=Mt(y.center.lat,-85.051129,vm),xe=Mt(re.lat,-85.051129,vm),we=by(y.center.lng),je=ig(fe);let Be=we-by(re.lng);const Ye=je-ig(xe);Be>.5?Be-=1:Be<-.5&&(Be+=1);let Ue=0;Math.abs(Be)>Math.abs(Ye)?Ue=Be>=0?1:3:(Ue=Ye>=0?0:2,Pe(se,se,[M[4]*C,M[5]*C,M[6]*C],-Math.sin(We(Ye>=0?L.getSouth():L.getNorth()))*mu));const tt=O[Ue],ot=O[(Ue+1)%4],pt=new xr(tt,ot,se),Rt=[or(pt,0)||tt[0],or(pt,1)||tt[1],or(pt,2)||tt[2]],_t=Li(y.zoom);if(_t>0){const Et=function({x:At,y:ns,z:is},xs,ks,ws,Ks){const ds=1/(1<.5?cr=-1:Ds<-.5&&(cr=1),gs=((gs+cr)*xs-(ws*=xs))*ks+ws,Cs=((Cs+cr)*xs-ws)*ks+ws,Bs=(Bs*xs-(Ks*=xs))*ks+Ks,Hs=(Hs*xs-Ks)*ks+Ks,[[gs,Hs,0],[Cs,Hs,0],[Cs,Bs,0],[gs,Bs,0]]}(p,u,y._pixelsPerMercatorPixel,we,je);for(let At=0;AtMath.PI/2*1.01}const sa=We(85),la=Math.cos(sa),$i=Math.sin(sa),Qo=j(),wi=y=>{const u=[];return y.paint.get("circle-pitch-alignment")==="map"&&u.push("PITCH_WITH_MAP"),y.paint.get("circle-pitch-scale")==="map"&&u.push("SCALE_WITH_MAP"),u};function $n(y,u,p,_,C,M,L,O,U){if(M&&y.queryGeometry.isAboveHorizon)return!1;M&&(U*=y.pixelToTileUnitsFactor);const W=y.tileID.canonical,J=p.projection.upVectorScale(W,p.center.lat,p.worldSize).metersToTile;for(const se of u)for(const re of se){const fe=re.add(O),xe=C&&p.elevation?p.elevation.exaggeration()*C.getElevationAt(fe.x,fe.y,!0):0,we=p.projection.projectTilePoint(fe.x,fe.y,W);if(xe>0){const Ue=p.projection.upVector(W,fe.x,fe.y);we.x+=Ue[0]*J*xe,we.y+=Ue[1]*J*xe,we.z+=Ue[2]*J*xe}const je=M?fe:ho(we.x,we.y,we.z,_),Be=M?y.tilespaceRays.map(Ue=>Oa(Ue,xe)):y.queryGeometry.screenGeometry,Ye=at([],[we.x,we.y,we.z,1],_);if(!L&&M?U*=Ye[3]/p.cameraToCenterDistance:L&&!M&&(U*=p.cameraToCenterDistance/Ye[3]),M){const Ue=Xc((re.y/mr+W.y)/(1<y.width||C.height>y.height||p.x>y.width-C.width||p.y>y.height-C.height)throw new RangeError("out of range source coordinates for image copy");if(C.width>u.width||C.height>u.height||_.x>u.width-C.width||_.y>u.height-C.height)throw new RangeError("out of range destination coordinates for image copy");const U=y.data,W=u.data,J=M===4&&O;for(let se=0;se{u[y.evaluationKey]=U;const W=y.expression.evaluate(u),J=W?W.toNonPremultipliedRenderColor(null):null;J&&(C.data[L+O+0]=Math.floor(255*J.r),C.data[L+O+1]=Math.floor(255*J.g),C.data[L+O+2]=Math.floor(255*J.b),C.data[L+O+3]=Math.floor(255*J.a))};if(y.clips)for(let L=0,O=0;L<_;++L,O+=4*p)for(let U=0,W=0;U80*p){O=y[0],U=y[1];let J=O,se=U;for(let re=p;reJ&&(J=fe),xe>se&&(se=xe)}W=Math.max(J-O,se-U),W=W!==0?32767/W:0}return ef(M,L,p,O,U,W,0),L}function Rp(y,u,p,_,C){let M;if(C===function(L,O,U,W){let J=0;for(let se=O,re=U-W;se0)for(let L=u;L=u;L-=_)M=rIe(L/_|0,y[L],y[L+1],M);return M&&lE(M,M.next)&&(V6(M),M=M.next),M}function _m(y,u){if(!y)return y;u||(u=y);let p,_=y;do if(p=!1,_.steiner||!lE(_,_.next)&&Jc(_.prev,_,_.next)!==0)_=_.next;else{if(V6(_),_=u=_.prev,_===_.next)break;p=!0}while(p||_!==u);return u}function ef(y,u,p,_,C,M,L){if(!y)return;!L&&M&&function(U,W,J,se){let re=U;do re.z===0&&(re.z=oE(re.x,re.y,W,J,se)),re.prevZ=re.prev,re.nextZ=re.next,re=re.next;while(re!==U);re.prevZ.nextZ=null,re.prevZ=null,function(fe){let xe,we=1;do{let je,Be=fe;fe=null;let Ye=null;for(xe=0;Be;){xe++;let Ue=Be,tt=0;for(let pt=0;pt0||ot>0&&Ue;)tt!==0&&(ot===0||!Ue||Be.z<=Ue.z)?(je=Be,Be=Be.nextZ,tt--):(je=Ue,Ue=Ue.nextZ,ot--),Ye?Ye.nextZ=je:fe=je,je.prevZ=Ye,Ye=je;Be=Ue}Ye.nextZ=null,we*=2}while(xe>1)}(re)}(y,_,C,M);let O=y;for(;y.prev!==y.next;){const U=y.prev,W=y.next;if(M?Op(y,_,C,M):_y(y))u.push(U.i,y.i,W.i),V6(y),y=W.next,O=W.next;else if((y=W)===O){L?L===1?ef(y=WN(_m(y),u),u,p,_,C,M,2):L===2&&H0(y,u,p,_,C,M):ef(_m(y),u,p,_,C,M,1);break}}}function _y(y){const u=y.prev,p=y,_=y.next;if(Jc(u,p,_)>=0)return!1;const C=u.x,M=p.x,L=_.x,O=u.y,U=p.y,W=_.y,J=Math.min(C,M,L),se=Math.min(O,U,W),re=Math.max(C,M,L),fe=Math.max(O,U,W);let xe=_.next;for(;xe!==u;){if(xe.x>=J&&xe.x<=re&&xe.y>=se&&xe.y<=fe&&U6(C,O,M,U,L,W,xe.x,xe.y)&&Jc(xe.prev,xe,xe.next)>=0)return!1;xe=xe.next}return!0}function Op(y,u,p,_){const C=y.prev,M=y,L=y.next;if(Jc(C,M,L)>=0)return!1;const O=C.x,U=M.x,W=L.x,J=C.y,se=M.y,re=L.y,fe=Math.min(O,U,W),xe=Math.min(J,se,re),we=Math.max(O,U,W),je=Math.max(J,se,re),Be=oE(fe,xe,u,p,_),Ye=oE(we,je,u,p,_);let Ue=y.prevZ,tt=y.nextZ;for(;Ue&&Ue.z>=Be&&tt&&tt.z<=Ye;){if(Ue.x>=fe&&Ue.x<=we&&Ue.y>=xe&&Ue.y<=je&&Ue!==C&&Ue!==L&&U6(O,J,U,se,W,re,Ue.x,Ue.y)&&Jc(Ue.prev,Ue,Ue.next)>=0||(Ue=Ue.prevZ,tt.x>=fe&&tt.x<=we&&tt.y>=xe&&tt.y<=je&&tt!==C&&tt!==L&&U6(O,J,U,se,W,re,tt.x,tt.y)&&Jc(tt.prev,tt,tt.next)>=0))return!1;tt=tt.nextZ}for(;Ue&&Ue.z>=Be;){if(Ue.x>=fe&&Ue.x<=we&&Ue.y>=xe&&Ue.y<=je&&Ue!==C&&Ue!==L&&U6(O,J,U,se,W,re,Ue.x,Ue.y)&&Jc(Ue.prev,Ue,Ue.next)>=0)return!1;Ue=Ue.prevZ}for(;tt&&tt.z<=Ye;){if(tt.x>=fe&&tt.x<=we&&tt.y>=xe&&tt.y<=je&&tt!==C&&tt!==L&&U6(O,J,U,se,W,re,tt.x,tt.y)&&Jc(tt.prev,tt,tt.next)>=0)return!1;tt=tt.nextZ}return!0}function WN(y,u){let p=y;do{const _=p.prev,C=p.next.next;!lE(_,C)&&tIe(_,p,p.next,C)&&q6(_,C)&&q6(C,_)&&(u.push(_.i,p.i,C.i),V6(p),V6(p.next),p=y=C),p=p.next}while(p!==y);return _m(p)}function H0(y,u,p,_,C,M){let L=y;do{let O=L.next.next;for(;O!==L.prev;){if(L.i!==O.i&&S0t(L,O)){let U=sIe(L,O);return L=_m(L,L.next),U=_m(U,U.next),ef(L,u,p,_,C,M,0),void ef(U,u,p,_,C,M,0)}O=O.next}L=L.next}while(L!==y)}function nb(y,u){let p=y.x-u.x;return p===0&&(p=y.y-u.y,p===0)&&(p=(y.next.y-y.y)/(y.next.x-y.x)-(u.next.y-u.y)/(u.next.x-u.x)),p}function z6(y,u){const p=function(C,M){let L=M;const O=C.x,U=C.y;let W,J=-1/0;if(lE(C,L))return L;do{if(lE(C,L.next))return L.next;if(U<=L.y&&U>=L.next.y&&L.next.y!==L.y){const we=L.x+(U-L.y)*(L.next.x-L.x)/(L.next.y-L.y);if(we<=O&&we>J&&(J=we,W=L.x=L.x&&L.x>=re&&O!==L.x&&eIe(UW.x||L.x===W.x&&$6(W,L)))&&(W=L,xe=we)}L=L.next}while(L!==se);return W}(y,u);if(!p)return u;const _=sIe(p,y);return _m(_,_.next),_m(p,p.next)}function $6(y,u){return Jc(y.prev,y,u.prev)<0&&Jc(u.next,y,y.next)<0}function oE(y,u,p,_,C){return(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=(y-p)*C|0)|y<<8))|y<<4))|y<<2))|y<<1))|(u=1431655765&((u=858993459&((u=252645135&((u=16711935&((u=(u-_)*C|0)|u<<8))|u<<4))|u<<2))|u<<1))<<1}function Kye(y){let u=y,p=y;do(u.x=(y-L)*(M-O)&&(y-L)*(_-O)>=(p-L)*(u-O)&&(p-L)*(M-O)>=(C-L)*(_-O)}function U6(y,u,p,_,C,M,L,O){return!(y===L&&u===O)&&eIe(y,u,p,_,C,M,L,O)}function S0t(y,u){return y.next.i!==u.i&&y.prev.i!==u.i&&!function(p,_){let C=p;do{if(C.i!==p.i&&C.next.i!==p.i&&C.i!==_.i&&C.next.i!==_.i&&tIe(C,C.next,p,_))return!0;C=C.next}while(C!==p);return!1}(y,u)&&(q6(y,u)&&q6(u,y)&&function(p,_){let C=p,M=!1;const L=(p.x+_.x)/2,O=(p.y+_.y)/2;do C.y>O!=C.next.y>O&&C.next.y!==C.y&&L<(C.next.x-C.x)*(O-C.y)/(C.next.y-C.y)+C.x&&(M=!M),C=C.next;while(C!==p);return M}(y,u)&&(Jc(y.prev,y,u.prev)||Jc(y,u.prev,u))||lE(y,u)&&Jc(y.prev,y,y.next)>0&&Jc(u.prev,u,u.next)>0)}function Jc(y,u,p){return(u.y-y.y)*(p.x-u.x)-(u.x-y.x)*(p.y-u.y)}function lE(y,u){return y.x===u.x&&y.y===u.y}function tIe(y,u,p,_){const C=g9(Jc(y,u,p)),M=g9(Jc(y,u,_)),L=g9(Jc(p,_,y)),O=g9(Jc(p,_,u));return C!==M&&L!==O||!(C!==0||!x9(y,p,u))||!(M!==0||!x9(y,_,u))||!(L!==0||!x9(p,y,_))||!(O!==0||!x9(p,u,_))}function x9(y,u,p){return u.x<=Math.max(y.x,p.x)&&u.x>=Math.min(y.x,p.x)&&u.y<=Math.max(y.y,p.y)&&u.y>=Math.min(y.y,p.y)}function g9(y){return y>0?1:y<0?-1:0}function q6(y,u){return Jc(y.prev,y,y.next)<0?Jc(y,u,y.next)>=0&&Jc(y,y.prev,u)>=0:Jc(y,u,y.prev)<0||Jc(y,y.next,u)<0}function sIe(y,u){const p=Yye(y.i,y.x,y.y),_=Yye(u.i,u.x,u.y),C=y.next,M=u.prev;return y.next=u,u.prev=y,p.next=C,C.prev=p,_.next=p,p.prev=_,M.next=_,_.prev=M,_}function rIe(y,u,p,_){const C=Yye(y,u,p);return _?(C.next=_.next,C.prev=_,_.next.prev=C,_.next=C):(C.prev=C,C.next=C),C}function V6(y){y.next.prev=y.prev,y.prev.next=y.next,y.prevZ&&(y.prevZ.nextZ=y.nextZ),y.nextZ&&(y.nextZ.prevZ=y.prevZ)}function Yye(y,u,p){return{i:y,x:u,y:p,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function H6(y,u){const p=y.length;if(p<=1)return[y];const _=[];let C,M;for(let L=0;L1)for(let L=0;L<_.length;L++)_[L].length<=u||(Gz(_[L],u,1,_[L].length-1,C0t),_[L]=_[L].slice(0,u));return _}function C0t(y,u){return u.area-y.area}function nIe(y,u,p=1){if(!y)return null;const _=typeof y=="string"?Au.from(y).getPrimary():y.getPrimary(),C=typeof y=="string"?null:y.getSecondary();for(const M of[_,C]){if(!M)continue;const L=M.id.toString();u.has(L)||u.set(L,[]),M.scaleSelf(p),u.get(L).push(M)}return{primary:_.toString(),secondary:C?C.toString():null}}function Zye(y,u,p,_){const C=_.patternDependencies;let M=!1;for(const L of u){const O=L.paint.get(`${y}-pattern`);O.isConstant()||(M=!0),nIe(O.constantOr(null),C,p)&&(M=!0)}return M}function Xye(y,u,p,_,C,M){const L=M.patternDependencies;for(const O of u){const U=O.paint.get(`${y}-pattern`).value;if(U.kind!=="constant"){const W=nIe(U.evaluate({zoom:_},p,{},void 0,M.availableImages),L,C);if(!W)continue;const{primary:J,secondary:se}=W;J&&(p.patterns[O.id]=[J,se].filter(Boolean))}}return p}class ab{constructor(){this.portals=[]}static isOnBorder(u,p){return u<=0&&p<=0||u>=mr&&p>=mr}static evaluate(u){if(u.length===0)return new ab;let p=[];for(const U of u)p.push(...U.portals);if(p.length===0)return new ab;for(const U of p){const W=U.va,J=U.vb;(ab.isOnBorder(W.x,J.x)||ab.isOnBorder(W.y,J.y))&&(U.type="border")}const _=p.filter(U=>U.type!=="unevaluated"),C=p.filter(U=>U.type==="unevaluated");if(C.length===0)return new ab;C.sort((U,W)=>U.hash===W.hash?U.isTunnel===W.isTunnel?0:U.isTunnel?-1:1:U.hashU.hashM!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Xm(p,{zoom:_,lut:C},M=>M!=="fill-bridge-guard-rail-color")}addVertices(u,p){const _=this.unevalVertices.length;for(let C=0;C=M.min.x&&se.x<=M.max.x&&se.y>=M.min.y&&se.y<=M.max.y||re.x>=M.min.x&&re.x<=M.max.x&&re.y>=M.min.y&&re.y<=M.max.y||Xe(se,re,O))||this.isOnBorder(se.x,re.x)||this.isOnBorder(se.y,re.y))continue;const fe=tf.computeEdgeHash(this.unevalVertices[W],this.unevalVertices[J]);let xe,we=this.vertexHashLookup.get(tf.computePosHash(se));we!=null?xe=we.next:(we=this.vertexHashLookup.get(tf.computePosHash(re)),xe=we!=null?we.prev:fe),this.unevalEdges.push({polygonIdx:u,a:W,b:J,hash:fe,portalHash:xe,isTunnel:C,type:"unevaluated",featureInfo:L})}}addPortalCandidates(u,p,_,C,M){if(p.length!==0){this.vertexHashLookup.clear();for(const L of p){if(L.length===0)continue;const O=L[0];let U=tf.computeEdgeHash(O[O.length-2],O.at(-1));for(let W=0;W({vertexOffset:0,primitiveOffset:this.indexArray.length}),_=re=>{re.primitiveLength=this.indexArray.length-re.primitiveOffset},C=new T0t(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(u.portals,this.unevalEdges);const M=p(),L=p(),O=p(),U=(re,fe)=>{re.sort((we,je)=>we.type===fe&&je.type!==fe?-1:we.type!==fe&&je.type===fe?1:0);const xe=re.findIndex(we=>we.type!==fe);return xe>=0?xe:re.length};let W=0;this.unevalEdges.length>0&&(W=U(this.unevalEdges,"none"),this.constructBridgeStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:W},this.tileToMeters)),_(O);const J=p(),se=p();if(this.unevalEdges.length>0){const re=this.unevalEdges.splice(W),fe=U(re,"tunnel")+W;this.unevalEdges.push(...re),this.constructTunnelStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:W},{min:W,max:fe})}_(J),C.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),_(se),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),_(L),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),_(M),this.maskSegments=Gi.simpleSegment(0,se.primitiveOffset,0,se.primitiveLength),this.depthSegments=Gi.simpleSegment(0,L.primitiveOffset,0,L.primitiveLength),this.renderableBridgeSegments=Gi.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength),this.renderableTunnelSegments=Gi.simpleSegment(0,J.primitiveOffset,0,J.primitiveLength),this.shadowCasterSegments=Gi.simpleSegment(0,M.primitiveOffset,0,M.primitiveLength)}update(u,p,_,C,M,L,O,U){this.bridgeProgramConfigurations.updatePaintArrays(u,p,M,_,C,L,O,U),this.tunnelProgramConfigurations.updatePaintArrays(u,p,M,_,C,L,O,U)}upload(u){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=u.createVertexBuffer(this.vertexPositions,Jo.members),this.vertexBufferNormal=u.createVertexBuffer(this.vertexNormals,Mu.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(u),this.tunnelProgramConfigurations.upload(u))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(u,p,_,C,M){const L=(O,U)=>{for(let W=0;Wie(ks,p[ws].x,p[ws].y,_[ws]*U),se=ne(),re=ne(),fe=ne(),xe=ne(),we=ne(),je=(ks,ws)=>{const Ks=O.get(tf.computePosHash(p[ws])),ds=Ks.from,gs=Ks.to;if(!ds||!gs)return;J(se,ds),J(re,ws),J(fe,gs),Ke(xe),Ce(se,re)||(nt(we,re,se),Te(xe,we)),Ce(fe,re)||(nt(we,fe,re),me(xe,xe,Te(we,we)));const Cs=lt(xe);return Cs>0?Me(ks,xe,1/Cs):void 0};let Be=Number.POSITIVE_INFINITY;this.sortSubarray(C,M.min,M.max,(ks,ws)=>ks.featureInfo.featureIndex-ws.featureInfo.featureIndex);const Ye=ne(),Ue=ne(),tt=ne(),ot=ne(),pt=ne(),Rt=ne(),_t=ne(),Et=ne(),jt=ne(),At=[ne(),ne(),ne(),ne()],ns=[ne(),ne(),ne(),ne()],is=[{coord:new us(0,0),height:0},{coord:new us(0,0),height:0}],xs=(ks,ws)=>ks>ws;for(let ks=M.min;ksBe.featureInfo.featureIndex-Ye.featureInfo.featureIndex;this.sortSubarray(C,M.min,M.max,U),this.sortSubarray(C,L.min,L.max,U);const W=Be=>Te(Be,Be),J=[{coord:new us(0,0),height:0},{coord:new us(0,0),height:0}],se=(Be,Ye)=>BeO.hash===U.hash?U.polygonIdx-O.polygonIdx:U.hash>O.hash?1:-1);let _=0,C=0,M=0,L=p[_].polygonIdx;do C++,(C===p.length||p[_].hash!==p[C].hash)&&((C-_===1||p[C-1].polygonIdx!==L)&&(M<_&&(p[M]=p[_],p[_]=null),p[M].type="none",M++),_=C,_!==p.length&&(L=p[_].polygonIdx));while(_!==p.length);if(p.splice(M),p.length!==0&&u.length!==0){p.sort((W,J)=>W.portalHashJ.hash?O++:J.hash>W.portalHash?U++:(W.type=J.type,O++)}}}isOnBorder(u,p){return u<=0&&p<=0||u>=mr&&p>=mr}addFeatureSection(u,p,_,C){return u!==p&&(p=u,_.push({featureIndex:u,vertexStart:C.getVertexCount()}),C.clearVertexLookup()),p}sortSubarray(u,p,_,C){const M=u.slice(p,_);M.sort(C),u.splice(p,M.length,...M)}static computeEdgeHash(u,p){return(u.y===p.y&&u.x>p.x||u.y>p.y)&&([u,p]=[p,u]),BigInt(tf.computePosHash(u))<<32n|BigInt(tf.computePosHash(p))}static computePosHash(u){return((65535&u.x)<<16|65535&u.y)>>>0}}function E0t(y,u){return y>u?1:y0))return p;p=p.left}}return null}contains(u){for(var p=this._root,_=this._compare;p;){var C=_(u,p.key);if(C===0)return!0;p=C<0?p.left:p.right}return!1}remove(u){var p=this.find(u);if(!p)return!1;if(this.splay(p),p.left)if(p.right){var _=this.minNode(p.right);_.parent!==p&&(this.replace(_,_.right),_.right=p.right,_.right.parent=_),this.replace(p,_),_.left=p.left,_.left.parent=_}else this.replace(p,p.left);else this.replace(p,p.right);return this._size--,!0}removeNode(u){if(!u)return!1;if(this.splay(u),u.left)if(u.right){var p=this.minNode(u.right);p.parent!==u&&(this.replace(p,p.right),p.right=u.right,p.right.parent=p),this.replace(u,p),p.left=u.left,p.left.parent=p}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}erase(u){var p=this.find(u);if(p){this.splay(p);var _=p.left,C=p.right,M=null;_&&(_.parent=null,M=this.maxNode(_),this.splay(M),this._root=M),C&&(_?M.right=C:this._root=C,C.parent=M),this._size--}}pop(){var u=this._root,p=null;if(u){for(;u.left;)u=u.left;p={key:u.key,data:u.data},this.remove(u.key)}return p}next(u){var p=u;if(p)if(p.right)for(p=p.right;p&&p.left;)p=p.left;else for(p=u.parent;p&&p.right===u;)u=p,p=p.parent;return p}prev(u){var p=u;if(p)if(p.left)for(p=p.left;p&&p.right;)p=p.right;else for(p=u.parent;p&&p.left===u;)u=p,p=p.parent;return p}forEach(u){for(var p=this._root,_=[],C=!1,M=0;!C;)p?(_.push(p),p=p.left):_.length>0?(u(p=_.pop(),M++),p=p.right):C=!0;return this}range(u,p,_,C){const M=[],L=this._compare;let O,U=this._root;for(;M.length!==0||U;)if(U)M.push(U),U=U.left;else{if(U=M.pop(),O=L(U.key,p),O>0)break;if(L(U.key,u)>=0&&_.call(C,U))return this;U=U.right}return this}keys(){for(var u=this._root,p=[],_=[],C=!1;!C;)u?(p.push(u),u=u.left):p.length>0?(u=p.pop(),_.push(u.key),u=u.right):C=!0;return _}values(){for(var u=this._root,p=[],_=[],C=!1;!C;)u?(p.push(u),u=u.left):p.length>0?(u=p.pop(),_.push(u.data),u=u.right):C=!0;return _}at(u){for(var p=this._root,_=[],C=!1,M=0;!C;)if(p)_.push(p),p=p.left;else if(_.length>0){if(p=_.pop(),M===u)return p;M++,p=p.right}else C=!0;return null}load(u=[],p=[],_=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const C=u.length;return _&&e0e(u,p,0,C-1,this._compare),this._root=Jye(null,u,p,0,C),this._size=C,this}min(){var u=this.minNode(this._root);return u?u.key:null}max(){var u=this.maxNode(this._root);return u?u.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(u,p,_,C,M){return new Qye(_,M).load(u,p,C)}}function Jye(y,u,p,_,C){const M=C-_;if(M>0){const L=_+Math.floor(M/2),O={key:u[L],data:p[L],parent:y};return O.left=Jye(O,u,p,_,L),O.right=Jye(O,u,p,L+1,C),O}return null}function e0e(y,u,p,_,C){if(p>=_)return;const M=y[p+_>>1];let L=p-1,O=_+1;for(;;){do L++;while(C(y[L],M)<0);do O--;while(C(y[O],M)>0);if(L>=O)break;let U=y[L];y[L]=y[O],y[O]=U,U=u[L],u[L]=u[O],u[O]=U}e0e(y,u,p,O,C),e0e(y,u,O+1,_,C)}const aIe=11102230246251565e-32,wm=134217729,A0t=(3+8*aIe)*aIe;function t0e(y,u,p,_,C){let M,L,O,U,W=u[0],J=_[0],se=0,re=0;J>W==J>-W?(M=W,W=u[++se]):(M=J,J=_[++re]);let fe=0;if(seW==J>-W?(L=W+M,O=M-(L-W),W=u[++se]):(L=J+M,O=M-(L-J),J=_[++re]),M=L,O!==0&&(C[fe++]=O);seW==J>-W?(L=M+W,U=L-M,O=M-(L-U)+(W-U),W=u[++se]):(L=M+J,U=L-M,O=M-(L-U)+(J-U),J=_[++re]),M=L,O!==0&&(C[fe++]=O);for(;se0:(_[0]-u[0])*(p[1]-u[1])-(p[0]-u[0])*(_[1]-u[1])>0}isAbove(u){return!this.isBelow(u)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const u=new dE(this.point,this.left,this.otherEvent,this.isSubject,this.type);return u.contourId=this.contourId,u.resultTransition=this.resultTransition,u.prevInResult=this.prevInResult,u.isExteriorRing=this.isExteriorRing,u.inOut=this.inOut,u.otherInOut=this.otherInOut,u}}function G0(y,u){return y[0]===u[0]&&y[1]===u[1]}function s0e(y,u,p){const _=function(C,M,L,O,U,W){const J=(M-W)*(L-U),se=(C-U)*(O-W),re=J-se;if(J===0||se===0||J>0!=se>0)return re;const fe=Math.abs(J+se);return Math.abs(re)>=33306690738754716e-32*fe?re:-function(xe,we,je,Be,Ye,Ue,tt){let ot,pt,Rt,_t,Et,jt,At,ns,is,xs,ks,ws,Ks,ds,gs,Cs,Bs,Hs;const cr=xe-Ye,Ds=je-Ye,tr=we-Ue,sr=Be-Ue;ds=cr*sr,jt=wm*cr,At=jt-(jt-cr),ns=cr-At,jt=wm*sr,is=jt-(jt-sr),xs=sr-is,gs=ns*xs-(ds-At*is-ns*is-At*xs),Cs=tr*Ds,jt=wm*tr,At=jt-(jt-tr),ns=tr-At,jt=wm*Ds,is=jt-(jt-Ds),xs=Ds-is,Bs=ns*xs-(Cs-At*is-ns*is-At*xs),ks=gs-Bs,Et=gs-ks,cE[0]=gs-(ks+Et)+(Et-Bs),ws=ds+ks,Et=ws-ds,Ks=ds-(ws-Et)+(ks-Et),ks=Ks-Cs,Et=Ks-ks,cE[1]=Ks-(ks+Et)+(Et-Cs),Hs=ws+ks,Et=Hs-ws,cE[2]=ws-(Hs-Et)+(ks-Et),cE[3]=Hs;let wr=function(si,Wn){let Pa=Wn[0];for(let ca=1;ca<4;ca++)Pa+=Wn[ca];return Pa}(0,cE),Ar=22204460492503146e-32*tt;if(wr>=Ar||-wr>=Ar||(Et=xe-cr,ot=xe-(cr+Et)+(Et-Ye),Et=je-Ds,Rt=je-(Ds+Et)+(Et-Ye),Et=we-tr,pt=we-(tr+Et)+(Et-Ue),Et=Be-sr,_t=Be-(sr+Et)+(Et-Ue),ot===0&&pt===0&&Rt===0&&_t===0)||(Ar=11093356479670487e-47*tt+A0t*Math.abs(wr),wr+=cr*_t+sr*ot-(tr*Rt+Ds*pt),wr>=Ar||-wr>=Ar))return wr;ds=ot*sr,jt=wm*ot,At=jt-(jt-ot),ns=ot-At,jt=wm*sr,is=jt-(jt-sr),xs=sr-is,gs=ns*xs-(ds-At*is-ns*is-At*xs),Cs=pt*Ds,jt=wm*pt,At=jt-(jt-pt),ns=pt-At,jt=wm*Ds,is=jt-(jt-Ds),xs=Ds-is,Bs=ns*xs-(Cs-At*is-ns*is-At*xs),ks=gs-Bs,Et=gs-ks,sf[0]=gs-(ks+Et)+(Et-Bs),ws=ds+ks,Et=ws-ds,Ks=ds-(ws-Et)+(ks-Et),ks=Ks-Cs,Et=Ks-ks,sf[1]=Ks-(ks+Et)+(Et-Cs),Hs=ws+ks,Et=Hs-ws,sf[2]=ws-(Hs-Et)+(ks-Et),sf[3]=Hs;const tn=t0e(4,cE,4,sf,iIe);ds=cr*_t,jt=wm*cr,At=jt-(jt-cr),ns=cr-At,jt=wm*_t,is=jt-(jt-_t),xs=_t-is,gs=ns*xs-(ds-At*is-ns*is-At*xs),Cs=tr*Rt,jt=wm*tr,At=jt-(jt-tr),ns=tr-At,jt=wm*Rt,is=jt-(jt-Rt),xs=Rt-is,Bs=ns*xs-(Cs-At*is-ns*is-At*xs),ks=gs-Bs,Et=gs-ks,sf[0]=gs-(ks+Et)+(Et-Bs),ws=ds+ks,Et=ws-ds,Ks=ds-(ws-Et)+(ks-Et),ks=Ks-Cs,Et=Ks-ks,sf[1]=Ks-(ks+Et)+(Et-Cs),Hs=ws+ks,Et=Hs-ws,sf[2]=ws-(Hs-Et)+(ks-Et),sf[3]=Hs;const zr=t0e(tn,iIe,4,sf,oIe);ds=ot*_t,jt=wm*ot,At=jt-(jt-ot),ns=ot-At,jt=wm*_t,is=jt-(jt-_t),xs=_t-is,gs=ns*xs-(ds-At*is-ns*is-At*xs),Cs=pt*Rt,jt=wm*pt,At=jt-(jt-pt),ns=pt-At,jt=wm*Rt,is=jt-(jt-Rt),xs=Rt-is,Bs=ns*xs-(Cs-At*is-ns*is-At*xs),ks=gs-Bs,Et=gs-ks,sf[0]=gs-(ks+Et)+(Et-Bs),ws=ds+ks,Et=ws-ds,Ks=ds-(ws-Et)+(ks-Et),ks=Ks-Cs,Et=Ks-ks,sf[1]=Ks-(ks+Et)+(Et-Cs),Hs=ws+ks,Et=Hs-ws,sf[2]=ws-(Hs-Et)+(ks-Et),sf[3]=Hs;const Sn=t0e(zr,oIe,4,sf,lIe);return lIe[Sn-1]}(C,M,L,O,U,W,fe)}(y[0],y[1],u[0],u[1],p[0],p[1]);return _>0?-1:_<0?1:0}function gw(y,u){const p=y.point,_=u.point;return p[0]>_[0]?1:p[0]<_[0]?-1:p[1]!==_[1]?p[1]>_[1]?1:-1:function(C,M,L){return C.left!==M.left?C.left?1:-1:s0e(L,C.otherEvent.point,M.otherEvent.point)!==0?C.isBelow(M.otherEvent.point)?-1:1:!C.isSubject&&M.isSubject?1:-1}(y,u,p)}function yw(y,u,p){const _=new dE(u,!1,y,y.isSubject),C=new dE(u,!0,y.otherEvent,y.isSubject);return G0(y.point,y.otherEvent.point)&&console.warn("what is that, a collapsed segment?",y),_.contourId=C.contourId=y.contourId,gw(C,y.otherEvent)>0&&(y.otherEvent.left=!0,C.left=!1),y.otherEvent.otherEvent=C,y.otherEvent=_,p.push(C),p.push(_),p}function y9(y,u){return y[0]*u[1]-y[1]*u[0]}function r0e(y,u){return y[0]*u[0]+y[1]*u[1]}function n0e(y,u,p){const _=function(U,W,J,se){const re=[W[0]-U[0],W[1]-U[1]],fe=[se[0]-J[0],se[1]-J[1]];function xe(Rt,_t,Et){return[Rt[0]+_t*Et[0],Rt[1]+_t*Et[1]]}const we=[J[0]-U[0],J[1]-U[1]];let je=y9(re,fe),Be=je*je;const Ye=r0e(re,re);if(Be>0){const Rt=y9(we,fe)/je;if(Rt<0||Rt>1)return null;const _t=y9(we,re)/je;return _t<0||_t>1?null:Rt===0||Rt===1?[xe(U,Rt,re)]:_t===0||_t===1?[xe(J,_t,fe)]:[xe(U,Rt,re)]}if(je=y9(we,re),Be=je*je,Be>0)return null;const Ue=r0e(re,we)/Ye,tt=Ue+r0e(re,fe)/Ye,ot=Math.min(Ue,tt),pt=Math.max(Ue,tt);return ot<=1&&pt>=0?ot===1?[xe(U,ot>0?ot:0,re)]:pt===0?[xe(U,pt<1?pt:1,re)]:[xe(U,ot>0?ot:0,re),xe(U,pt<1?pt:1,re)]:null}(y.point,y.otherEvent.point,u.point,u.otherEvent.point),C=_?_.length:0;if(C===0||C===1&&(G0(y.point,u.point)||G0(y.otherEvent.point,u.otherEvent.point))||C===2&&y.isSubject===u.isSubject)return 0;if(C===1)return!G0(y.point,_[0])&&!G0(y.otherEvent.point,_[0])&&yw(y,_[0],p),!G0(u.point,_[0])&&!G0(u.otherEvent.point,_[0])&&yw(u,_[0],p),1;const M=[];let L=!1,O=!1;return G0(y.point,u.point)?L=!0:gw(y,u)===1?M.push(u,y):M.push(y,u),G0(y.otherEvent.point,u.otherEvent.point)?O=!0:gw(y.otherEvent,u.otherEvent)===1?M.push(u.otherEvent,y.otherEvent):M.push(y.otherEvent,u.otherEvent),L&&O||L?(u.type=1,y.type=u.inOut===y.inOut?2:3,L&&!O&&yw(M[1].otherEvent,M[0].point,p),2):O?(yw(M[0],M[1].point,p),3):M[0]!==M[3].otherEvent?(yw(M[0],M[1].point,p),yw(M[1],M[2].point,p),3):(yw(M[0],M[1].point,p),yw(M[3].otherEvent,M[2].point,p),3)}function M0t(y,u){if(y===u)return 0;if(s0e(y.point,y.otherEvent.point,u.point)!==0||s0e(y.point,y.otherEvent.point,u.otherEvent.point)!==0)return G0(y.point,u.point)?y.isBelow(u.otherEvent.point)?-1:1:y.point[0]===u.point[0]?y.point[1](u.contourId??0)?1:-1}return gw(y,u)===1?1:-1}class I0t{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function P0t(y,u,p,_){let C,M=y+1,L=u[y].point;const O=u.length;for(M_;)M--;return M}function L0t(y,u,p){const _=new I0t;if(y.prevInResult!=null){const C=y.prevInResult,M=C.outputContourId;if(C.resultTransition>0){const L=u[M];if(L.holeOf!=null){const O=L.holeOf;u[O].holeIds.push(p),_.holeOf=O,_.depth=u[M].depth}else u[M].holeIds.push(p),_.holeOf=M,_.depth=u[M].depth+1}else _.holeOf=null,_.depth=u[M].depth}else _.holeOf=null,_.depth=0;return _}const dIe=Math.max,uIe=Math.min;let v9=0;function hIe(y,u,p,_,C,M){let L,O,U,W,J,se;for(L=0,O=y.length-1;L0?se.left=!0:J.left=!0;const re=U[0],fe=U[1];C[0]=uIe(C[0],re),C[1]=uIe(C[1],fe),C[2]=dIe(C[2],re),C[3]=dIe(C[3],fe),_.push(J),_.push(se)}}const b9=[];function mIe(y,u,p){let _=y,C=u;typeof y[0][0][0]=="number"&&(_=[y]),typeof u[0][0][0]=="number"&&(C=[u]);let M=function(re,fe,xe){let we=null;return re.length*fe.length===0&&(xe===0?we=b9:xe===2?we=re:(xe===1||xe===3)&&(we=re.length===0?fe:re)),we}(_,C,p);if(M)return M===b9?null:M;const L=[1/0,1/0,-1/0,-1/0],O=[1/0,1/0,-1/0,-1/0],U=function(re,fe,xe,we,je){const Be=new _N(void 0,gw);let Ye,Ue,tt,ot,pt,Rt;for(tt=0,ot=re.length;ttwe[2]||we[0]>xe[2]||xe[1]>we[3]||we[1]>xe[3])&&(je===0?Be=b9:je===2?Be=re:(je===1||je===3)&&(Be=re.concat(fe))),Be}(_,C,L,O,p),M)return M===b9?null:M;const W=function(re,fe,xe,we,je,Be){const Ye=new Qye(M0t),Ue=[],tt=Math.min(we[2],je[2]);let ot,pt,Rt;for(;re.length!==0;){let _t=re.pop();if(Ue.push(_t),Be===0&&_t.point[0]>tt||Be===2&&_t.point[0]>we[2])break;if(_t.left){pt=ot=Ye.insert(_t),Rt=Ye.minNode(),ot=ot!==Rt?Ye.prev(ot):null,pt=Ye.next(pt);const Et=ot?ot.key:null;let jt;if(W6(_t,Et,Be),pt&&n0e(_t,pt.key,re)===2&&(W6(_t,Et,Be),W6(pt.key,_t,Be)),ot&&n0e(ot.key,_t,re)===2){let At=ot;At=At!==Rt?Ye.prev(At):null,jt=At?At.key:null,W6(Et,jt,Be),W6(_t,Et,Be)}}else _t=_t.otherEvent,pt=ot=Ye.find(_t),ot&&pt&&(ot=ot!==Rt?Ye.prev(ot):null,pt=Ye.next(pt),Ye.remove(_t),pt&&ot&&n0e(ot.key,pt.key,re))}return Ue}(U,0,0,L,O,p),J=function(re){let fe,xe;const we=function(Ye){let Ue,tt,ot,pt,Rt;const _t=[];for(tt=0,ot=Ye.length;tt{je[Rt]=!0,Rt=we.length)&&we[ot];);Be.push(Ue)}return Be}(W),se=[];for(let re=0;re{L.push(new us(se,U+(se-O)/(W-O)*(J-U)))}:(L,O,U,W,J,se)=>{L.push(new us(O+(se-U)/(J-U)*(W-O),se))};for(const L of y){const O=[];for(const U of L){if(U.length<=2)continue;const W=[];for(let re=0;reu&&M(W,fe,xe,we,je,u):Be>p?Ye=u&&M(W,fe,xe,we,je,u),Ye>p&&Be<=p&&M(W,fe,xe,we,je,p)}let J=U.at(-1);const se=_===0?J.x:J.y;se>=u&&se<=p&&W.push(J),W.length&&(J=W.at(-1),W[0].x===J.x&&W[0].y===J.y||W.push(W[0]),O.push(W))}O.length&&C.push(O)}return C}function D0t(y,u){const p=mIe(a0e(y),a0e([u]),0);return p==null?[]:fIe(p)}function R0t(y,u,p=0){let C=a0e(y,65536);const M=[];for(;u.valid();u.next()){const[L,O]=u.get();let U=L.x*65536,W=L.y*65536,J=O.x*65536,se=O.y*65536;const re=J-U,fe=se-W,xe=Math.hypot(re,fe);if(xe===0)continue;U-=re*p,W-=fe*p,J+=re*p,se+=fe*p;const we=Math.trunc(fe/xe*3),je=-Math.trunc(re/xe*3);M.push([[[U,W],[J,se],[J+we,se+je],[U+we,W+je],[U,W]]])}return M.length>0&&(C=mIe(C,M,2)),fIe(C,1/65536,128)}function a0e(y,u=1){return[y.map(p=>p.map(_=>[_.x*u,_.y*u]))]}function fIe(y,u=1,p){return y.map(_=>_.map((C,M)=>{const L=C.map(O=>{let U=O[0],W=O[1];return p&&(U=Math.round(U/p)*p,W=Math.round(W/p)*p),new us(U*u,W*u)._round()});return M>0&&L.reverse(),L}))}class i0e{constructor(u,p){this.layoutVertexArray=new zf,this.indexArray=new Go,this.lineIndexArray=new Bh,this.triangleSegments=new Gi,this.lineSegments=new Gi,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.lut}),this.uploaded=!1,p&&(this.elevatedLayoutVertexArray=new Wd)}update(u,p,_,C,M,L,O,U){this.programConfigurations.updatePaintArrays(u,p,M,_,C,L,O,U)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Nl.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.lineIndexBuffer=u.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,Rc.members))),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(u,p,_,C,M,L,O){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,p,_,C,M,L,void 0,O)}}class w9{constructor(u){this.zoom=u.zoom,this.pixelRatio=u.pixelRatio,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=u.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=u.lut,this.bufferData=new i0e(u,!1),this.elevationBufferData=new i0e(u,!0),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.projection=u.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=u.sourceLayerIndex,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,p){}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){this.hasPattern=Zye("fill",this.layers,this.pixelRatio,p);const M=this.layers[0].layout.get("fill-sort-key"),L=[];for(const{feature:O,id:U,index:W,sourceLayerIndex:J}of u){const se=this.layers[0]._featureFilter.needGeometry,re=Hf(O,se);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),re,_))continue;const fe=M?M.evaluate(re,{},_,p.availableImages):void 0,xe={id:U,properties:O.properties,type:O.type,sourceLayerIndex:J,index:W,geometry:se?re.geometry:bm(O,_,C),patterns:{},sortKey:fe};L.push(xe)}M&&L.sort((O,U)=>O.sortKey-U.sortKey);for(const O of L){const{geometry:U,index:W,sourceLayerIndex:J}=O;if(this.hasPattern){const se=Xye("fill",this.layers,O,this.zoom,this.pixelRatio,p);this.patternFeatures.push(se)}else this.addFeature(O,U,W,_,{},p.availableImages,p.brightness,p.elevationFeatures);p.featureIndex.insert(u[W].feature,U,W,J,this.index)}}update(u,p,_,C,M,L,O){this.bufferData.update(u,p,_,C,M,L,O,this.worldview),this.elevationBufferData.update(u,p,_,C,M,L,O,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(u,p,_,C,M,L,O,this.worldview)}updateExpressions(u){this.bufferData.programConfigurations.updateExpressions(u),this.elevationBufferData.programConfigurations.updateExpressions(u),this.elevatedStructures&&(this.elevatedStructures.bridgeProgramConfigurations.updateExpressions(u),this.elevatedStructures.tunnelProgramConfigurations.updateExpressions(u))}addFeatures(u,p,_,C,M,L){for(const O of this.patternFeatures)this.addFeature(O,O.geometry,O.index,p,_,C,L,u.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(u){this.bufferData.upload(u),this.elevationBufferData.upload(u),this.elevatedStructures&&this.elevatedStructures.upload(u)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(u,p,_,C,M,L=[],O,U){const W=H6(p,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(u,W,C,_,U):this.addGeometry(W,this.bufferData),this.bufferData.populatePaintArrays(u,_,M,L,C,O,this.worldview),this.elevationBufferData.populatePaintArrays(u,_,M,L,C,O,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(u,p,_,C,M){this.elevatedStructures&&(this.elevatedStructures.construct(u),this.elevatedStructures.populatePaintArrays(p,_,C,M,this.worldview))}addElevatedRoadFeature(u,p,_,C,M){const L=new Array,O=E.getElevationFeature(u,M);if(!O)return void this.addGeometry(p,this.bufferData);{const W=this.clipPolygonsToTile(p,1);W.length>0&&L.push({polygons:W,elevationFeature:O,elevationTileID:_})}const U={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(u,{},_),featureIndex:C};for(const W of L)if(W.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new tf(W.elevationTileID,this.layers,this.zoom,this.lut));const se=W.elevationFeature.isTunnel();let re=0;Object.hasOwn(u.properties,u9)&&(re=+u.properties[u9]),this.elevatedStructures.addPortalCandidates(W.elevationFeature.id,W.polygons,se,W.elevationFeature,re)}W.elevationFeature.constantHeight==null&&(W.polygons=this.prepareElevatedPolygons(W.polygons,W.elevationFeature,W.elevationTileID));const J=new f(_,W.elevationTileID);this.addElevatedGeometry(W.polygons,J,W.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,C,U)}}addElevatedGeometry(u,p,_,C,M,L){const O={elevation:_,elevationSampler:p,bias:C,index:M,featureInfo:L},[U,W]=this.addGeometry(u,this.elevationBufferData,O);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:U,max:W}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,U),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,W))}addGeometry(u,p,_){let C=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,L=null;_&&(L=_.elevationSampler.constantElevation(_.elevation,_.bias),L!=null&&(C=L,M=L));const O=(U,W,J)=>{if(_!=null)if(W.push(U),L!=null)p.elevatedLayoutVertexArray.emplaceBack(L),J.push(L);else{const se=_.elevationSampler.pointElevation(U,_.elevation,_.bias);p.elevatedLayoutVertexArray.emplaceBack(se),J.push(se),C=Math.min(C,se),M=Math.max(M,se)}};for(const U of u){let W=0;for(const Ue of U)W+=Ue.length;const J=p.triangleSegments.prepareSegment(W,p.layoutVertexArray,p.indexArray),se=J.vertexLength,re=[],fe=[],xe=[],we=[],je=[],Be=p.layoutVertexArray.length;for(const Ue of U){if(Ue.length===0)continue;Ue!==U[0]&&fe.push(re.length/2);const tt=p.lineSegments.prepareSegment(Ue.length,p.layoutVertexArray,p.lineIndexArray),ot=tt.vertexLength;_&&je.push(p.layoutVertexArray.length-Be),O(Ue[0],xe,we),p.layoutVertexArray.emplaceBack(Ue[0].x,Ue[0].y),p.lineIndexArray.emplaceBack(ot+Ue.length-1,ot),re.push(Ue[0].x),re.push(Ue[0].y);for(let pt=1;pt0&&_&&this.elevationMode==="hd-road-base"){const Ue=_.elevation.isTunnel(),tt=_.elevation.safeArea,ot=this.elevatedStructures.addVertices(xe,we);this.elevatedStructures.addTriangles(Ye,ot,Ue);const pt=je.length;if(pt>0){for(let Rt=0;Rt=_&&fe.max.x<=M&&fe.min.y>=C&&fe.max.y<=L?U:W).push(re)}if(U.length===u.length)return u;const J=[new us(_,C),new us(M,C),new us(M,L),new us(_,L),new us(_,C)],se=U;for(const re of W)se.push(...D0t(re,J));return se}}let pIe,xIe,gIe,yIe;Mr(w9,"FillBucket",{omit:["layers","patternFeatures"]}),Mr(i0e,"FillBufferData"),Mr(tf,"ElevatedStructures");class j9{constructor(u,p,_,C){if(this.triangleCount=p.length/3,this.min=new us(0,0),this.max=new us(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||u.length===0)return;const[M,L]=[u[0].clone(),u[0].clone()];for(let se=1;sese.cellIdx-re.cellIdx||se.triIdx-re.triIdx);let J=0;for(;Jthis.max.x||this.min.x>u.x||u.y>this.max.y||this.min.y>u.y)return;const _=W0(u.x-this.min.x,this.xScale,this.cellsX),C=W0(u.y-this.min.y,this.yScale,this.cellsY),M=this.cells[C*this.cellsX+_];if(M){this._lazyInitLookup();for(let L=0;Lthis.max.x||this.min.x>p.x||u.y>this.max.y||this.min.y>p.y)return;this._lazyInitLookup();const C=W0(u.x-this.min.x,this.xScale,this.cellsX),M=W0(p.x-this.min.x,this.xScale,this.cellsX),L=W0(u.y-this.min.y,this.yScale,this.cellsY),O=W0(p.y-this.min.y,this.yScale,this.cellsY);for(let U=L;U<=O;U++)for(let W=C;W<=M;W++){const J=this.cells[U*this.cellsX+W];if(J)for(let se=0;sep.fqid),this.index=u.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.footprints=[],this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,p){for(const _ of this.footprints)p.push({footprint:_,id:u})}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){const M=[];for(const{feature:L,id:O,index:U,sourceLayerIndex:W}of u){const J=this.layers[0]._featureFilter.needGeometry,se=Hf(L,J);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),se,_))continue;const re={id:O,properties:L.properties,type:L.type,sourceLayerIndex:W,index:U,geometry:J?se.geometry:bm(L,_,C),patterns:{}};M.push(re)}for(const L of M){const{geometry:O,index:U,sourceLayerIndex:W}=L;this.addFeature(L,O,U,_,{},p.availableImages,p.brightness),p.featureIndex.insert(u[U].feature,O,U,W,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(u){}update(u,p,_,C,M,L,O){}destroy(){}addFeature(u,p,_,C,M,L=[],O){for(const U of H6(p,2)){const W=[],J=[],se=[],re=new us(1/0,1/0),fe=new us(-1/0,-1/0);for(const je of U)if(je.length!==0){je!==U[0]&&se.push(J.length/2);for(let Be=0;Beu.max.x||y.max.xu.max.y||y.max.ynew us((U.x+M.x*mr)*O-L.x*mr,(U.y+M.y*mr)*O-L.y*mr))}return l0e(p,C,y.indices,0,y.indices.length,0,0)}function NIe(y,u,p,_){const C=Math.pow(2,_.z-p.z);return new us((y+p.x*mr)*C-_.x*mr,(u+p.y*mr)*C-_.y*mr)}function kIe(y,u){const p=[];u.grid.queryPoint(y,p);const _=u.indices,C=u.vertices;for(let M=0;M0&&(_.length>1&&p.push(_),_=[])}return _.length>1&&p.push(_),p}const d0e=V0.types,W0t=["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"],K0t=["fill-extrusion-flood-light-ground-radius"],Y0t=Math.pow(2,13),Z0t=Math.pow(2,15)-1,C9=new us(0,1),ib=2147483648,T9=1073741824;function Y6(y,u,p,_,C,M,L,O){y.emplaceBack((u<<1)+L,(p<<1)+M,(Math.floor(_*Y0t)<<1)+C,Math.round(O))}function Z6(y,u,p){y.emplaceBack(u.x*mr,u.y*mr,p?1:0)}function E9(y,u,p,_,C,M){y.emplaceBack(u.x,u.y,(p.x<<1)+_,(p.y<<1)+C,M)}function X6(y,u,p){y.emplaceBack(u.x,u.y,u.z,p[0]*16384,p[1]*16384,p[2]*16384)}class CIe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class A9{constructor(){this.data=[]}get length(){return this.data.length}push(u){this.data.push(u)}get(u){return this.data[u]}static serialize(u,p){const _=u.data.length,C=new Uint32Array(4*_),M=[];M.length=_;for(let L=0;L<_;L++){const O=u.data[L],U=4*L;C[U]=O.vertexOffset,C[U+1]=O.vertexCount,C[U+2]=O.indexOffset,C[U+3]=O.indexCount,M[L]=O.ringIndices}return p&&p.add(C.buffer),{scalars:C,rings:M}}static deserialize(u){const{scalars:p,rings:_}=u,C=p.length/4,M=new A9,L=[];L.length=C,M.data=L;for(let O=0;Ou.max.x&&(u.max.x=p.x,C=!0),p.yu.max.y&&(u.max.y=p.y,C=!0),((p.x===0||p.x===mr)&&p.x===_.x)!=((p.y===0||p.y===mr)&&p.y===_.y)&&this.processBorderOverlap(p,_),C&&this.checkBorderIntersection(p,_)}checkBorderIntersection(u,p){p.x<0!=u.x<0&&this.addBorderIntersection(0,Jr(p.y,u.y,(0-p.x)/(u.x-p.x))),p.x>mr!=u.x>mr&&this.addBorderIntersection(1,Jr(p.y,u.y,(mr-p.x)/(u.x-p.x))),p.y<0!=u.y<0&&this.addBorderIntersection(2,Jr(p.x,u.x,(0-p.y)/(u.y-p.y))),p.y>mr!=u.y>mr&&this.addBorderIntersection(3,Jr(p.x,u.x,(mr-p.y)/(u.y-p.y)))}addBorderIntersection(u,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 _=this.borders[u];p<_[0]&&(_[0]=p),p>_[1]&&(_[1]=p)}processBorderOverlap(u,p){if(u.x===p.x){if(u.y===p.y)return;const _=u.x===0?0:1;this.addBorderIntersection(_,p.y),this.addBorderIntersection(_,u.y)}else{const _=u.y===0?2:3;this.addBorderIntersection(_,p.x),this.addBorderIntersection(_,u.x)}}centroid(){return this.accCount===0?new us(0,0):new us(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((u,p)=>u+ +(p[0]!==Number.MAX_VALUE),0):0}}function TIe(y,u){const p=y.add(u)._unit(),_=Mt(y.x*p.x+y.y*p.y,-1,1);var C,M,L;return L=Math.acos(_),Math.min(4,Math.max(-4,Math.tan(L)))/4*Z0t*((C=y).x*(M=u).y-C.y*M.x<0?-1:1)}const X0t=[y=>y.x<0,y=>y.x>mr,y=>y.y<0,y=>y.y>mr];function Q0t(y,u,p,_){const C=[4];if(_===0)return C;p._mult(_);const M=y.sub(p),L=u.sub(p),O=[y,u,M,L];for(let U=0;U<4;U++)for(const W of O)if(X0t[U](W)){C.push(U);break}return C}class h0e{constructor(u){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new f6,this.indexArray=new Go,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.lut},p=>K0t.includes(p)),this._segments=new Gi,this.hiddenByLandmarkVertexArray=new zN,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Gi}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(u,p,_,C=!1){const M=u.length;if(M>2){let L=Math.max(0,this._segments.get().length-1);const O=this._segments._prepareSegment(4*M,this.vertexArray.length,2*this._segmentToGroundQuads[L].length);let U;L!==this._segments.get().length-1&&(L++,this._segmentToGroundQuads[L]=[],this._segmentToRegionTriCounts[L]=[0,0,0,0,0]);{const W=u[0],J=u[1];U=TIe(W.sub(u[M-1])._perp()._unit(),J.sub(W)._perp()._unit())}for(let W=0;WC.region-M.region);for(let _=0;_U+W,0);let O=0;for(let U=0;U<=4;U++){const W=L[U];if(W!==0){let J=this.regionSegments[U];J||(J=this.regionSegments[U]=new Gi);const se={vertexOffset:M.vertexOffset,primitiveOffset:M.primitiveOffset+O,vertexLength:M.vertexLength,primitiveLength:W};J.get().push(se)}O+=W}for(let U=0;U0?this.hiddenByLandmarkVertexBuffer=u.createVertexBuffer(this.hiddenByLandmarkVertexArray,U0t.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let u=0;u<=4;u++){const p=this.regionSegments[u];p&&p.destroy()}}}}class P9{constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaling=u.overscaling,this.layers=u.layers,this.pixelRatio=u.pixelRatio,this.layerIds=this.layers.map(p=>p.fqid),this.index=u.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=u.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=new I9,this.footprintIndices=new Go,this.footprintVertices=new zf,this.footprintSegments=new A9,this.layoutVertexArray=new m6,this.centroidVertexArray=new Q7,this.wallVertexArray=new e9,this.indexArray=new Go,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.lut},p=>W0t.includes(p)),this.segments=new Gi,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.groundEffect=new h0e(u),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,p){}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){this.features=[],this.hasPattern=Zye("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=Jm(_),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:M,id:L,index:O,sourceLayerIndex:U}of u){const W=this.layers[0]._featureFilter.needGeometry,J=Hf(M,W);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),J,_))continue;const se={id:L,sourceLayerIndex:U,index:O,geometry:W?J.geometry:bm(M,_,C),properties:M.properties,type:M.type,patterns:{}},re=this.layoutVertexArray.length,fe=d0e[se.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:M.id,feature:Xye("fill-extrusion",this.layers,se,this.zoom,this.pixelRatio,p)});else if(this.wallMode)for(const xe of se.geometry)for(const we of SIe(xe,fe))this.addFeature(M.id,se,[we],O,_,{},p.availableImages,C,p.brightness);else this.addFeature(M.id,se,se.geometry,O,_,{},p.availableImages,C,p.brightness);p.featureIndex.insert(M,se.geometry,O,U,this.index,re)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(u,p,_,C,M,L){for(const{featureId:O,feature:U}of this.features){const W=d0e[U.type]==="Polygon",{geometry:J}=U;if(this.wallMode)for(const se of J)for(const re of SIe(se,W))this.addFeature(O,U,[re],U.index,p,_,C,M,L);else this.addFeature(O,U,J,U.index,p,_,C,M,L)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(u,p,_,C,M,L,O){this.programConfigurations.updatePaintArrays(u,p,M,_,C,L,O,this.worldview),this.groundEffect.update(u,p,M,_,C,L,O,this.worldview)}updateExpressions(u){this.programConfigurations.updateExpressions(u),this.groundEffect.programConfigurations.updateExpressions(u)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,V0t),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.wallVertexBuffer=u.createVertexBuffer(this.wallVertexArray,$0t.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=u.createVertexBuffer(this.layoutVertexExtArray,q0t.members,!0)),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}uploadCentroid(u){this.groundEffect.uploadHiddenByLandmark(u),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=u.createVertexBuffer(this.centroidVertexArray,z0t.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(u,p,_,C,M,L,O,U,W){const J=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(p,{})/this.tileToMeter,se=[new us(0,0),new us(mr,mr)],re=U.projection,fe=re.name==="globe",xe=this.wallMode||d0e[p.type]==="Polygon",we=new u0e;we.centroidDataIndex=this.centroidData.length;const je=new M9;je.buildingId=u,p.properties&&Object.hasOwn(p.properties,"building_id")&&(je.buildingId=Number(p.properties.building_id)),we.buildingId=je.buildingId;const Be=this.layers[0].paint.get("fill-extrusion-base").evaluate(p,{},M)<=0,Ye=this.layers[0].paint.get("fill-extrusion-height").evaluate(p,{},M);let Ue;if(je.height=Ye,je.vertexArrayOffset=this.layoutVertexArray.length,je.groundVertexArrayOffset=this.groundEffect.vertexArray.length,fe&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new ZT),this.wallMode){if(fe)return void ra("Non zero fill-extrusion-line-width is not yet supported on globe.");if(_.length!==1)return;Ue=function(jt){const At=jt[0].x===jt.at(-1).x&&jt[0].y===jt.at(-1).y;(function(tr){let sr=0;const wr=tr.length;for(let Ar=0;Ar=0})(jt)||(jt=jt.reverse());const is={geometry:[],joinNormals:[],indices:[]},xs=[],ks=[],ws=[];let Ks=jt.length;for(;Ks>=2&&jt[Ks-1].equals(jt[Ks-2]);)Ks--;if(Ks<(At?3:2))return is;let ds,gs,Cs,Bs,Hs,cr=0;for(;cr0;let zr="miter";const Sn=2;zr==="miter"&&Ar>Sn&&(zr="bevel"),zr==="bevel"&&(Ar>100&&(zr="flipbevel"),Ar{const xi=new us(Wn.x,Wn.y),ei=new us(Wn.x,Wn.y);xi.x+=Pa.x*dl,xi.y+=Pa.y*dl,ei.x-=Pa.x*Math.max(ca,1),ei.y-=Pa.y*Math.max(ca,1),ws.push(Pa),xs.push(xi),ks.push(ei)};if(zr==="miter")sr._mult(Ar),si(ds,sr,0,0);else if(zr==="flipbevel")sr=Hs.mult(-1),si(ds,sr,0,0),si(ds,sr.mult(-1),0,0);else{const Wn=-Math.sqrt(Ar*Ar-1),Pa=tn?Wn:0,ca=tn?0:Wn;gs&&si(ds,Bs,Pa,ca),Cs&&si(ds,Hs,Pa,ca)}}is.geometry=[...xs,...ks.reverse(),xs[0]],is.joinNormals=[...ws,...ws.reverse(),ws.at(-1)];const Ds=is.geometry.length-1;for(let tr=0;trjt<(At.length-1)/2||jt===At.length-1,ot=this.wallMode?[_]:H6(_,500);for(let jt=ot.length-1;jt>=0;jt--){const At=ot[jt];(At.length===0||evt(At[0]))&&ot.splice(jt,1)}let pt;if(fe)pt=DIe(ot,se,M);else{pt=[];for(const jt of ot)pt.push({polygon:jt,bounds:se})}const Rt=xe?this.edgeRadius:0,_t=Rt>0&&this.zoom<17,Et=(jt,At)=>{if(jt.length===0)return!1;const ns=jt.at(-1);return At.x===ns.x&&At.y===ns.y};for(const{polygon:jt,bounds:At}of pt){let ns=0,is=0;for(const Ks of jt)xe&&!Ks[0].equals(Ks.at(-1))&&Ks.push(Ks[0]),is+=xe?Ks.length-1:Ks.length;const xs=this.segments.prepareSegment((xe?5:4)*is,this.layoutVertexArray,this.indexArray);je.footprintSegIdx<0&&(je.footprintSegIdx=this.footprintSegments.length),je.polygonSegIdx<0&&(je.polygonSegIdx=this.polygonSegments.length);const ks={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},ws=new CIe;if(ws.vertexOffset=this.footprintVertices.length,ws.indexOffset=3*this.footprintIndices.length,ws.ringIndices=[],xe){const Ks=[],ds=[];ns=xs.vertexLength;for(let Cs=0;Cs4&&IIe(ds[ds.length-2],ds[0],ds[1]),Cs=Rt?J0t(ds[ds.length-2],ds[0],ds[1],Rt):0;const Bs=[];let Hs,cr,Ds;cr=ds[1].sub(ds[0])._perp()._unit();let tr=!0;for(let sr=1,wr=0;sr0?1:0,Pa=Ar.dist(tn);if(wr+Pa>32768&&(wr=0),Rt){Ds=zr.sub(tn)._perp()._unit();let ei=AIe(Ar,tn,zr,EIe(cr,Ds),Rt);isNaN(ei)&&(ei=0);const Vi=tn.sub(Ar)._unit();Ar=Ar.add(Vi.mult(Cs))._round(),tn=tn.add(Vi.mult(-ei))._round(),Cs=ei,cr=Ds,Be&&this.zoom>=17&&(Et(Bs,Ar)||Bs.push(Ar),Et(Bs,tn)||Bs.push(tn))}const ca=xs.vertexLength,dl=ds.length>4&&IIe(Ar,tn,zr);let xi=PIe(wr,gs,tr);if(Y6(this.layoutVertexArray,Ar.x,Ar.y,si,Wn,0,0,xi),Y6(this.layoutVertexArray,Ar.x,Ar.y,si,Wn,0,1,xi),this.wallMode){const ei=tt(sr-1,ds),Vi=Ue.joinNormals[sr-1];Z6(this.wallVertexArray,Vi,ei),Z6(this.wallVertexArray,Vi,ei)}if(wr+=Pa,xi=PIe(wr,dl,!tr),gs=dl,Y6(this.layoutVertexArray,tn.x,tn.y,si,Wn,0,0,xi),Y6(this.layoutVertexArray,tn.x,tn.y,si,Wn,0,1,xi),this.wallMode){const ei=tt(sr,ds),Vi=Ue.joinNormals[sr];Z6(this.wallVertexArray,Vi,ei),Z6(this.wallVertexArray,Vi,ei)}if(xs.vertexLength+=4,this.indexArray.emplaceBack(ca+0,ca+1,ca+2),this.indexArray.emplaceBack(ca+1,ca+3,ca+2),xs.primitiveLength+=2,Rt){const ei=ns+(sr===1?ds.length-2:sr-2),Vi=sr===1?ns:ei+1;if(this.indexArray.emplaceBack(ca+1,ei,ca+3),this.indexArray.emplaceBack(ei,Vi,ca+3),xs.primitiveLength+=2,Hs===void 0&&(Hs=ca),!m0e(zr,ds[sr],At)){const Ro=sr===ds.length-1?Hs:xs.vertexLength;this.indexArray.emplaceBack(ca+2,ca+3,Ro),this.indexArray.emplaceBack(ca+3,Ro+1,Ro),this.indexArray.emplaceBack(ca+3,Vi,Ro+1),xs.primitiveLength+=3}tr=!tr}if(fe){const ei=this.layoutVertexExtArray,Vi=re.projectTilePoint(Ar.x,Ar.y,M),Ro=re.projectTilePoint(tn.x,tn.y,M),Fc=re.upVector(M,Ar.x,Ar.y),eo=re.upVector(M,tn.x,tn.y);X6(ei,Vi,Fc),X6(ei,Vi,Fc),X6(ei,Ro,eo),X6(ei,Ro,eo)}}xe&&(ns+=ds.length-1),Be&&Rt&&this.zoom>=17&&(Bs.length!==0&&Et(Bs,Bs[0])&&Bs.pop(),this.groundEffect.addData(Bs,At,J,Rt>0))}this.footprintSegments.push(ws),ks.triangleCount=this.indexArray.length-ks.triangleArrayOffset,this.polygonSegments.push(ks),++je.footprintSegLen,++je.polygonSegLen}if(je.vertexCount=this.layoutVertexArray.length-je.vertexArrayOffset,je.groundVertexCount=this.groundEffect.vertexArray.length-je.groundVertexArrayOffset,je.vertexCount!==0){if(je.centroidXY=we.borders?C9:this.encodeCentroid(we,je),p.properties&&Object.hasOwn(p.properties,"building_id")){const jt=je.buildingId;let At=this.buildingGroups.get(jt);At||(At={accX:0,accY:0,accCount:0,mergedMin:new us(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new us(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(jt,At)),At.accX+=we.acc.x,At.accY+=we.acc.y,At.accCount+=we.accCount,At.mergedMin.x=Math.min(At.mergedMin.x,je.min.x),At.mergedMin.y=Math.min(At.mergedMin.y,je.min.y),At.mergedMax.x=Math.max(At.mergedMax.x,je.max.x),At.mergedMax.y=Math.max(At.mergedMax.y,je.max.y),At.partIndices.push(this.centroidData.length)}if(this.centroidData.push(je),we.borders){this.featuresOnBorder.push(we);const jt=this.featuresOnBorder.length-1;for(let At=0;Atthis.featuresOnBorder[p].borders[u][0]-this.featuresOnBorder[_].borders[u][0])}splitToSubtiles(){const u=[];for(let O=0;Omr),J=2*W+(+(U.min.x+U.max.x>mr)^W);for(let se=0;seO.triangleSegmentIdx===U.triangleSegmentIdx?O.subtile-U.subtile:O.triangleSegmentIdx-U.triangleSegmentIdx);let _=0,C=0,M=0;for(const O of u){if(O.triangleSegmentIdx!==_)break;M++}const L=u.length;for(;C!==u.length;){_=u[C].triangleSegmentIdx;let O=0,U=C,W=C;for(let J=U;J0&&this.triangleSubSegments.push({segment:fe,min:se,max:re}),U=W;for(let xe=U;xe[we[0]*(1-Be[0])+je[0]*Be[0],we[1]*(1-Be[1])+je[1]*Be[1]],fe=[],xe=[];for(const we of this.triangleSubSegments){fe[0]=we.min.x/mr,fe[1]=we.min.y/mr,xe[0]=we.max.x/mr,xe[1]=we.max.y/mr;const je=re(J,se,fe),Be=re(J,se,xe);if(new So([je[0],je[1],M],[Be[0],Be[1],L]).intersectsPrecise(_)===0){W&&(C.segments.push(W),W=void 0);continue}const Ye=we.segment;W&&W.vertexOffset!==Ye.vertexOffset&&(C.segments.push(W),W=void 0),W?(W.vertexLength+=Ye.vertexLength,W.primitiveLength+=Ye.primitiveLength):W={vertexOffset:Ye.vertexOffset,primitiveLength:Ye.primitiveLength,vertexLength:Ye.vertexLength,primitiveOffset:Ye.primitiveOffset,sortKey:void 0,vaos:{}}}return W&&C.segments.push(W),C}encodeCentroid(u,p){const _=u.centroid(),C=p.span(),M=Math.min(7,Math.round(C.x*this.tileToMeter/10)),L=Math.min(6,Math.round(C.y*this.tileToMeter/10));return new us(Mt(_.x,1,8191)<<3|M,Mt(_.y,1,8191)<<3|L)}encodeBorderCentroid(u){if(!u.borders)return new us(0,0);const p=u.borders,_=Number.MAX_VALUE;if(p[0][0]!==_||p[1][0]!==_){const C=p[0][0]!==_?0:1;return new us(6|(p[0][0]!==_?0:65528),(p[C][0]+p[C][1])/2<<3|6)}{const C=p[2][0]!==_?2:3;return new us((p[C][0]+p[C][1])/2<<3|6,6|(p[2][0]!==_?0:65528))}}showCentroid(u){const p=this.centroidData.get(u.centroidDataIndex);if(p.flags&=ib,p.groupCentroidPos.x!==0||p.groupCentroidPos.y!==0){const _=p.span(),C=Math.min(7,Math.round(_.x*this.tileToMeter/10)),M=Math.min(6,Math.round(_.y*this.tileToMeter/10));p.centroidXY=new us(Mt(p.groupCentroidPos.x,1,8191)<<3|C,Mt(p.groupCentroidPos.y,1,8191)<<3|M)}else p.centroidXY=new us(0,0);this.writeCentroidToBuffer(p)}writeCentroidToBuffer(u){this.groundEffect.updateHiddenByLandmark(u);const p=u.vertexArrayOffset,_=u.vertexCount+u.vertexArrayOffset,C=-1073741824&u.flags?C9:u.centroidXY,M=this.centroidVertexArray.geta_centroid_pos0(p);if(this.centroidVertexArray.geta_centroid_pos1(p)!==C.y||M!==C.x){for(let L=p;L<_;++L)this.centroidVertexArray.emplace(L,C.x,C.y);this.needsCentroidUpdate=!0}}createCentroidsBuffer(){this.centroidVertexArray.resize(this.layoutVertexArray.length),this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const u of this.centroidData)this.writeCentroidToBuffer(u)}updateReplacement(u,p,_){if(p.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=p.updateTime;const C=p.getReplacementRegionsForTile(u.toUnwrapped());if(k9(this.activeReplacements,C))return;if(this.activeReplacements=C,this.centroidVertexArray.length===0)this.createCentroidsBuffer();else for(const L of this.centroidData)L.flags&=1073741823;const M=[];for(const L of this.activeReplacements){if(L.order<_)continue;const O=Math.max(1,Math.pow(2,L.footprintTileId.canonical.z-u.canonical.z));if(L.footprint.buildingIds)for(const U of this.centroidData)U.flags&ib||U.flags&T9||L.min.x>U.max.x||U.min.x>L.max.x||L.min.y>U.max.y||U.min.y>L.max.y||L.footprint.buildingIds.has(U.buildingId)&&(U.flags|=L.clipMask!==S9.None?-1073741824:ib);else for(const U of this.centroidData)if(!(U.flags&ib||U.flags&T9||L.min.x>U.max.x||U.min.x>L.max.x||L.min.y>U.max.y||U.min.y>L.max.y))for(let W=0;Wp!=fe>p&&u<(this.footprintVertices.int16[2*(J+L.vertexOffset)+0]-se)*(p-re)/(fe-re)+se&&(C=!C)}O=U}}return C}getHeightAtTileCoord(u,p){let _=Number.NEGATIVE_INFINITY,C=!0;const M=4*(u+mr)*mr+(p+mr);if(Object.hasOwn(this.partLookup,M)){const U=this.partLookup[M];return U?{height:U.height,hidden:!!(U.flags&ib)}:void 0}const L=this.centroidData.buffer,O=this.centroidData.length;for(let U=0;UL[W+4]||L[W+2]>u||p>L[W+5]||L[W+3]>p)continue;const J=L[W+13];if(J<=_)continue;const se=this.centroidData.get(U);this.footprintContainsPoint(u,p,se)&&(_=J,this.partLookup[M]=se,C=!!(se.flags&ib))}if(_!==Number.NEGATIVE_INFINITY)return{height:_,hidden:C};this.partLookup[M]=void 0}}function EIe(y,u){const p=y.add(u)._unit();return y.x*p.x+y.y*p.y}function J0t(y,u,p,_){const C=u.sub(y)._perp()._unit(),M=p.sub(u)._perp()._unit();return AIe(y,u,p,EIe(C,M),_)}function AIe(y,u,p,_,C){const M=Math.sqrt(1-_*_);return Math.min(y.dist(u)/3,u.dist(p)/3,C*M/_)}function m0e(y,u,p){return y.xp[1].x&&u.x>p[1].x||y.yp[1].y&&u.y>p[1].y}function MIe(y,u){return y.xu[1].x||y.yu[1].y}function evt(y){return y.every(u=>u.x<=0)||y.every(u=>u.x>=mr)||y.every(u=>u.y<=0)||y.every(u=>u.y>=mr)}function IIe(y,u,p){if(y.x<0||y.x>=mr||u.x<0||u.x>=mr||p.x<0||p.x>=mr)return!1;const _=p.sub(u),C=_.perp(),M=y.sub(u);return(_.x*M.x+_.y*M.y)/Math.sqrt((_.x*_.x+_.y*_.y)*(M.x*M.x+M.y*M.y))>-.866&&C.x*M.x+C.y*M.y<0}function PIe(y,u,p){const _=u?2|y:-3&y;return p?1|_:-2&_}function LIe(){const y=Math.PI/32,u=Math.tan(y),p=tb;return p*Math.sqrt(1+2*u*u)-p}function DIe(y,u,p){const _=1<{for(const _t of pt)xe.push({polygon:_t,bounds:Rt})},je=Math.ceil(Math.log2(J)),Be=Math.ceil(Math.log2(se)),Ye=je-Be,Ue=[];for(let pt=0;pt0?0:1);for(let pt=0;ptRt+1?ot.push({polygons:xs,bounds:ws,depth:Rt+1}):we(xs,ws)}if(ks.length){const ws=[new us(_t===0?is:Et.x,_t===1?is:Et.y),jt];Ue.length>Rt+1?ot.push({polygons:ks,bounds:ws,depth:Rt+1}):we(ks,ws)}}return xe}(y,u,Math.ceil((M-C)/11.25),Math.ceil((L-O)/11.25),1,(U,W,J)=>{if(U===0)return .5*(W+J);{const se=Xc((p.y+W/mr)/_);return(ig(.5*(Xc((p.y+J/mr)/_)+se))*_-p.y)*mr}})}function tvt(y,u,p,_,C,M){const L=Math.pow(2,_.z-C.z);for(let O=0;O=U[L]&&(O=u,U=y),O[L]C&&$Ie(O,U,L,C),O[L]M&&$Ie(U,O,L,M)}}function L9(y,u,p,_,C,M){const L=[];for(let O=0;O=_&&xe.x>=_||(fe.x>=_?fe=new us(_,fe.y+(_-fe.x)/(xe.x-fe.x)*(xe.y-fe.y))._round():xe.x>=_&&(xe=new us(_,fe.y+(_-fe.x)/(xe.x-fe.x)*(xe.y-fe.y))._round()),fe.y>=C&&xe.y>=C||(fe.y>=C?fe=new us(fe.x+(C-fe.y)/(xe.y-fe.y)*(xe.x-fe.x),C)._round():xe.y>=C&&(xe=new us(fe.x+(C-fe.y)/(xe.y-fe.y)*(xe.x-fe.x),C)._round()),W&&fe.equals(W.at(-1))||(W=[fe],L.push(W),M&&M.push({progress:{min:je+qIe(Be,Ye,fe)*we,max:1},parentIndex:O,prevPoint:Be,nextPoint:Ye})),W.push(xe),M&&(M.at(-1).progress.max=je+qIe(Be,Ye,xe)*we,M.at(-1).nextPoint=Ye)))))}if(M&&se>0)for(let re=J;reW.t-J.t);let L=0,O=0,U=[];for(_.push(U);L!==y.length;){if(O===M.length){for(;L!==y.length;)U.length!==0&&U.at(-1).equals(y[L])||U.push(y[L]),L++;break}M[O].t<=L?(U.length!==0&&U.at(-1).equals(M[O].point)||U.push(M[O].point),Math.trunc(M[O].t),O++):(U.length!==0&&U.at(-1).equals(y[L])||U.push(y[L]),L++)}}function qIe(y,u,p){return y.x!==u.x?(p.x-y.x)/(u.x-y.x):y.y!==u.y?(p.y-y.y)/(u.y-y.y):0}function Q6(y,u){return y.x*u.x+y.y*u.y}function VIe(y,u){if(y.length===1){let p=0;const _=u[p++];let C;for(;!C||_.equals(C);)if(C=u[p++],!C)return 1/0;for(;p{is[0]=xs,is[1]=ks,is[2]=ws,is[3]=1},ns=LIe();fe>0&&(fe+=ns),xe+=ns;for(const is of re){const xs=[],ks=[];for(const ws of is){const Ks=ws.x+we.x,ds=ws.y+we.y,gs=se.projection.projectTilePoint(Ks,ds,ot),Cs=se.projection.upVector(ot,ws.x,ws.y);let Bs=fe,Hs=xe;if(Be){const cr=WIe(Ks,ds,fe,xe,Be,Ye,Ue,tt);Bs+=cr.base,Hs+=cr.top}fe!==0?At(Et,gs.x+Cs[0]*_t*Bs,gs.y+Cs[1]*_t*Bs,gs.z+Cs[2]*_t*Bs):At(Et,gs.x,gs.y,gs.z),At(jt,gs.x+Cs[0]*_t*Hs,gs.y+Cs[1]*_t*Hs,gs.z+Cs[2]*_t*Hs),rt(Et,Et,je),rt(jt,jt,je),xs.push(new KN(Et[0],Et[1],Et[2])),ks.push(new KN(jt[0],jt[1],jt[2]))}pt.push(xs),Rt.push(ks)}return[pt,Rt]}(y,u,p,_,C,M,L,O,U,W,J):L?function(se,re,fe,xe,we,je,Be,Ye,Ue){const tt=[],ot=[],pt=[0,0,0,1];for(const Rt of se){const _t=[],Et=[];for(const jt of Rt){const At=jt.x+xe.x,ns=jt.y+xe.y,is=WIe(At,ns,re,fe,je,Be,Ye,Ue);pt[0]=At,pt[1]=ns,pt[2]=is.base,pt[3]=1,at(pt,pt,we),pt[3]=Math.max(pt[3],1e-5);const xs=new KN(pt[0]/pt[3],pt[1]/pt[3],pt[2]/pt[3]);pt[0]=At,pt[1]=ns,pt[2]=is.top,pt[3]=1,at(pt,pt,we),pt[3]=Math.max(pt[3],1e-5);const ks=new KN(pt[0]/pt[3],pt[1]/pt[3],pt[2]/pt[3]);_t.push(xs),Et.push(ks)}tt.push(_t),ot.push(Et)}return[tt,ot]}(u,p,_,C,M,L,O,U,W):function(se,re,fe,xe,we){const je=[],Be=[],Ye=we[8]*re,Ue=we[9]*re,tt=we[10]*re,ot=we[11]*re,pt=we[8]*fe,Rt=we[9]*fe,_t=we[10]*fe,Et=we[11]*fe;for(const jt of se){const At=[],ns=[];for(const is of jt){const xs=is.x+xe.x,ks=is.y+xe.y,ws=we[0]*xs+we[4]*ks+we[12],Ks=we[1]*xs+we[5]*ks+we[13],ds=we[2]*xs+we[6]*ks+we[14],gs=we[3]*xs+we[7]*ks+we[15],Cs=ws+Ye,Bs=Ks+Ue,Hs=ds+tt,cr=Math.max(gs+ot,1e-5),Ds=ws+pt,tr=Ks+Rt,sr=ds+_t,wr=Math.max(gs+Et,1e-5);At.push(new KN(Cs/cr,Bs/cr,Hs/cr)),ns.push(new KN(Ds/wr,tr/wr,sr/wr))}je.push(At),Be.push(ns)}return[je,Be]}(u,p,_,C,M)}function WIe(y,u,p,_,C,M,L,O){const U=L*C.getElevationAt(y,u,!0,!0),W=M[0]!==0,J=W?M[1]===0?L*(M[0]/7-450):L*function(se,re,fe){const xe=Math.floor(re[0]/8),we=Math.floor(re[1]/8),je=10*(re[0]-8*xe),Be=10*(re[1]-8*we),Ye=se.getElevationAt(xe,we,!0,!0),Ue=se.getMeterToDEM(fe),tt=Math.floor(.5*(je*Ue-1)),ot=Math.floor(.5*(Be*Ue-1)),pt=se.tileCoordToPixel(xe,we),Rt=2*tt+1,_t=2*ot+1,Et=function(ks,ws,Ks,ds,gs){return[ks.getElevationAtPixel(ws,Ks,!0),ks.getElevationAtPixel(ws+gs,Ks,!0),ks.getElevationAtPixel(ws,Ks+gs,!0),ks.getElevationAtPixel(ws+ds,Ks+gs,!0)]}(se,pt.x-tt,pt.y-ot,Rt,_t),jt=Math.abs(Et[0]-Et[1]),At=Math.abs(Et[2]-Et[3]),ns=Math.abs(Et[0]-Et[2])+Math.abs(Et[1]-Et[3]),is=Math.min(.25,.5*Ue*(jt+At)/Rt),xs=Math.min(.25,.5*Ue*ns/_t);return Ye+Math.max(is*je,xs*Be)}(C,M,O):U;return{base:U+(p===0?-1:p),top:W?Math.max(J+_,U+p+2):U+_}}let wy=null,D9=null,f0e=null,R9=null;const KIe=5120,YIe=5121,ZIe=5122,XIe=5123,QIe=5125,JIe=5126,O9={[KIe]:Int8Array,[YIe]:Uint8Array,[ZIe]:Int16Array,[XIe]:Uint16Array,[QIe]:Uint32Array,[JIe]:Float32Array},rvt={[KIe]:"DT_INT8",[YIe]:"DT_UINT8",[ZIe]:"DT_INT16",[XIe]:"DT_UINT16",[QIe]:"DT_UINT32",[JIe]:"DT_FLOAT32"},J6={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function ePe(y,u,p){const _=p.json.bufferViews.length,C=p.buffers.length;u.bufferView=_,p.json.bufferViews[_]={buffer:C,byteLength:y.byteLength},p.buffers[C]=y}const p0e="KHR_draco_mesh_compression";function nvt(y,u){const p=y.extensions&&y.extensions[p0e];if(!p)return;const _=new wy.Decoder,C=nPe(u,p.bufferView),M=new wy.Mesh;if(!_.DecodeArrayToMesh(C,C.byteLength,M))throw new Error("Failed to decode Draco mesh");const L=u.json.accessors[y.indices],O=O9[L.componentType],U=L.count*O.BYTES_PER_ELEMENT,W=wy._malloc(U);O===Uint16Array?_.GetTrianglesUInt16Array(M,U,W):_.GetTrianglesUInt32Array(M,U,W),ePe(wy.memory.buffer.slice(W,W+U),L,u),wy._free(W);for(const J of Object.keys(p.attributes)){const se=_.GetAttributeByUniqueId(M,p.attributes[J]),re=u.json.accessors[y.attributes[J]],fe=rvt[re.componentType],xe=re.count*J6[re.type]*O9[re.componentType].BYTES_PER_ELEMENT,we=wy._malloc(xe);_.GetAttributeDataArrayForAllPoints(M,se,wy[fe],xe,we),ePe(wy.memory.buffer.slice(we,we+xe),re,u),wy._free(we)}_.destroy(),M.destroy(),delete y.extensions[p0e]}const F9="EXT_meshopt_compression";function avt(y,u){if(!y.extensions||!y.extensions[F9])return;const p=y.extensions[F9],_=new Uint8Array(u.buffers[p.buffer],p.byteOffset||0,p.byteLength||0),C=new Uint8Array(p.count*p.byteStride);f0e.decodeGltfBuffer(C,p.count,p.byteStride,_,p.mode,p.filter),y.buffer=u.buffers.length,y.byteOffset=0,u.buffers[y.buffer]=C.buffer,delete y.extensions[F9]}const tPe=1179937895,sPe=new TextDecoder("utf8");function rPe(y,u){return new URL(y,u).href}async function ivt(y,u,p,_,C){const M=await fetch(rPe(y.uri,_),{signal:C}),L=await M.arrayBuffer();u.buffers[p]=L}function nPe(y,u){const p=y.json.bufferViews[u];return new Uint8Array(y.buffers[p.buffer],p.byteOffset||0,p.byteLength)}async function ovt(y,u,p,_,C){if(y.uri){const M=rPe(y.uri,_),L=await fetch(M,{signal:C}),O=await L.blob(),U=await createImageBitmap(O);u.images[p]=U}else if(y.bufferView!==void 0){const M=nPe(u,y.bufferView),L=new Blob([M],{type:y.mimeType}),O=await createImageBitmap(L);u.images[p]=O}}async function aPe(y,u=0,p,_){const C={json:null,images:[],buffers:[]};if(new Uint32Array(y,u,1)[0]===tPe){const fe=new Uint32Array(y,u);let xe=2;const we=(fe[xe++]>>2)-3,je=fe[xe++]>>2;if(xe++,C.json=JSON.parse(sPe.decode(fe.subarray(xe,xe+je))),xe+=je,xe>>0,Math.ceil(1.2*Ue)),ot=Math.ceil((tt-Ue)/65536);try{return we.grow(ot),je(),!0}catch{return!1}},b:Be}}).then(Ye=>{const{Rb:Ue,Qb:tt,P:ot,T:pt,X:Rt,Ja:_t,La:Et,Qa:jt,Va:At,Wa:ns,eb:is,jb:xs,f:ks,e:ws,yb:Ks,zb:ds,Ab:gs,Bb:Cs,Db:Bs,Gb:Hs}=Ye.instance.exports;we=ws;const cr=(()=>{let Ds=0,tr=0,sr=0,wr=0;return Ar=>{sr&&(Ue(wr),Ue(Ds),tr+=sr,sr=Ds=0),Ds||(tr+=128,Ds=tt(tr));const tn=Ar.length+7&-8;let zr=Ds;tn>=tr&&(sr=tn,zr=wr=tt(tn));for(let Sn=0;Sn{wy=fe,D9=null})),D9}()),re&&J.push(function(){var fe;if(!f0e)return R9!=null||(R9=(fe=fetch(Wm()),WebAssembly.instantiateStreaming(fe,{}).then(xe=>{const{sbrk:we,memory:je,meshopt_decodeVertexBuffer:Be,meshopt_decodeIndexBuffer:Ye,meshopt_decodeIndexSequence:Ue,meshopt_decodeFilterOct:tt,meshopt_decodeFilterQuat:ot,meshopt_decodeFilterExp:pt}=xe.instance.exports,Rt={ATTRIBUTES:Be,TRIANGLES:Ye,INDICES:Ue},_t={OCTAHEDRAL:tt,QUATERNION:ot,EXPONENTIAL:pt};return xe.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer(Et,jt,At,ns,is,xs){const ks=jt+3&-4,ws=we(ks*At),Ks=we(ns.length),ds=new Uint8Array(je.buffer);ds.set(ns,Ks);const gs=Rt[is](ws,jt,At,Ks,ns.length);if(gs===0&&_t[xs]&&_t[xs](ws,ks,At),Et.set(ds.subarray(ws,ws+jt*At)),we(ws-we(0)),gs!==0)throw new Error(`Malformed buffer data: ${gs}`)}}})).then(xe=>{f0e=xe,R9=null})),R9}()),L)for(let fe=0;fe{const O=S0(_,(U,W)=>{U?L(U):M(W)});C&&C.addEventListener("abort",()=>{O.cancel(),L(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:y,type:"arrayBuffer"},u);return aPe(p,0,y,u)}function x0e(y){switch(y){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 g0e(y){switch(y){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 K0{constructor(u,p,_,C){this.context=u,this.format=_,this.useMipmap=C&&C.useMipmap,this.texture=u.gl.createTexture(),this.update(p,{premultiply:C&&C.premultiply})}update(u,p){const _=u&&u instanceof HTMLVideoElement&&u.width===0?u.videoWidth:u.width,C=u&&u instanceof HTMLVideoElement&&u.height===0?u.videoHeight:u.height,{context:M}=this,{gl:L}=M,{x:O,y:U}=p&&p.position?p.position:{x:0,y:0},W=O+_,J=U+C;this.size&&(this.size[0]!==W||this.size[1]!==J)&&(!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),M.pixelStoreUnpackFlipY.set(!1),M.pixelStoreUnpack.set(1),M.pixelStoreUnpackPremultiplyAlpha.set(this.format===L.RGBA8&&(!p||p.premultiply!==!1));const se=u instanceof HTMLImageElement||u instanceof HTMLCanvasElement||u instanceof HTMLVideoElement||u instanceof ImageData||ImageBitmap&&u instanceof ImageBitmap;if(!this.size&&W>0&&J>0){const re=this.useMipmap?Math.floor(Math.log2(Math.max(W,J)))+1:1;L.texStorage2D(L.TEXTURE_2D,re,this.format,W,J),this.size=[W,J]}this.size&&(se?L.texSubImage2D(L.TEXTURE_2D,0,O,U,x0e(this.format),g0e(this.format),u):"data"in u&&u.data&&L.texSubImage2D(L.TEXTURE_2D,0,O,U,_,C,x0e(this.format),g0e(this.format),u.data)),this.useMipmap&&L.generateMipmap(L.TEXTURE_2D)}bind(u,p,_=!1){const{context:C}=this,{gl:M}=C;M.bindTexture(M.TEXTURE_2D,this.texture),u!==this.minFilter&&(M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MAG_FILTER,u),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MIN_FILTER,this.useMipmap&&!_?u===M.NEAREST?M.NEAREST_MIPMAP_NEAREST:M.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),p!==this.wrapS&&(M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_S,p),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_T,p),this.wrapS=p)}bindExtraParam(u,p,_,C,M){const{context:L}=this,{gl:O}=L;O.bindTexture(O.TEXTURE_2D,this.texture),p!==this.magFilter&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,p),this.magFilter=p),u!==this.minFilter&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,this.useMipmap?u===O.NEAREST?O.NEAREST_MIPMAP_NEAREST:O.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),_!==this.wrapS&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,_),this.wrapS=_),C!==this.wrapT&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,C),this.wrapT=C),M!==this.compareMode&&(M?(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_COMPARE_MODE,O.COMPARE_REF_TO_TEXTURE),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_COMPARE_FUNC,M)):O.texParameteri(O.TEXTURE_2D,O.TEXTURE_COMPARE_MODE,O.NONE),this.compareMode=M)}destroy(){const{gl:u}=this.context;u.deleteTexture(this.texture),this.texture=null}}class eD{constructor(u,p){this.context=u,this.texture=p}bind(u,p){const{context:_}=this,{gl:C}=_;C.bindTexture(C.TEXTURE_2D,this.texture),u!==this.minFilter&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,u),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,u),this.minFilter=u),p!==this.wrapS&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,p),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,p),this.wrapS=p)}}const lvt=fa([{name:"a_pos_3f",components:3,type:"Float32"}]),cvt=fa([{name:"a_color_3f",components:3,type:"Float32"}]),dvt=fa([{name:"a_color_4f",components:4,type:"Float32"}]),uvt=fa([{name:"a_uv_2f",components:2,type:"Float32"}]),hvt=fa([{name:"a_normal_3f",components:3,type:"Float32"}]),mvt=fa([{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"}]),fvt=fa([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function oPe(y,u){const p=B9(y.projection,y.zoom,y.width,y.height),_=function(M,L,O,U,W){const J=new di(O.lng-180*vw,O.lat),se=new di(O.lng+180*vw,O.lat),re=M.project(J.lng,J.lat),fe=M.project(se.lng,se.lat),xe=-Math.atan2(fe.y-re.y,fe.x-re.x),we=fu.fromLngLat(O);we.y=Mt(we.y,-1+vw,1-vw);const je=we.toLngLat(),Be=M.project(je.lng,je.lat),Ye=fu.fromLngLat(je);Ye.x+=vw;const Ue=Ye.toLngLat(),tt=M.project(Ue.lng,Ue.lat),ot=cPe(tt.x-Be.x,tt.y-Be.y,xe),pt=fu.fromLngLat(je);pt.y+=vw;const Rt=pt.toLngLat(),_t=M.project(Rt.lng,Rt.lat),Et=cPe(_t.x-Be.x,_t.y-Be.y,xe),jt=Math.abs(ot.x)/Math.abs(Et.y),At=N([]);z(At,At,-xe*(1-(W?0:U)));const ns=N([]);return P(ns,ns,[1,1-(1-jt)*U,1]),ns[4]=-Et.x/Et.y*U,z(ns,ns,xe),T(ns,At,ns),ns}(y.projection,0,y.center,p,u),C=lPe(y);return P(_,_,[C,C,1]),_}function lPe(y){const u=y.projection,p=B9(y.projection,y.zoom,y.width,y.height),_=y0e(u,y.center),C=y0e(u,di.convert(u.center));return Math.pow(2,_*p+(1-p)*C)}function B9(y,u,p,_,C=1/0){const M=y.range;if(!M)return 0;const L=Math.min(C,Math.max(p,_)),O=Math.log2(L/1024);return Kt(M[0]+O,M[1]+O,u)}const vw=1/4e4;function y0e(y,u){const p=Mt(u.lat,-85.051129,vm),_=new di(u.lng-180*vw,p),C=new di(u.lng+180*vw,p),M=y.project(_.lng,p),L=y.project(C.lng,p),O=fu.fromLngLat(_),U=fu.fromLngLat(C),W=L.x-M.x,J=L.y-M.y,se=U.x-O.x,re=U.y-O.y,fe=Math.sqrt((se*se+re*re)/(W*W+J*J));return Math.log2(fe)}function cPe(y,u,p){const _=Math.cos(p),C=Math.sin(p);return{x:y*_-u*C,y:y*C+u*_}}const pvt=new Float64Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]);function dPe(y,u,p){N(y),z(y,y,We(u[2])),D(y,y,We(u[0])),B(y,y,We(u[1])),P(y,y,p),T(y,y,pvt)}function z9(y,u,p,_,C,M,L,O){const U=[p[0]-u[0],p[1]-u[1],0],W=[_[0]-u[0],_[1]-u[1],0];if(ce(U)<1e-12||ce(W)<1e-12)return et(y);const J=ct([],U,W);Te(J,J),oe(W,_,u),U[2]=(M-C)*O,W[2]=(L-C)*O;const se=U;return ct(se,U,W),Te(se,se),yt(y,J,se)}function $9(y,u,p=!1){const _=Li(u.zoom),C=function(M,L,O){const U=L.worldSize,W=[M[12],M[13],M[14]],J=Xc(W[1]/U),se=ym(W[0]/U),re=N([]),fe=ch(1,J)*U,xe=ch(1,0)*U*sb(J,L.zoom),we=1/qn(U);let je=xe*we;if(O){const tt=B9(L.projection,L.zoom,L.width,L.height,1024);je=we*L.projection.pixelSpaceConversion(L.center.lat,U,tt)}const Be=ag(J,se);me(Be,Be,Me([],Te([],Be),fe*je*W[2]));const Ye=function(tt){const ot=[tt[0],tt[1],tt[2]];let pt=[0,1,0];const Rt=ct([],pt,ot);return ct(pt,ot,Rt),Se(pt)===0&&(pt=[0,1,0],ct(Rt,ot,pt)),Te(Rt,Rt),Te(pt,pt),Te(ot,ot),[Rt[0],Rt[1],Rt[2],0,pt[0],pt[1],pt[2],0,ot[0],ot[1],ot[2],0,tt[0],tt[1],tt[2],1]}(Be);P(re,re,[je,je,je*fe]),A(re,re,[-W[0],-W[1],-W[2]]);const Ue=T([],L.globeMatrix,Ye);return T(Ue,Ue,re),T(Ue,Ue,M),Ue}(y,u,p);if(_>0){const M=function(L,O){const U=O.worldSize,W=ch(1,0)*U*sb(O.center.lat,O.zoom)/qn(U),J=ch(1,O.center.lat)*U,se=N([]);B(se,se,We(O.center.lng)),D(se,se,We(O.center.lat)),A(se,se,[0,0,mu]),P(se,se,[W,W,W*J]);const re=O.point;return A(se,se,[-re.x,-re.y,0]),T(se,se,L),T(se,O.globeMatrix,se)}(y,u);return function(L,O,U){const W=(xe,we,je)=>{const Be=ce(xe),Ye=ce(we),Ue=Ys(xe,we,je);return Me(Ue,Ue,1/ce(Ue)*Jr(Be,Ye,je))},J=W([L[0],L[1],L[2]],[O[0],O[1],O[2]],U),se=W([L[4],L[5],L[6]],[O[4],O[5],O[6]],U),re=W([L[8],L[9],L[10]],[O[8],O[9],O[10]],U),fe=Ys([L[12],L[13],L[14]],[O[12],O[13],O[14]],U);return[J[0],J[1],J[2],0,se[0],se[1],se[2],0,re[0],re[1],re[2],0,fe[0],fe[1],fe[2],1]}(C,M,_)}return C}function v0e(y,u,p,_){const C=So.projectAabbCorners(_,p);let M=Number.MAX_VALUE;for(let O=0;O0||je===0&&xe[0]*we[0]+xe[1]*we[1]>=0&&xe[0]*xe[0]+xe[1]*xe[1]>we[0]*we[0]+we[1]*we[1])&&(J=fe)}se=J}while(se!==W);return U.length>0&&U.push(U[0]),U}(C);if(R(y,L))return M}const YN=64,uE={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function U9(y,u,p,_,C,M,L,O,U,W=!1){const J=p.zoom,se=p.project(_),re=sb(_.lat,J),fe=1/re;N(y),A(y,y,[se.x+L[0]*fe,se.y+L[1]*fe,L[2]]);let xe=1,we=1;const je=p.worldSize;if(W){if(p.projection.name==="mercator"){let tt=0;p.elevation&&(tt=p.elevation.getAtPointOrZero(new fu(se.x/je,se.y/je),0));const ot=at([],[se.x,se.y,tt,1],p.projMatrix)[3]/p.cameraToCenterDistance;xe=ot,we=ot*sb(p.center.lat,J)}else if(p.projection.name==="globe"){const tt=$9(y,p),ot=[0,0,0,1];at(ot,ot,T([],p.projMatrix,tt));const pt=ot[3]/p.cameraToCenterDistance,Rt=Li(J),_t=p.projection.pixelsPerMeter(_.lat,je)*sb(_.lat,J),Et=p.projection.pixelsPerMeter(p.center.lat,je)*sb(p.center.lat,J);xe=pt/Jr(_t,n9(p.center.lat),Rt),we=pt*re/_t,xe*=Et,we*=Et}}else xe=fe;P(y,y,[xe,xe,we]);const Be=[...y],Ye=u.orientation,Ue=[];if(dPe(Ue,[Ye[0]+(C?C[0]:0),Ye[1]+(C?C[1]:0),Ye[2]+(C?C[2]:0)],M),T(y,Be,Ue),O&&p.elevation){let tt=0;const ot=[];if(U&&p.elevation){tt=function(Rt,_t,Et,jt,At){const ns=_t.elevation;if(!ns)return 0;const is=So.projectAabbCorners(Et,jt),xs=ch(1,At.lat)*_t.worldSize,ks=function(sr,wr){const Ar=[0,0,1],tn=[{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 zr of tn){const Sn=sr[zr.corners[0]],si=sr[zr.corners[1]],Wn=sr[zr.corners[2]],Pa=[si[0]-Sn[0],si[1]-Sn[1],wr*(si[2]-Sn[2])],ca=ct(Pa,Pa,[Wn[0]-Sn[0],Wn[1]-Sn[1],wr*(Wn[2]-Sn[2])]);Te(ca,ca),zr.dotProductWithUp=ye(ca,Ar)}return tn.sort((zr,Sn)=>zr.dotProductWithUp-Sn.dotProductWithUp),tn[0].corners}(is,xs),ws=is[ks[0]],Ks=is[ks[1]],ds=is[ks[2]],gs=is[ks[3]],Cs=ns.getAtPointOrZero(new fu(ws[0]/_t.worldSize,ws[1]/_t.worldSize),0),Bs=ns.getAtPointOrZero(new fu(Ks[0]/_t.worldSize,Ks[1]/_t.worldSize),0),Hs=ns.getAtPointOrZero(new fu(ds[0]/_t.worldSize,ds[1]/_t.worldSize),0),cr=ns.getAtPointOrZero(new fu(gs[0]/_t.worldSize,gs[1]/_t.worldSize),0),Ds=(Cs+cr)/2,tr=(Bs+Hs)/2;return Ds>tr?Bs=u.gl.NEAREST_MIPMAP_NEAREST}),y.uploaded=!0,y.image=null)}function hPe(y,u,p){y.indexBuffer=u.createIndexBuffer(y.indexArray,!1,!0),y.vertexBuffer=u.createVertexBuffer(y.vertexArray,lvt.members,!1,!0),y.normalArray&&(y.normalBuffer=u.createVertexBuffer(y.normalArray,hvt.members,!1,!0)),y.texcoordArray&&(y.texcoordBuffer=u.createVertexBuffer(y.texcoordArray,uvt.members,!1,!0)),y.colorArray&&(y.colorBuffer=u.createVertexBuffer(y.colorArray,(y.colorArray.bytesPerElement===12?cvt:dvt).members,!1,!0)),y.featureArray&&(y.pbrBuffer=u.createVertexBuffer(y.featureArray,fvt.members,!0)),y.segments=Gi.simpleSegment(0,0,y.vertexArray.length,y.indexArray.length);const _=y.material;_.pbrMetallicRoughness.baseColorTexture&&tD(_.pbrMetallicRoughness.baseColorTexture,u),_.pbrMetallicRoughness.metallicRoughnessTexture&&tD(_.pbrMetallicRoughness.metallicRoughnessTexture,u),_.normalTexture&&tD(_.normalTexture,u),_.occlusionTexture&&tD(_.occlusionTexture,u,p),_.emissionTexture&&tD(_.emissionTexture,u)}function b0e(y,u,p){if(y.meshes)for(const _ of y.meshes)hPe(_,u,p);if(y.lodMeshes)for(const _ of y.lodMeshes)hPe(_,u,p);if(y.children)for(const _ of y.children)b0e(_,u,p)}function mPe(y){y.indexArray.destroy(),y.vertexArray.destroy(),y.colorArray&&y.colorArray.destroy(),y.normalArray&&y.normalArray.destroy(),y.texcoordArray&&y.texcoordArray.destroy(),y.featureArray&&y.featureArray.destroy()}function q9(y){if(y.meshes)for(const u of y.meshes)mPe(u);if(y.lodMeshes)for(const u of y.lodMeshes)mPe(u);if(y.children)for(const u of y.children)q9(u)}function fPe(y){var u;y.vertexBuffer&&(y.vertexBuffer.destroy(),y.indexBuffer.destroy(),y.normalBuffer&&y.normalBuffer.destroy(),y.texcoordBuffer&&y.texcoordBuffer.destroy(),y.colorBuffer&&y.colorBuffer.destroy(),y.pbrBuffer&&y.pbrBuffer.destroy(),y.segments.destroy(),y.material&&((u=y.material).pbrMetallicRoughness.baseColorTexture&&u.pbrMetallicRoughness.baseColorTexture.gfxTexture&&u.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),u.pbrMetallicRoughness.metallicRoughnessTexture&&u.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&u.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),u.normalTexture&&u.normalTexture.gfxTexture&&u.normalTexture.gfxTexture.destroy(),u.emissionTexture&&u.emissionTexture.gfxTexture&&u.emissionTexture.gfxTexture.destroy(),u.occlusionTexture&&u.occlusionTexture.gfxTexture&&u.occlusionTexture.gfxTexture.destroy()))}function _0e(y){if(y.meshes)for(const u of y.meshes)fPe(u);if(y.lodMeshes)for(const u of y.lodMeshes)fPe(u);if(y.footprintDebugMesh&&(y.footprintDebugMesh.vertexBuffer.destroy(),y.footprintDebugMesh.indexBuffer.destroy(),y.footprintDebugMesh.segments.destroy()),y.children)for(const u of y.children)_0e(u)}function w0e(y,u,p,_){return y[0]<=_[0]&&u[0]>=p[0]&&y[1]<=_[1]&&u[1]>=p[1]&&y[2]<=_[2]&&u[2]>=p[2]}function xvt(y,u,p,_,C,M,L,O,U,W,J){const se=.5*(W[0]+J[0]),re=.5*(W[1]+J[1]),fe=.5*(W[2]+J[2]),xe=.5*(J[0]-W[0]),we=.5*(J[1]-W[1]),je=.5*(J[2]-W[2]),Be=y-se,Ye=u-re,Ue=p-fe,tt=_-se,ot=C-re,pt=M-fe,Rt=L-se,_t=O-re,Et=U-fe,jt=tt-Be,At=ot-Ye,ns=pt-Ue,is=Rt-tt,xs=_t-ot,ks=Et-pt,ws=Be-Rt,Ks=Ye-_t,ds=Ue-Et;let gs,Cs,Bs,Hs,cr,Ds;if(gs=Ue*At-Ye*ns,Cs=pt*At-ot*ns,Bs=Et*At-_t*ns,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ns)*we+Math.abs(At)*je,Hs>Ds||cr<-Ds||(gs=Ue*xs-Ye*ks,Cs=pt*xs-ot*ks,Bs=Et*xs-_t*ks,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ks)*we+Math.abs(xs)*je,Hs>Ds||cr<-Ds)||(gs=Ue*Ks-Ye*ds,Cs=pt*Ks-ot*ds,Bs=Et*Ks-_t*ds,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ds)*we+Math.abs(Ks)*je,Hs>Ds||cr<-Ds)||(gs=Be*ns-Ue*jt,Cs=tt*ns-pt*jt,Bs=Rt*ns-Et*jt,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ns)*xe+Math.abs(jt)*je,Hs>Ds||cr<-Ds)||(gs=Be*ks-Ue*is,Cs=tt*ks-pt*is,Bs=Rt*ks-Et*is,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ks)*xe+Math.abs(is)*je,Hs>Ds||cr<-Ds)||(gs=Be*ds-Ue*ws,Cs=tt*ds-pt*ws,Bs=Rt*ds-Et*ws,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(ds)*xe+Math.abs(ws)*je,Hs>Ds||cr<-Ds)||(gs=Ye*jt-Be*At,Cs=ot*jt-tt*At,Bs=_t*jt-Rt*At,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(At)*xe+Math.abs(jt)*we,Hs>Ds||cr<-Ds)||(gs=Ye*is-Be*xs,Cs=ot*is-tt*xs,Bs=_t*is-Rt*xs,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(xs)*xe+Math.abs(is)*we,Hs>Ds||cr<-Ds)||(gs=Ye*ws-Be*Ks,Cs=ot*ws-tt*Ks,Bs=_t*ws-Rt*Ks,Hs=Math.min(gs,Cs,Bs),cr=Math.max(gs,Cs,Bs),Ds=Math.abs(Ks)*xe+Math.abs(ws)*we,Hs>Ds||cr<-Ds)||(Hs=Math.min(Be,tt,Rt),cr=Math.max(Be,tt,Rt),Hs>xe||cr<-xe)||(Hs=Math.min(Ye,ot,_t),cr=Math.max(Ye,ot,_t),Hs>we||cr<-we)||(Hs=Math.min(Ue,pt,Et),cr=Math.max(Ue,pt,Et),Hs>je||cr<-je))return!1;const tr=At*ks-ns*xs,sr=ns*is-jt*ks,wr=jt*xs-At*is,Ar=-(tr*Be+sr*Ye+wr*Ue);return Ds=xe*Math.abs(tr)+we*Math.abs(sr)+je*Math.abs(wr),!(Math.abs(Ar)>Ds)}const gvt=[];class pPe{serializeFromGltf(u,p,_,C){if(u.length<7)return;let M=0;if(u[M++]!==109||u[M++]!==98||u[M++]!==120||u[M++]!==98||u[M++]!==118||u[M++]!==104||u[M++]!==43)return;const L=new DataView(u.buffer,u.byteOffset),O=L.getUint16(M,!0);if(M+=2,O===0)return;this._nodes=[];let U=0;for(let J=0;J0;){const M=_.pop(),L=this._nodes[M];if(L.aabbMax[2]<=C)continue;if(L.backChild===65535){for(let fe=0;fe=0?C:null}}function ZN(y,u){const p=y.json.bufferViews[u.bufferView],_=O9[u.componentType];return new _(y.buffers[p.buffer],(u.byteOffset||0)+(p.byteOffset||0),u.count*(p.byteStride&&p.byteStride!==J6[u.type]*_.BYTES_PER_ELEMENT?p.byteStride/_.BYTES_PER_ELEMENT:J6[u.type]))}function j0e(y,u,p,_){const C=O9[u.componentType],M=function(J){switch(J){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(C),L=y.json.bufferViews[u.bufferView],O=L.byteStride?L.byteStride/C.BYTES_PER_ELEMENT:J6[u.type],U=p.float32,W=U.length/p.capacity;for(let J=0,se=0;J0){for(let je=0;je0){M.texcoordArray=new z0;const re=u.json.accessors[C.TEXCOORD_0];M.texcoordArray.resize(re.count);const fe=ZN(u,re);j0e(u,re,M.texcoordArray,fe)}if(C._FEATURE_ID_RGBA4444!==void 0){const re=u.json.accessors[C._FEATURE_ID_RGBA4444];u.json.extensionsUsed&&u.json.extensionsUsed.includes("EXT_meshopt_compression")&&(M.featureData=ZN(u,re))}C._FEATURE_RGBA4444!==void 0&&(M.featureData=new Uint32Array(ZN(u,u.json.accessors[C._FEATURE_RGBA4444]).buffer));const se=y.material;return M.material=function(re,fe){const{emissiveFactor:xe=[0,0,0],alphaMode:we="OPAQUE",alphaCutoff:je=.5,normalTexture:Be,occlusionTexture:Ye,emissiveTexture:Ue,doubleSided:tt,name:ot}=re,{baseColorFactor:pt=[1,1,1,1],metallicFactor:Rt=1,roughnessFactor:_t=1,baseColorTexture:Et,metallicRoughnessTexture:jt}=re.pbrMetallicRoughness||{},At=Ye?fe[Ye.index]:void 0;if(Ye&&Ye.extensions&&Ye.extensions.KHR_texture_transform&&At){const ns=Ye.extensions.KHR_texture_transform;At.offsetScale=[ns.offset[0],ns.offset[1],ns.scale[0],ns.scale[1]]}return{name:ot,pbrMetallicRoughness:{baseColorFactor:new Wa(...pt),metallicFactor:Rt,roughnessFactor:_t,baseColorTexture:Et?fe[Et.index]:void 0,metallicRoughnessTexture:jt?fe[jt.index]:void 0},doubleSided:tt,emissiveFactor:new Wa(...xe),alphaMode:we,alphaCutoff:je,normalTexture:Be?fe[Be.index]:void 0,occlusionTexture:At,emissionTexture:Ue?fe[Ue.index]:void 0,defined:re.defined===void 0}}(se!==void 0?u.json.materials[se]:{defined:!1},p),M}function N0e(y,u,p){const{matrix:_,rotation:C,translation:M,scale:L,mesh:O,extras:U,children:W,name:J}=y,se={};if(se.name=J,se.localMatrix=_||function(re,fe,xe,we){var je=fe[0],Be=fe[1],Ye=fe[2],Ue=fe[3],tt=je+je,ot=Be+Be,pt=Ye+Ye,Rt=je*tt,_t=je*ot,Et=je*pt,jt=Be*ot,At=Be*pt,ns=Ye*pt,is=Ue*tt,xs=Ue*ot,ks=Ue*pt,ws=we[0],Ks=we[1],ds=we[2];return re[0]=(1-(jt+ns))*ws,re[1]=(_t+ks)*ws,re[2]=(Et-xs)*ws,re[3]=0,re[4]=(_t-ks)*Ks,re[5]=(1-(Rt+ns))*Ks,re[6]=(At+is)*Ks,re[7]=0,re[8]=(Et+xs)*ds,re[9]=(At-is)*ds,re[10]=(1-(Rt+jt))*ds,re[11]=0,re[12]=xe[0],re[13]=xe[1],re[14]=xe[2],re[15]=1,re}([],C||[0,0,0,1],M||[0,0,0],L||[1,1,1]),se.globalMatrix=b(se.localMatrix),O!==void 0){se.meshes=p[O];const re=se.anchor=[0,0];for(const fe of se.meshes){const{min:xe,max:we}=fe.aabb;re[0]+=xe[0]+we[0],re[1]+=xe[1]+we[1]}re[0]=Math.floor(re[0]/se.meshes.length/2),re[1]=Math.floor(re[1]/se.meshes.length/2)}if(U&&(U.id&&(se.id=U.id),U.lights&&(se.lights=function(re){if(!re.length)return[];const fe=function(Ye){const Ue=atob(Ye),tt=new Uint8Array(Ue.length);for(let ot=0;ot=Ue.length||je>=Ue.length||Be>=Ue.length||Ye>=Ue.length)return null;const tt=Ue[we],ot=Ue[je],pt=Ue[Be],Rt=Ue[Ye];if(tt.bufferView===void 0||ot.bufferView===void 0||pt.bufferView===void 0||Rt.bufferView===void 0)return null;const _t=re.json.bufferViews;if(tt.bufferView>=_t.length||ot.bufferView>=_t.length||pt.bufferView>=_t.length||Rt.bufferView>=_t.length)return null;const Et=_t[tt.bufferView],jt=_t[ot.bufferView],At=_t[pt.bufferView],ns=_t[Rt.bufferView];if(Et.buffer>=re.buffers.length||jt.buffer>=re.buffers.length||At.buffer>=re.buffers.length||ns.buffer>=re.buffers.length)return null;const is=(cr,Ds,tr)=>cr>=0&&cr<=tr&&Ds<=tr-cr,xs=tt.byteOffset||0,ks=ot.byteOffset||0,ws=pt.byteOffset||0,Ks=Rt.byteOffset||0;if(!(is(xs,0,Et.byteLength)&&is(ks,3*ot.count*4,jt.byteLength)&&is(ws,3*pt.count*4,At.byteLength)&&is(Ks,4*Rt.count,ns.byteLength)))return null;const ds=new Uint8Array(re.buffers[Et.buffer],(Et.byteOffset||0)+xs,Et.byteLength-xs),gs=new Float32Array(re.buffers[jt.buffer],(jt.byteOffset||0)+ks,3*ot.count),Cs=new Float32Array(re.buffers[At.buffer],(At.byteOffset||0)+ws,3*pt.count),Bs=new Uint32Array(re.buffers[ns.buffer],(ns.byteOffset||0)+Ks,Rt.count),Hs=new pPe;if(Hs.serializeFromGltf(ds,gs,Cs,Bs),xe!==void 0&&re.json.meshes&&re.json.meshes[xe]){const cr=re.json.meshes[xe].primitives[0];if(cr&&cr.attributes.POSITION!==void 0&&cr.attributes.POSITION1&&_.at(-1).equals(_[0])&&_.pop();let C=0;for(let L=0;L<_.length;L++){const O=_[L],U=_[(L+1)%_.length],W=_[(L+2)%_.length];C+=(O.x-U.x)*(W.y-U.y)-(W.x-U.x)*(O.y-U.y)}C>0&&_.reverse();const M=Iu(_.flatMap(L=>[L.x,L.y]),[]);return M.length===0?null:{vertices:_,indices:M}}function _vt(y,u){const p=[],_=[];let C=0;const M=[];for(const L of y){C=p.length;const O=L.vertexArray.float32,U=L.indexArray.uint16;for(let W=0;W0&&([_[L+1],_[L+2]]=[_[L+2],_[L+1]])}return{vertices:p,indices:_}}function xPe(y,u){for(let p=0;p0){const we=Array.from(xe.values()).sort((je,Be)=>je-Be);for(let je=we.length-1;je>=0;je--)J.splice(we[je],1)}})(U,O,y.json.nodes);const W=_?xPe(_,"LOD"):-1;if(W>=0){const J=_[W].nodes,se=new Map;for(const re of J){const fe=N0e(M[re],y,p);fe.id&&se.set(fe.id,fe)}for(const re of U)if(re.id){const fe=se.get(re.id);fe&&fe.meshes&&(re.lodMeshes=fe.meshes,fe.meshBVH&&(re.meshBVH=fe.meshBVH))}}return U}function wvt(y){y.heightmap=new Float32Array(4096),y.heightmap.fill(-1);const u=y.vertexArray.float32,p=y.aabb.min[0]-1,_=y.aabb.min[1]-1,C=YN/(y.aabb.max[0]-p+2),M=YN/(y.aabb.max[1]-_+2);for(let L=0;Ly.heightmap[W*YN+U]&&(y.heightmap[W*YN+U]=O)}}function gPe(y,u,p,_,C){p.reserve(p.length+4*y.length),_.reserve(_.length+10*y.length),C.reserve(C.length+10*y.length);let M=_.length;for(const L of y){const O=Math.min(10,Math.max(4,1.3*L.height))*u,U=[-L.normal[1],L.normal[0],0],W=Math.min(.29,.1*L.width/L.depth),J=L.width-2*L.depth*u*(W+.01),se=Pe([],L.pos,U,J/2),re=Pe([],L.pos,U,-J/2),fe=[se[0],se[1],se[2]+L.height],xe=[re[0],re[1],re[2]+L.height],we=Pe([],L.normal,U,W);Me(we,we,O);const je=Pe([],L.normal,U,-W);Me(je,je,O),me(we,se,we),me(je,re,je),se[2]+=.1,re[2]+=.1,_.emplaceBack(we[0],we[1],we[2]),_.emplaceBack(je[0],je[1],je[2]),_.emplaceBack(se[0],se[1],se[2]),_.emplaceBack(re[0],re[1],re[2]),_.emplaceBack(fe[0],fe[1],fe[2]),_.emplaceBack(xe[0],xe[1],xe[2]),_.emplaceBack(se[0],se[1],se[2]),_.emplaceBack(re[0],re[1],re[2]),_.emplaceBack(we[0],we[1],we[2]),_.emplaceBack(je[0],je[1],je[2]);const Be=J/O/2;C.emplaceBack(-Be-W,-1,Be,.8),C.emplaceBack(Be+W,-1,Be,.8),C.emplaceBack(-Be,0,Be,1.3),C.emplaceBack(Be,0,Be,1.3),C.emplaceBack(Be+W,-.8,Be,.7),C.emplaceBack(Be+W,-.8,Be,.7),C.emplaceBack(0,0,Be,1.3),C.emplaceBack(0,0,Be,1.3),C.emplaceBack(Be+W,-1.2,Be,.8),C.emplaceBack(Be+W,-1.2,Be,.8),p.emplaceBack(6+M,4+M,8+M),p.emplaceBack(7+M,9+M,5+M),p.emplaceBack(0+M,1+M,2+M),p.emplaceBack(1+M,3+M,2+M),M+=10}}function jvt(y,u){const p={};p.indexArray=new Go,p.vertexArray=new Zm,p.colorArray=new gy,gPe(y,u,p.indexArray,p.vertexArray,p.colorArray);const _={defined:!0};_.emissiveFactor=Wa.black;const C={};return C.baseColorFactor=Wa.white,_.pbrMetallicRoughness=C,p.material=_,p.aabb=new So([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),p}Mr(pPe,"ModelBVH");const yPe=fa([{name:"a_pos_3f",components:3,type:"Float32"}]),Nvt=fa([{name:"a_normal_3",components:3,type:"Int16"}]),kvt=fa([{name:"a_centroid_3",components:3,type:"Int16"}]),vPe=fa([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),Svt=fa([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Cvt=fa([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Tvt=fa([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Evt=fa([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),Avt=fa([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),S0e=4096;class Mvt{constructor(u){this.module=u,this.memoryStack=this.module.malloc(S0e),this.memoryStackNextFree=this.memoryStack}createIntArray(u){const p=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>S0e?-1:(new Int32Array(this.module.heap32.buffer,p,u.length).set(u),p)}createFloatArray(u){const p=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>S0e?-1:(new Float32Array(this.module.heapF32.buffer,p,u.length).set(u),p)}readStringBuffer(u){let p="";for(;this.module.heapU8[u]!==0;)p+=String.fromCharCode(this.module.heapU8[u]),++u;return p}setStyle(u){const p=u.normalScale;this.module.setStyle(p[0],p[1],p[2],u.tileToMeters)}setAOOptions(u,p){this.module.setAOOptions(u?1:0,p)}setMetricOptions(u,p){this.module.setMetricOptions(u?1:0,p)}setStructuralOptions(u){this.module.setStructuralOptions(u?1:0)}setFacadeOptions(u,p){this.module.setFacadeOptions(u,p?1:0)}setFauxFacadeOptions(u,p,_){this.module.setFauxFacadeOptions(u?1:0,p?1:0,_)}setFacadeClassifierOptions(u){this.module.setFacadeClassifierOptions(u)}generateMesh(u,p){this.memoryStackNextFree=this.memoryStack;for(const O of u){const U=this.createIntArray(O.ringIndices),W=this.createFloatArray(O.coordinates);if(U===-1||W===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(O.id,O.sourceId,O.minHeight,O.height,O.roofType,W,U,O.ringIndices.length-1)}for(const O of p){let U;U=O.entrances?JSON.parse(O.entrances):[];const W=this.createFloatArray(U),J=this.createFloatArray(O.coordinates);if(W===-1||J===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(O.sourceId,O.crossPerc,O.distanceToRoad,W,U.length,J,O.coordinates.length)}if(!this.module.generateMesh()){const O=this.module.getLastError();return this.readStringBuffer(O)}const _=this.module.getMeshCount(),C=new Array(_);for(let O=0;O<_;O++){const U=this.module.getPositionsPtr(O),W=this.module.getPositionsLength(O),J=new Float32Array(this.module.heapF32.buffer,U,W),se=this.module.getNormalsPtr(O),re=this.module.getNormalsLength(O),fe=new Float32Array(this.module.heapF32.buffer,se,re),xe=this.module.getAOPtr(O),we=this.module.getAOLength(O),je=new Float32Array(this.module.heapF32.buffer,xe,we),Be=this.module.getUVPtr(O),Ye=this.module.getUVLength(O),Ue=new Float32Array(this.module.heapF32.buffer,Be,Ye),tt=this.module.getFauxFacadePtr(O),ot=this.module.getFauxFacadeLength(O),pt=new Uint8Array(this.module.heapU8.buffer,tt,ot),Rt=this.module.getIndicesPtr(O),_t=this.module.getIndicesLength(O),Et=new Int16Array(this.module.heap16.buffer,Rt,_t),jt=this.module.getBuildingPart(O);C[O]={positions:J,normals:fe,ao:je,uv:Ue,isFauxFacade:pt,indices:Et,buildingPart:jt}}const M=this.module.getRingCount(),L=[];for(let O=0;Op||C.y<-u||C.y>p)return!1;return!0}function Pvt(y){switch(y){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: ${y}`)}}let hE=null,_Pe=null,Fp=null;class C0e{constructor(){this.layoutVertexArray=new Zm,this.layoutAttenuationArray=new gy,this.layoutColorArray=new Bh,this.indexArray=new Go,this.indexArrayForConflation=new Go,this.segmentsBucket=new Gi}}class T0e{constructor(u){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Gi,this.entranceBloom=new C0e;const p=66560;this.layoutVertexArray=new Zm,this.layoutVertexArray.reserve(p),this.layoutNormalArray=new K1,this.layoutNormalArray.reserve(p),this.layoutCentroidArray=new K1,this.layoutCentroidArray.reserve(p),this.layoutColorArray=new Bh,this.layoutColorArray.reserve(p),this.layoutFloodLightDataArray=new uw,this.layoutFloodLightDataArray.reserve(p),this.layoutAOArray=new zN,this.layoutAOArray.reserve(p),this.indexArray=new Go,this.indexArray.reserve(66560),this.indexArrayForConflation=new Go,this.segmentsBucket=new Gi,this.entranceBloom=new C0e,u&&(this.layoutFacadePaintArray=new Bh,this.layoutFacadeDataArray=new dw,this.layoutFacadeVerticalRangeArray=new Bh)}reserve(u,p,_){this.layoutVertexArray.reserveForAdditional(u),this.layoutCentroidArray.reserveForAdditional(u),this.layoutFloodLightDataArray.reserveForAdditional(u),this.layoutNormalArray.reserveForAdditional(u),this.layoutAOArray.reserveForAdditional(u),this.layoutColorArray.reserveForAdditional(u),this.indexArray.reserveForAdditional(p),_&&(this.layoutFacadePaintArray.reserveForAdditional(u),this.layoutFacadeDataArray.reserveForAdditional(u),this.layoutFacadeVerticalRangeArray.reserveForAdditional(u))}}class wPe{constructor(u){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new z0,this.footprintsIndices=new yy,this.footprintsMin=new us(1/0,1/0),this.footprintsMax=new us(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new T0e(!1),this.buildingWithFacade=new T0e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=u.zoom,this.canonical=u.canonical,this.layers=u.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=u.index,this.hasPattern=!1,this.worldview=u.worldview,this.lut=u.lut,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.lut}),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.projection=u.projection,this.groundEffect=new h0e(u),this.groundEffect.groundRadiusArray=new Wd,this.hasAppearances=null}updateFootprints(u,p){const _=new j9([],[],1),C={vertices:[],indices:new Uint32Array(0),grid:_,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};p.push({footprint:C,id:u})}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){if(!Fp)return;const M=Jm(_);this.tileToMeter=M,this.brightness=p.brightness,Fp.setStyle({normalScale:[1,-1,M],tileToMeters:M}),Fp.setAOOptions(!1,.3),Fp.setMetricOptions(!1,16),Fp.setStructuralOptions(!0),Fp.setFacadeClassifierOptions(3);const L=new Map,O=new Map;let U=0;for(const{feature:je}of u){if(bPe[je.type]!=="LineString"){L.set(je.id,je.properties.source_id);continue}const Be=this.layers[0]._featureFilter.needGeometry;if(Be&&!this.layers[0]._featureFilter.filter(new fi(this.zoom),je,_))continue;const Ye=Hf(je,Be);if(!Be&&!this.layers[0]._featureFilter.filter(new fi(this.zoom),Ye,_))continue;const Ue=Be?Ye.geometry:bm(je,_,C),tt=[];for(const _t of Ue)for(const Et of _t)tt.push(Et.x),tt.push(Et.y);const ot={coordinates:tt,crossPerc:je.properties.cross_perc,distanceToRoad:je.properties.distance_to_road,entrances:je.properties.entrances,sourceId:0},pt=je.properties.source_id;let Rt=O.get(pt);Rt||(Rt=[],O.set(pt,Rt)),Rt.push(ot),++U}this.maxHeight=0;const W=new Array,J=new Set,se=je=>{je!=null&&J.add(je)},re=(je,Be)=>{je!=null&&W.push({buildingId:je,footprintIndex:Be})},fe=64*(u.length-U),xe=fe/2;this.buildingWithFacade.reserve(fe,xe,!0),this.buildingWithoutFacade.reserve(2*fe,2*xe,!1),this.footprintsIndices.reserve(16*(u.length-U)),this.footprintsVertices.reserve(8*(u.length-U));for(const{feature:je,id:Be,index:Ye,sourceLayerIndex:Ue}of u){if(bPe[je.type]==="LineString")continue;const tt=this.layers[0]._featureFilter.needGeometry;if(tt&&!this.layers[0]._featureFilter.filter(new fi(this.zoom),je,_))continue;let ot=null;if(je.properties&&Object.hasOwn(je.properties,"building_id")&&(ot=Number(je.properties.building_id),J.has(ot)))continue;const pt=Hf(je,tt);if(!tt&&!this.layers[0]._featureFilter.filter(new fi(this.zoom),pt,_))continue;const Rt=tt?pt.geometry:bm(je,_,C),_t=H6(Rt,500);let Et=!1;for(const xa of _t)if(xa.length!==1){Et=!0;break}if(Et){se(ot);continue}if(!Ivt(Rt,163)){se(ot);continue}const jt=this.layers[0],At=Pvt(jt.layout.get("building-roof-shape").evaluate(je,{},_)),ns=jt.layout.get("building-base").evaluate(je,{},_),is=jt.layout.get("building-height").evaluate(je,{},_),xs=jt.layout.get("building-flood-light-ground-radius").evaluate(je,{},_),ks=jt.paint.get("building-ambient-occlusion-intensity"),ws=xs/this.tileToMeter;je.properties["building-part"]="roof";const Ks=jt.paint.get("building-color").evaluate(je,{},this.canonical).toPremultipliedRenderColor(this.lut),ds=jt.paint.get("building-emissive-strength").evaluate(je,{},this.canonical);je.properties["building-part"]="wall";const gs=jt.paint.get("building-color").evaluate(je,{},this.canonical).toPremultipliedRenderColor(this.lut),Cs=jt.paint.get("building-emissive-strength").evaluate(je,{},this.canonical);je.properties["building-part"]="window";const Bs=jt.paint.get("building-color").evaluate(je,{},this.canonical).toPremultipliedRenderColor(this.lut),Hs=jt.paint.get("building-emissive-strength").evaluate(je,{},this.canonical);je.properties["building-part"]="door";const cr=jt.paint.get("building-color").evaluate(je,{},this.canonical).toPremultipliedRenderColor(this.lut),Ds=jt.paint.get("building-emissive-strength").evaluate(je,{},this.canonical);let tr=jt.layout.get("building-flood-light-wall-radius").evaluate(je,{},_);tr=Mt(tr,0,2048);const sr=tr/2048*V9,wr=L.get(Be),Ar=O.get(wr)||[],tn=Ar.length!==0&&jt.layout.get("building-facade").evaluate(je,{},_);Fp.setFacadeOptions(4,!0),Fp.setFauxFacadeOptions(tn,!1,1);let zr=0,Sn=0,si=0,Wn=0,Pa=0,ca=0,dl=0,xi=0,ei=0,Vi=0,Ro=0;if(tn){let xa=Math.round(jt.layout.get("building-facade-floors").evaluate(je,{},_));if(ns===0){xa=Math.max(1,xa-(Ar.length>0?1:0));let hl=4;if(is>100){const jc=[10,13,15];hl=jc[je.id?je.id%jc.length:0]}else is<=10&&(hl=3);Fp.setFacadeOptions(hl,!0),Pa=(is<15?1.3:1.61803)*hl/M}else Pa=ns/M;ca=is/M,Pa=Math.min(Pa,ca),si=jt.layout.get("building-facade-unit-width").evaluate(je,{},_)/M,Wn=(ca-Pa)/xa,Fp.setFauxFacadeOptions(!0,!0,si);const td=jt.layout.get("building-facade-window").evaluate(je,{},_);zr=td[0],Sn=td[1],dl=Math.floor(65535*Math.min(1,Pa/mr)),xi=Math.floor(65535*Math.min(1,ca/mr)),ei=Math.floor(255*zr)<<8|Math.floor(255*Sn),Vi=Math.floor(65535*Math.min(1,si/mr)),Ro=Math.floor(65535*Math.min(1,Wn/mr))}const Fc=Array(_t.length),eo={x:1/0,y:1/0},ul={x:-1/0,y:-1/0},ac={x:0,y:0};let Fl=0;for(let xa=0;xa<_t.length;xa++){const td=_t[xa];if(td.length>0){const hl=[],jc=Array(td.length+1);jc[0]=0;for(let $p=0;$pmr||eo.y<0||ul.y>mr)&&this.featuresOnBorder.push({featureId:je.id,footprintIndex:this.footprints.length});{const xa=Iu(cb,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+xa.length),this.footprintsIndices.uint16.set(xa,_D),this.buildingIds.add(ot??je.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Wf.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Wf.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,zp.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,zp.y);const td={footprintVertexOffset:wD,footprintVertexLength:this.footprintsVertices.length-wD,footprintIndexOffset:_D,footprintIndexLength:this.footprintsIndices.length-_D,min:Wf,max:zp,hiddenFlags:0,indicesOffset:jm,indicesLength:mve,bloomIndicesOffset:Pu,bloomIndicesLength:Zd,groundEffectVertexOffset:Sw,groundEffectVertexLength:Cw,hasFauxFacade:tn,height:wE,promoteId:Be,feature:pt,parts:kl,buildingBloom:ed},hl=this.footprints.length;je.id!==void 0&&this.featureFootprintLookup.set(je.id,hl),re(ot,hl),this.footprints.push(td)}this.programConfigurations.populatePaintArrays(pa.layoutVertexArray.length,je,Ye,{},p.availableImages,_,p.brightness),this.groundEffect.addPaintPropertiesData(je,Ye,{},p.availableImages,_,p.brightness),p.featureIndex.insert(je,Rt,Ye,Ue,this.index,Wo)}W.forEach(({buildingId:je,footprintIndex:Be})=>{J.has(je)&&(this.footprints[Be].hiddenFlags|=4)});const we=new Set;this.buildingIds.forEach((je,Be,Ye)=>{J.has(je)||we.add(je)}),this.buildingIds=we,this.groundEffect.prepareBorderSegments()}update(u,p,_,C,M,L,O){this.programConfigurations.updatePaintArrays(u,p,M,_,C,L,O),this.groundEffect.update(u,p,M,_,C,L,O),this.evaluate(this.layers[0],u),this.colorBufferUploaded=!1}updateExpressions(u){this.programConfigurations.updateExpressions(u),this.groundEffect.programConfigurations.updateExpressions(u)}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(u){const p=_=>{_.layoutVertexBuffer=u.createVertexBuffer(_.layoutVertexArray,yPe.members),_.layoutNormalBuffer=u.createVertexBuffer(_.layoutNormalArray,Nvt.members),_.layoutCentroidBuffer=u.createVertexBuffer(_.layoutCentroidArray,kvt.members),_.layoutFloodLightDataBuffer=u.createVertexBuffer(_.layoutFloodLightDataArray,Avt.members),_.layoutFacadeDataArray&&_.layoutFacadeDataArray.length&&(_.layoutFacadeDataBuffer=u.createVertexBuffer(_.layoutFacadeDataArray,Cvt.members)),_.layoutFacadeVerticalRangeArray&&_.layoutFacadeVerticalRangeArray.length&&(_.layoutFacadeVerticalRangeBuffer=u.createVertexBuffer(_.layoutFacadeVerticalRangeArray,Tvt.members)),_.entranceBloom.layoutVertexArray.length&&(_.entranceBloom.layoutVertexBuffer=u.createVertexBuffer(_.entranceBloom.layoutVertexArray,yPe.members),_.entranceBloom.layoutAttenuationBuffer=u.createVertexBuffer(_.entranceBloom.layoutAttenuationArray,Evt.members)),this.uploadUpdatedColorBuffer(u),this.uploadUpdatedIndexBuffer(u)};this.uploaded||(p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){const u=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()))};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(u,p,_=!0){let C=!1;const M=_?p:0,L=0|(_?-1:~p);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const O of u){const U=this.footprints[O],W=U.hiddenFlags&L|M;U.hiddenFlags!==W&&(U.hiddenFlags=W,C=!0,this.groundEffect.updateHiddenByLandmarkRange(U.groundEffectVertexOffset,U.groundEffectVertexLength,U.hiddenFlags!==0))}return C&&(this.indexArrayForConflationUploaded=!1),C}uploadUpdatedIndexBuffer(u){if(this.groundEffect.uploadHiddenByLandmark(u),this.indexArrayForConflationUploaded)return;const p=C=>{C.indexArray.length!==0&&(C.indexArrayForConflation.resize(C.indexArray.length),C.indexArrayForConflation.uint16.set(C.indexArray.uint16),C.entranceBloom.indexArrayForConflation.resize(C.entranceBloom.indexArray.length),C.entranceBloom.indexArrayForConflation.uint16.set(C.entranceBloom.indexArray.uint16))};p(this.buildingWithoutFacade),p(this.buildingWithFacade);for(const C of this.footprints){const M=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,L=C.indicesOffset+C.indicesLength;if(C.hiddenFlags!==0){for(let U=C.indicesOffset;U{C.indexArray.length!==0&&(C.indexBuffer?C.indexBuffer.updateData(C.indexArrayForConflation):C.indexBuffer=u.createIndexBuffer(C.indexArrayForConflation,!0),C.entranceBloom.indexBuffer?C.entranceBloom.indexBuffer.updateData(C.entranceBloom.indexArrayForConflation):C.entranceBloom.indexBuffer=u.createIndexBuffer(C.entranceBloom.indexArrayForConflation,!0))};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(u){const p=_=>{_.layoutColorBuffer?_.layoutColorBuffer.updateData(_.layoutColorArray):_.layoutColorBuffer=u.createVertexBuffer(_.layoutColorArray,vPe.members,!0),_.layoutFacadePaintArray&&(_.layoutFacadePaintBuffer?_.layoutFacadePaintBuffer.updateData(_.layoutFacadePaintArray):_.layoutFacadePaintBuffer=u.createVertexBuffer(_.layoutFacadePaintArray,Svt.members,!0)),_.entranceBloom.layoutColorBuffer?_.entranceBloom.layoutColorBuffer.updateData(_.entranceBloom.layoutColorArray):_.entranceBloom.layoutColorBuffer=u.createVertexBuffer(_.entranceBloom.layoutColorArray,vPe.members,!0)};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(u,p){const _=u.paint.get("building-ambient-occlusion-intensity");for(const C of this.footprints){if(4&C.hiddenFlags)continue;const M=p[C.promoteId],L=C.feature;L.properties["building-part"]="roof";const O=u.paint.get("building-color").evaluate(L,M,this.canonical).toPremultipliedRenderColor(this.lut),U=u.paint.get("building-emissive-strength").evaluate(L,M,this.canonical);L.properties["building-part"]="wall";const W=u.paint.get("building-color").evaluate(L,M,this.canonical).toPremultipliedRenderColor(this.lut),J=u.paint.get("building-emissive-strength").evaluate(L,M,this.canonical);L.properties["building-part"]="window";const se=u.paint.get("building-color").evaluate(L,M,this.canonical).toPremultipliedRenderColor(this.lut),re=u.paint.get("building-emissive-strength").evaluate(L,M,this.canonical);L.properties["building-part"]="door";const fe=u.paint.get("building-color").evaluate(L,M,this.canonical).toPremultipliedRenderColor(this.lut),xe=u.paint.get("building-emissive-strength").evaluate(L,M,this.canonical),we=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const Be of C.parts){let Ye,Ue=O;Be.part===1?(Ue=O,Ye=U):Be.part===0?(Ue=W,Ye=J):Be.part===2?(Ue=se,Ye=re):Be.part===3&&(Ue=fe,Ye=xe),Ye=Mt(Ye,0,1);for(let tt=0;ttL.max.x||U.max.xL.max.y||U.max.yO.max.x||O.min.x>u||p>O.max.y||O.min.y>p||O.height<=_||Lvt(L,this.footprintsVertices.float32.subarray(2*O.footprintVertexOffset,2*(O.footprintVertexOffset+O.footprintVertexLength)),this.footprintsIndices.uint16.subarray(O.footprintIndexOffset,O.footprintIndexOffset+O.footprintIndexLength))&&(_=O.height,this.footprintLookup[M]=O,C=O.hiddenFlags!==0);if(_!==Number.NEGATIVE_INFINITY)return{height:_,hidden:C};this.footprintLookup[M]=void 0}}function Lvt(y,u,p){for(let _=0;_{},J={a:{a:U,f:function(se){const re=p.length,fe=Math.max(se>>>0,Math.ceil(1.2*re)),xe=Math.ceil((fe-re)/65536);try{return L.grow(xe),O(),!0}catch{return!1}},g:U,b:W,c:W,d:W,e:W}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(u,J):u.then(se=>se.arrayBuffer()).then(se=>WebAssembly.instantiate(se,J))).then(se=>{const re=se.instance.exports;return(0,re.g)(),L=re.f,O(),new Mvt({setStyle:re.h,setAOOptions:re.i,setMetricOptions:re.j,setStructuralOptions:re.k,setFacadeOptions:re.l,setFauxFacadeOptions:re.m,setFacadeClassifierOptions:re.n,addFeature:re.o,addFacade:re.p,generateMesh:re.q,getLastError:re.r,getOuterRingLength:re.s,getMeshCount:re.t,getPositionsPtr:re.u,getPositionsLength:re.v,getNormalsPtr:re.w,getNormalsLength:re.x,getAOPtr:re.y,getAOLength:re.z,getUVPtr:re.A,getUVLength:re.B,getFauxFacadePtr:re.C,getFauxFacadeLength:re.D,getIndicesPtr:re.E,getIndicesLength:re.F,getBuildingPart:re.G,getRingCount:re.H,getRingPtr:re.I,getRingLength:re.J,malloc:re.K,free:re.L,heapU8:p,heap16:_,heap32:C,heapF32:M})})}(y).then(u=>{hE=null,Fp=u}).catch(u=>{ra("Could not load building-gen"),hE=null,_Pe=u}),hE}()}Mr(wPe,"BuildingBucket",{omit:["layers"]}),Mr(T0e,"BuildingGeometry"),Mr(C0e,"BuildingBloomGeometry");const Rvt=fa([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"},{name:"a_linesofar",components:1,type:"Float32"}],4),Ovt=fa([{name:"a_z_offset_width",components:3,type:"Float32"}],4),Fvt=fa([{name:"a_elevation_id_col",components:3,type:"Float32"}],4),Bvt=fa([{name:"a_elevation_ground_scale",components:1,type:"Float32"}],4),{members:zvt}=Rvt,$vt=fa([{name:"a_packed",components:3,type:"Float32"}]),{members:Uvt}=$vt,qvt=fa([{name:"a_pattern_data",components:3,type:"Float32"}]),{members:Vvt}=qvt;class NPe{constructor(u,p){this.width=u,this.height=p,this.nextRow=0,this.image=new pu({width:u,height:p}),this.positions={},this.uploaded=!1}getDash(u,p){const _=this.getKey(u,p);return this.positions[_]}trim(){const u=this.width,p=this.height=Yn(this.nextRow);this.image.resize({width:u,height:p})}getKey(u,p){return u.join(",")+p}getDashRanges(u,p,_){const C=[];let M=u.length%2==1?-u.at(-1)*_:0,L=u[0]*_,O=!0;C.push({left:M,right:L,isDash:O,zeroLength:u[0]===0});let U=u[0];for(let W=1;W1&&(U=u[++O]);const J=Math.abs(W-U.left),se=Math.abs(W-U.right),re=Math.min(J,se);let fe;const xe=M/_*(C+1);if(U.isDash){const we=C-Math.abs(xe);fe=Math.sqrt(re*re+we*we)}else fe=C-Math.sqrt(re*re+xe*xe);this.image.data[L+W]=Math.max(0,Math.min(255,fe+128))}}}addRegularDash(u,p){for(let U=u.length-1;U>=0;--U){const W=u[U],J=u[U+1];W.zeroLength?u.splice(U,1):J&&J.isDash===W.isDash&&(J.left=W.left,u.splice(U,1))}const _=u[0],C=u.at(-1);_.isDash===C.isDash&&(_.left=C.left-this.width,C.right=_.right+this.width);const M=this.width*this.nextRow;let L=0,O=u[L];for(let U=0;U1&&(O=u[++L]);const W=Math.abs(U-O.left),J=Math.abs(U-O.right),se=Math.min(W,J);this.image.data[M+U]=Math.max(0,Math.min(255,(O.isDash?se:-se)+p+128))}}addDash(u,p){const _=this.getKey(u,p);if(this.positions[_])return this.positions[_];const C=p==="round",M=C?7:0,L=2*M+1;if(this.nextRow+L>this.height)return ra("LineAtlas out of space"),null;u.length===0&&u.push(1);let O=0;for(let se=0;sep.fqid),this.index=u.index,this.projection=u.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(p=>{this.gradients[p.id]={}}),this.layoutVertexArray=new p6,this.layoutVertexArray2=new Zm,this.patternVertexArray=new Zm,this.indexArray=new Go,this.programConfigurations=new Xm(u.layers,{zoom:u.zoom,lut:u.lut}),this.segments=new Gi,this.maxLineLength=0,this.zOffsetVertexArray=new Zm,this.elevationIdColVertexArray=new Zm,this.elevationGroundScaleVertexArray=new Wd,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.tessellationStep=u.tessellationStep?u.tessellationStep:128,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,p){}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){this.showElevationIdDebug=p.showElevationIdDebug,this.hasPattern=Zye("line",this.layers,this.pixelRatio,p);const M=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Jm(_);const L=this.layers[0].layout.get("line-elevation-reference");if(L==="hd-road-markup")this.elevationType="road";else{const re=this.layers[0].layout.get("line-z-offset"),fe=re.isConstant()&&!re.constantOr(0);this.elevationType=L!=="sea"&&L!=="ground"&&fe?"none":"offset",this.elevationType==="offset"&&L==="none"&&ra(`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 O=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&O!==void 0;const U=[];for(const{feature:re,id:fe,index:xe,sourceLayerIndex:we}of u){const je=this.layers[0]._featureFilter.needGeometry,Be=Hf(re,je);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),Be,_))continue;const Ye=M?M.evaluate(Be,{},_):void 0,Ue={id:fe,properties:re.properties,type:re.type,sourceLayerIndex:we,index:xe,geometry:je?Be.geometry:bm(re,_,C),patterns:{},sortKey:Ye};U.push(Ue)}M&&U.sort((re,fe)=>re.sortKey-fe.sortKey);const{lineAtlas:W,featureIndex:J}=p,se=this.addConstantDashes(W);for(const re of U){const{geometry:fe,index:xe,sourceLayerIndex:we}=re;if(se&&this.addFeatureDashes(re,W),this.hasPattern){const je=Xye("line",this.layers,re,this.zoom,this.pixelRatio,p);this.patternFeatures.push(je)}else this.addFeature(re,fe,xe,_,W.positions,p.availableImages,p.brightness,p.elevationFeatures);J.insert(u[xe].feature,fe,xe,we,this.index)}}addConstantDashes(u){let p=!1;for(const _ of this.layers){const C=_.paint.get("line-dasharray").value,M=_.layout.get("line-cap").value;if(C.kind!=="constant"||M.kind!=="constant")p=!0;else{const L=M.value,O=C.value;if(!O)continue;u.addDash(O,L)}}return p}addFeatureDashes(u,p){const _=this.zoom;for(const C of this.layers){const M=C.paint.get("line-dasharray").value,L=C.layout.get("line-cap").value;if(M.kind==="constant"&&L.kind==="constant")continue;let O,U;if(M.kind==="constant"){if(O=M.value,!O)continue}else O=M.evaluate({zoom:_},u);U=L.kind==="constant"?L.value:L.evaluate({zoom:_},u),p.addDash(O,U),u.patterns[C.id]=[p.getKey(O,U)]}}update(u,p,_,C,M,L,O,U,W){this.programConfigurations.updatePaintArrays(u,p,M,_,C,L,O,W)}updateExpressions(u){this.programConfigurations.updateExpressions(u)}addFeatures(u,p,_,C,M,L){for(const O of this.patternFeatures)this.addFeature(O,O.geometry,O.index,p,_,C,L,u.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=u.createVertexBuffer(this.layoutVertexArray2,Uvt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=u.createVertexBuffer(this.patternVertexArray,Vvt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,Ovt.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=u.createVertexBuffer(this.elevationIdColVertexArray,Fvt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=u.createVertexBuffer(this.elevationGroundScaleVertexArray,Bvt.members,!0)),this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,zvt),this.indexBuffer=u.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationIdColVertexBuffer&&this.elevationIdColVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(u,p){let _,C;if(p&&p>0?(_=`mapbox_clip_start_${p}`,C=`mapbox_clip_end_${p}`):(_="mapbox_clip_start",C="mapbox_clip_end"),u.properties&&Object.hasOwn(u.properties,_)&&Object.hasOwn(u.properties,C))return{start:+u.properties[_],end:+u.properties[C]}}addFeature(u,p,_,C,M,L,O,U){const W=this.layers[0].layout,J=W.get("line-join").evaluate(u,{}),se=W.get("line-cap").evaluate(u,{}),re=W.get("line-miter-limit"),fe=W.get("line-round-limit");this.lineClips=this.lineFeatureClips(u),this.lineFeature=u;const xe=!(!u.properties||!Object.hasOwn(u.properties,"mapbox_line_metrics"))&&u.properties.mapbox_line_metrics;this.zOffsetValue=W.get("line-z-offset").value;const we=this.layers[0].paint.get("line-width").value;if(we.kind!=="constant"&&we.isLineProgressConstant===!1&&(this.variableWidthValue=we),this.isSeaLevelReference){const je=W.get("line-elevation-ground-scale").value;je.kind==="constant"&&je.value===0||(this.elevationGroundScaleValue=je)}if(this.elevationType==="road"){const je=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(u,p,C,U,J,se,re,fe)){const[Be,Ye]=this.clipRuntimeLinesToTile(p,1);for(let Ue=0;Ue0?ot.parentIndex:null)}this.fillNonElevatedRoadSegment(je)}}else for(let je=0;je0?je:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,_,M,L,C,O,void 0,this.worldview)}computeSegNextDir(u,p){return u.nextPoint.sub(p.at(-2)).unit()}computeSegPrevDir(u,p){return p[1].sub(u.prevPoint).unit()}clipLinesToTile(u,p){return L9(u,-p,-p,mr+p,mr+p)}clipRuntimeLinesToTile(u,p){const _=[];return[L9(u,-p,-p,mr+p,mr+p,_),_]}addElevatedRoadFeature(u,p,_,C,M,L,O,U){const W=[],J=E.getElevationFeature(u,C);if(J){const se=this.clipLinesToTile(p,1),re=this.prepareElevatedLines(se,J,_);for(const fe of re)W.push({geometry:fe,elevation:J,elevationTileID:_,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(W.length===0)return!1;for(const se of W){const re=this.layoutVertexArray.length;this.addLine(se.geometry,u,_,M,L,O,U);const fe=new f(_,se.elevationTileID);if(se.elevation){const xe=this.showElevationIdDebug?w(se.elevation.id):null;for(let we=re;we>1,this.layoutVertexArray.int16[6*we+1]>>1),Be=fe.pointElevation(je,se.elevation,.05);this.updateHeightRange(Be),this.zOffsetVertexArray.emplaceBack(Be,0,0),xe?this.elevationIdColVertexArray.emplaceBack(xe[0],xe[1],xe[2]):this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)}}else this.fillNonElevatedRoadSegment(re)}return!0}prepareElevatedLines(u,p,_){if(p.constantHeight!=null)return u;const C=[],M=1/Jm(_);for(const L of u)svt(L,new B6(p,M),0,C);return C}fillNonElevatedRoadSegment(u){for(let p=u;p0,re=U&&U.progress.max<1;if(this.lineClips){let Et={min:this.lineClips.start,max:this.lineClips.end},jt=1;if(U){const is=this.lineClips.end-this.lineClips.start;Et=function(xs,ks,ws){return{min:ll(xs.min,ks,ws),max:ll(xs.max,ks,ws)}}(U.progress,{min:0,max:1},Et),is>0&&(jt=(Et.max-Et.min)/is)}const At=+p.properties.mapbox_clip_feature_len,ns=+p.properties.mapbox_clip_seg_len;if(Number.isNaN(At)||Number.isNaN(ns)){for(let xs=0;xs=2&&u[xe-1].equals(u[xe-2]);)xe--;let we=0;for(;we0,gs=this.overscaling<=16?122880/(512*this.overscaling):0;if(jt&&At==="round"){if(ksL&&(At="bevel"),At==="bevel"&&(ks>2&&(At="flipbevel"),ks2*gs){const Hs=Be.sub(Be.sub(Ye)._mult(gs/Cs)._round());this.updateDistance(Ye,Hs),this.addCurrentVertex(Hs,tt,0,0,je,_t),Ye=Hs}this.updateDistance(Ye,Be),is._mult(ks),this.addCurrentVertex(Be,is,0,0,je,_t);const Bs=Be.dist(Ue);if(Bs>2*gs){const Hs=Be.add(Ue.sub(Be)._mult(gs/Bs)._round());this.updateDistance(Be,Hs),this.addCurrentVertex(Hs,ot,0,0,je,_t),Be=Hs}}else is._mult(ks),this.addCurrentVertex(Be,is,0,0,je,_t);else if(At==="flipbevel"){if(ks>100)is=ot.mult(-1);else{const Cs=ks*tt.add(ot).mag()/tt.sub(ot).mag();is._perp()._mult(Cs*(ds?-1:1))}this.addCurrentVertex(Be,is,0,0,je,_t),this.addCurrentVertex(Be,is.mult(-1),0,0,je,_t)}else if(At==="bevel"||At==="fakeround"){const Cs=Be.dist(Ye);let Bs=1;if(this.elevationType==="offset"&&At==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&_t!=null&&Ye&&Ue){const wr=4*gs;Cs1){this.lineSoFar=u.w;const we=(p.x-u.x)/se,je=(p.y-u.y)/se,Be=(p.z-u.z)/se,Ye=(p.w-u.w)/se,Ue=p.x-u.x,tt=p.y-u.y,ot=Math.sqrt(Ue*Ue+tt*tt);if(ot===0)return;const pt=-tt/ot,Rt=Ue/ot,_t=pt,Et=Rt,jt=-pt,At=-Rt;for(let ns=1;ns=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,J),U.primitiveLength++),L?this.e2=J:this.e1=J,W!=null&&(this.zOffsetVertexArray.emplaceBack(W.zOffset,W.variableWidth,W.variableWidth),this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)),this.elevationGroundScaleValue){const se=W?W.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(se)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(u,p){this.prevDistance=this.distance,this.distance+=u.dist(p),this.updateScaledDistance()}}function E0e(y,u,p){return y.xp||y.yp}let kPe,SPe;function CPe(y,u,p){return u*(mr/(y.tileSize*Math.pow(2,p-y.tileID.overscaledZ)))}Mr(H9,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const TPe=(y,u,p)=>(1-p)*y+p*u;function EPe(y,u){return 1/CPe(y,1,u.tileZoom)}function APe(y,u,p,_){return y.translatePosMatrix(_||u.tileID.projMatrix,u,p.paint.get("line-translate"),p.paint.get("line-translate-anchor"))}const MPe=y=>{const u=[];IPe(y)&&u.push("RENDER_LINE_DASH"),y.paint.get("line-gradient")&&u.push("RENDER_LINE_GRADIENT"),y.paint.get("line-blend-mode")==="multiply"&&u.push("LINE_BLEND_MULTIPLY"),y.paint.get("line-blend-mode")==="additive"&&u.push("LINE_BLEND_ADDITIVE");const p=y.paint.get("line-trim-offset");p[0]===0&&p[1]===0||u.push("RENDER_LINE_TRIM_OFFSET"),y.paint.get("line-border-width").constantOr(1)!==0&&u.push("RENDER_LINE_BORDER");const _=y.layout.get("line-join").constantOr("miter")==="none",C=!!y.paint.get("line-pattern").constantOr(1);return _&&C&&u.push("LINE_JOIN_NONE"),u};function IPe(y){const u=y.paint.get("line-dasharray").value;return u.kind!=="constant"||u.value}let A0e;const PPe=()=>A0e||(A0e={layout:kPe||(kPe=new ko({"line-cap":new lr(Yt.layout_line["line-cap"]),"line-join":new lr(Yt.layout_line["line-join"]),"line-miter-limit":new rr(Yt.layout_line["line-miter-limit"]),"line-round-limit":new rr(Yt.layout_line["line-round-limit"]),"line-sort-key":new lr(Yt.layout_line["line-sort-key"]),"line-z-offset":new lr(Yt.layout_line["line-z-offset"]),"line-elevation-reference":new rr(Yt.layout_line["line-elevation-reference"]),"line-cross-slope":new rr(Yt.layout_line["line-cross-slope"]),visibility:new rr(Yt.layout_line.visibility),"line-width-unit":new rr(Yt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new lr(Yt.layout_line["line-elevation-ground-scale"])})),paint:SPe||(SPe=new ko({"line-opacity":new lr(Yt.paint_line["line-opacity"]),"line-color":new lr(Yt.paint_line["line-color"]),"line-translate":new rr(Yt.paint_line["line-translate"]),"line-translate-anchor":new rr(Yt.paint_line["line-translate-anchor"]),"line-width":new lr(Yt.paint_line["line-width"]),"line-gap-width":new lr(Yt.paint_line["line-gap-width"]),"line-offset":new lr(Yt.paint_line["line-offset"]),"line-blur":new lr(Yt.paint_line["line-blur"]),"line-dasharray":new lr(Yt.paint_line["line-dasharray"]),"line-pattern":new lr(Yt.paint_line["line-pattern"]),"line-pattern-cross-fade":new rr(Yt.paint_line["line-pattern-cross-fade"]),"line-gradient":new F0(Yt.paint_line["line-gradient"]),"line-trim-offset":new rr(Yt.paint_line["line-trim-offset"]),"line-trim-fade-range":new rr(Yt.paint_line["line-trim-fade-range"]),"line-trim-color":new rr(Yt.paint_line["line-trim-color"]),"line-emissive-strength":new lr(Yt.paint_line["line-emissive-strength"]),"line-border-width":new lr(Yt.paint_line["line-border-width"]),"line-border-color":new lr(Yt.paint_line["line-border-color"]),"line-occlusion-opacity":new rr(Yt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new rr(Yt.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new rr(Yt.paint_line["line-blend-additive-clamp"]),"line-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},A0e);class Kvt extends lr{possiblyEvaluate(u,p){return p=new fi(Math.floor(p.zoom),{now:p.now,fadeDuration:p.fadeDuration,transition:p.transition,worldview:p.worldview}),super.possiblyEvaluate(u,p)}evaluate(u,p,_,C){return p=Object.assign({},p,{zoom:Math.floor(p.zoom)}),super.evaluate(u,p,_,C)}}let sD;function LPe(y,u){return u>0?u+2*y:y}const Yvt=fa([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zvt=fa([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),Xvt=fa([{name:"a_projected_pos",components:4,type:"Float32"}],4);fa([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Qvt=fa([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),Jvt=fa([{name:"a_feature_index",components:1,type:"Float32"}],4),e1t=fa([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),t1t=fa([{name:"a_texb",components:2,type:"Uint16"}]),s1t=fa([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),r1t=fa([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);fa([{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 DPe=fa([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),n1t=fa([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);fa([{name:"triangle",components:3,type:"Uint16"}]),fa([{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"}]),fa([{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"}]),fa([{type:"Float32",name:"offsetX"}]),fa([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const XN=class Hw{constructor(u=null,p=0,_=4096){if(this.batchIndex=p,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=u||null,this.propsDwords=_,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(Hw.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),!Hw._blockIndicesTemplate){Hw._blockIndicesTemplate=new Uint32Array(this.propsDwords);for(let C=0;Cu.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${u.maxUniformBlockSize}`);if(this.headerBuffer=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,Hw.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(u){const p=this.headerData;p[0]=u.dataDrivenMask,p[1]=u.zoomDependentMask,p[2]=u.dataDrivenBlockSizeVec4,p[3]=u.offsets[0],p[4]=u.offsets[1],p[5]=u.offsets[2],p[6]=u.offsets[3],p[7]=u.offsets[4],p[8]=u.offsets[5],p[9]=u.offsets[6],p[10]=u.offsets[7],p[11]=u.offsets[8]}writeDataDrivenBlock(u,p,_){const C=4*_.dataDrivenBlockSizeVec4;if(C===0)return;const M=p*C;if(M+C>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${p} exceeds propertiesData capacity`);for(let L=0;L<9;L++)_.dataDrivenMask&1<{if(!O)return;const W=_.getUniformBlockIndex(p,L);W!==_.INVALID_INDEX&&(_.uniformBlockBinding(p,W,U),_.bindBufferBase(_.UNIFORM_BUFFER,U,O))},M=3*this.batchIndex;C("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,M),C("SymbolPaintPropertiesUniform",this.propertiesBuffer,M+1),C("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,M+2)}destroy(){if(this.context){const u=this.context.gl;this.headerBuffer&&(u.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(u.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(u.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};XN.HEADER_DWORDS=12,XN.HEADER_BYTES=48,XN.EVAL_FLAT_OFFSETS=[0,4,8,10,12,14,16,18,20],XN.EVAL_FLAT_SIZES=[4,4,2,2,2,2,2,2,4],XN.EVAL_FLAT_TOTAL=24,XN._blockIndicesTemplate=null;let bw=XN;function RPe(y,u,p,_,C,M,L,O){return!!y&&(y.kind==="constant"?y.value==="none":y.kind==="composite"||y.kind==="source"?y.evaluate({zoom:0,brightness:M,worldview:O},u,p,C,_,L)==="none":typeof y=="string"&&y==="none")}Mr(bw,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class M0e{constructor(u,p,_,C,M="",L,O){this.layer=u,this.zoom=p,this.lut=_,this.isText=C,this.propDefs=this._getPropDefs(),this.worldview=M,this.maxUniformBufferBindings=L||24,this.uboSizeDwords=O||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(u,C),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map,this.isLightConstant=!0,this._evalFlat=new Float32Array(bw.EVAL_FLAT_TOTAL)}_getPropDefs(){const u=this.isText?"text":"icon";return[{name:`${u}-color`,useThemeName:`${u}-color-use-theme`,isColor:!0},{name:`${u}-halo-color`,useThemeName:`${u}-halo-color-use-theme`,isColor:!0},{name:`${u}-opacity`,useThemeName:null,isColor:!1},{name:`${u}-halo-width`,useThemeName:null,isColor:!1},{name:`${u}-halo-blur`,useThemeName:null,isColor:!1},{name:`${u}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${u}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${u}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const u=this.layer.paint,p=this.propDefs;let _=0,C=0,M=0,L=0,O=!0;const U=[0,0,0,0,0,0,0,0,0];for(let J=0;J<9;J++){const{name:se,isColor:re,isVec2:fe}=p[J],xe=u.get(se),we=!(!xe||typeof xe.isConstant!="function"||xe.isConstant()),je=this._appearancesHavePaintProperties(se),Be=we||je,Ye=!(!xe||!xe.value||xe.value.kind!=="composite"),Ue=this.layer._transitionablePaint._values[se],tt=!Be&&(Ue&&Ue.value&&Ue.value.expression&&Ue.value.expression.kind)==="camera";if(Be){_|=1<p.hasPaintProperty(u):this.isText?p=>p.hasTextPaintProperties():p=>p.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(u,p){const _=u.paint,C=p?"text":"icon",M=[`${C}-color`,`${C}-halo-color`,`${C}-opacity`,`${C}-halo-width`,`${C}-halo-blur`,`${C}-emissive-strength`,`${C}-occlusion-opacity`,"symbol-z-offset",`${C}-translate`];for(const L of M){const O=_.get(L);if(O&&typeof O=="object"&&"isConstant"in O&&!O.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(u,p){if(p.dataDrivenMask===0)return"";const _=[];for(let C=0;C=xe){ra(`Too many symbol features: batch ${re} requires binding points up to ${3*re+2}, device limit ${xe}. Some features will render incorrectly.`);const je={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:p,featureId:U};return this.allFeatures.push(je),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(je)),0}this.ubos[re]||(this.ubos[re]=new bw(O,re,this.uboSizeDwords),this.ubos[re].writeHeader(W)),this.ubos[re].writeDataDrivenBlock(J,fe,W);const we={batchIndex:re,localFeatureIndex:fe,vtFeatureIndex:p,featureId:U};return this.allFeatures.push(we),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(we)),fe}updateFeatures(u,p,_,C,M,L,O){if(this.layer=p,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const W of u){const J=this.featureVertexRangesFromId.get(W);if(!J)continue;const se=L[W]||{};for(const re of J){if(!_)continue;const fe=_.feature(re.vtFeatureIndex);if(!fe)continue;const xe={type:fe.type,id:W,properties:fe.properties||{},geometry:[]},we=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(re.vtFeatureIndex):void 0,je=this.evaluateAllProperties(xe,se,C,M,O,void 0,we);this.ubos[re.batchIndex]&&this.ubos[re.batchIndex].writeDataDrivenBlock(je,re.localFeatureIndex,U)}}}updateDynamicExpressions(u,p,_,C,M,L){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader||this.cachedHeader.dataDrivenMask===0)return;const O=this.cachedHeader;for(const U of this.allFeatures){if(!p)continue;const W=p.feature(U.vtFeatureIndex);if(!W)continue;const J=U.featureId!=null&&M[U.featureId]||{},se={type:W.type,id:U.featureId,properties:W.properties||{},geometry:[]},re=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(U.vtFeatureIndex):void 0,fe=this.evaluateAllProperties(se,J,_,C,L,void 0,re);this.ubos[U.batchIndex]&&this.ubos[U.batchIndex].writeDataDrivenBlock(fe,U.localFeatureIndex,O)}}updateFeaturePaintForAppearance(u,p,_,C,M,L,O){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(u,O||null),!this.cachedHeader))return!1;const U=this.cachedHeader;if(U.dataDrivenMask===0)return!1;let W=!1;for(const J of this.allFeatures){if(J.vtFeatureIndex!==u)continue;const se=this.evaluateAllProperties(p,_,C,M,L,void 0,O);this.ubos[J.batchIndex]&&(this.ubos[J.batchIndex].writeDataDrivenBlock(se,J.localFeatureIndex,U),W=!0)}return W}getConstantUniformValues(u,p){const _=this.cachedHeader,C=!(!_||!_.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===p&&(!C||this.cachedConstantRenderZoom===u))return this.cachedConstantUniforms;const M=this.layer.paint,L=this.propDefs,O=C?new fi(u,{brightness:p,worldview:this.worldview}):null,U={type:1,id:void 0,properties:{},geometry:[]},W=re=>{const fe=L[re],xe=M.get(fe.name);if(!xe)return[0,0,0,1];const we=fe.useThemeName?M.get(fe.useThemeName):void 0,je=RPe(we&&typeof we!="string"?we.value:void 0,U,{},[],void 0,p,void 0,this.worldview)?null:this.lut;let Be;Be=_&&_.cameraMask&1<{const xe=M.get(L[re].name);if(!xe)return fe;if(_&&_.cameraMask&1<{_.text=function(C,M,L){const O=M.layout.get("text-transform").evaluate(L,{});return O==="uppercase"?C=C.toLocaleUpperCase():O==="lowercase"&&(C=C.toLocaleLowerCase()),Pp.applyArabicShaping&&(C=Pp.applyArabicShaping(C)),C}(_.text,u,p)}),y}const rD={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function i1t(y){return y==="︶"||y==="﹈"||y==="︸"||y==="﹄"||y==="﹂"||y==="︾"||y==="︼"||y==="︺"||y==="︘"||y==="﹀"||y==="︐"||y==="︓"||y==="︔"||y==="`"||y===" ̄"||y==="︑"||y==="︒"}function o1t(y){return y==="︵"||y==="﹇"||y==="︷"||y==="﹃"||y==="﹁"||y==="︽"||y==="︻"||y==="︹"||y==="︗"||y==="︿"}const I0e=4294967296,OPe=1/I0e,FPe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let G9=class{constructor(y=new Uint8Array(16)){this.buf=ArrayBuffer.isView(y)?y:new Uint8Array(y),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(y,u,p=this.length){for(;this.pos>3,M=this.pos;this.type=7&_,y(C,u,this),this.pos===M&&this.skip(_)}return u}readMessage(y,u){return this.readFields(y,u,this.readVarint()+this.pos)}readFixed32(){const y=this.dataView.getUint32(this.pos,!0);return this.pos+=4,y}readSFixed32(){const y=this.dataView.getInt32(this.pos,!0);return this.pos+=4,y}readFixed64(){const y=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*I0e;return this.pos+=8,y}readSFixed64(){const y=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*I0e;return this.pos+=8,y}readFloat(){const y=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,y}readDouble(){const y=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,y}readVarint(y){const u=this.buf;let p,_;return _=u[this.pos++],p=127&_,_<128?p:(_=u[this.pos++],p|=(127&_)<<7,_<128?p:(_=u[this.pos++],p|=(127&_)<<14,_<128?p:(_=u[this.pos++],p|=(127&_)<<21,_<128?p:(_=u[this.pos],p|=(15&_)<<28,function(C,M,L){const O=L.buf;let U,W;if(W=O[L.pos++],U=(112&W)>>4,W<128||(W=O[L.pos++],U|=(127&W)<<3,W<128)||(W=O[L.pos++],U|=(127&W)<<10,W<128)||(W=O[L.pos++],U|=(127&W)<<17,W<128)||(W=O[L.pos++],U|=(127&W)<<24,W<128)||(W=O[L.pos++],U|=(1&W)<<31,W<128))return mE(C,U,M);throw new Error("Expected varint not more than 10 bytes")}(p,y,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const y=this.readVarint();return y%2==1?(y+1)/-2:y/2}readBoolean(){return!!this.readVarint()}readString(){const y=this.readVarint()+this.pos,u=this.pos;return this.pos=y,y-u>=12&&FPe?FPe.decode(this.buf.subarray(u,y)):function(p,_,C){let M="",L=_;for(;L239?4:O>223?3:O>191?2:1;if(L+re>C)break;re===1?O<128&&(se=O):re===2?(U=p[L+1],(192&U)==128&&(se=(31&O)<<6|63&U,se<=127&&(se=null))):re===3?(U=p[L+1],W=p[L+2],(192&U)==128&&(192&W)==128&&(se=(15&O)<<12|(63&U)<<6|63&W,(se<=2047||se>=55296&&se<=57343)&&(se=null))):re===4&&(U=p[L+1],W=p[L+2],J=p[L+3],(192&U)==128&&(192&W)==128&&(192&J)==128&&(se=(15&O)<<18|(63&U)<<12|(63&W)<<6|63&J,(se<=65535||se>=1114112)&&(se=null))),se===null?(se=65533,re=1):se>65535&&(se-=65536,M+=String.fromCharCode(se>>>10&1023|55296),se=56320|1023&se),M+=String.fromCharCode(se),L+=re}return M}(this.buf,u,y)}readBytes(){const y=this.readVarint()+this.pos,u=this.buf.subarray(this.pos,y);return this.pos=y,u}readPackedVarint(y=[],u){const p=this.readPackedEnd();for(;this.pos127;);else if(u===2)this.pos=this.readVarint()+this.pos;else if(u===5)this.pos+=4;else{if(u!==1)throw new Error(`Unimplemented type: ${u}`);this.pos+=8}}writeTag(y,u){this.writeVarint(y<<3|u)}realloc(y){let u=this.length||16;for(;u268435455||y<0?function(u,p){let _,C;if(u>=0?(_=u%4294967296|0,C=u/4294967296|0):(_=~(-u%4294967296),C=~(-u/4294967296),4294967295^_?_=_+1|0:(_=0,C=C+1|0)),u>=18446744073709552e3||u<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");p.realloc(10),function(M,L,O){O.buf[O.pos++]=127&M|128,M>>>=7,O.buf[O.pos++]=127&M|128,M>>>=7,O.buf[O.pos++]=127&M|128,M>>>=7,O.buf[O.pos++]=127&M|128,O.buf[O.pos]=127&(M>>>=7)}(_,0,p),function(M,L){const O=(7&M)<<4;L.buf[L.pos++]|=O|((M>>>=3)?128:0),M&&(L.buf[L.pos++]=127&M|((M>>>=7)?128:0),M&&(L.buf[L.pos++]=127&M|((M>>>=7)?128:0),M&&(L.buf[L.pos++]=127&M|((M>>>=7)?128:0),M&&(L.buf[L.pos++]=127&M|((M>>>=7)?128:0),M&&(L.buf[L.pos++]=127&M)))))}(C,p)}(y,this):(this.realloc(4),this.buf[this.pos++]=127&y|(y>127?128:0),y<=127||(this.buf[this.pos++]=127&(y>>>=7)|(y>127?128:0),y<=127||(this.buf[this.pos++]=127&(y>>>=7)|(y>127?128:0),y<=127||(this.buf[this.pos++]=y>>>7&127))))}writeSVarint(y){this.writeVarint(y<0?2*-y-1:2*y)}writeBoolean(y){this.writeVarint(+y)}writeString(y){y=String(y),this.realloc(4*y.length),this.pos++;const u=this.pos;this.pos=function(_,C,M){for(let L,O,U=0;U55295&&L<57344){if(!O){L>56319||U+1===C.length?(_[M++]=239,_[M++]=191,_[M++]=189):O=L;continue}if(L<56320){_[M++]=239,_[M++]=191,_[M++]=189,O=L;continue}L=O-55296<<10|L-56320|65536,O=null}else O&&(_[M++]=239,_[M++]=191,_[M++]=189,O=null);L<128?_[M++]=L:(L<2048?_[M++]=L>>6|192:(L<65536?_[M++]=L>>12|224:(_[M++]=L>>18|240,_[M++]=L>>12&63|128),_[M++]=L>>6&63|128),_[M++]=63&L|128)}return M}(this.buf,y,this.pos);const p=this.pos-u;p>=128&&BPe(u,p,this),this.pos=u-1,this.writeVarint(p),this.pos+=p}writeFloat(y){this.realloc(4),this.dataView.setFloat32(this.pos,y,!0),this.pos+=4}writeDouble(y){this.realloc(8),this.dataView.setFloat64(this.pos,y,!0),this.pos+=8}writeBytes(y){const u=y.length;this.writeVarint(u),this.realloc(u);for(let p=0;p=128&&BPe(p,_,this),this.pos=p-1,this.writeVarint(_),this.pos+=_}writeMessage(y,u,p){this.writeTag(y,2),this.writeRawMessage(u,p)}writePackedVarint(y,u){u.length&&this.writeMessage(y,l1t,u)}writePackedSVarint(y,u){u.length&&this.writeMessage(y,c1t,u)}writePackedBoolean(y,u){u.length&&this.writeMessage(y,h1t,u)}writePackedFloat(y,u){u.length&&this.writeMessage(y,d1t,u)}writePackedDouble(y,u){u.length&&this.writeMessage(y,u1t,u)}writePackedFixed32(y,u){u.length&&this.writeMessage(y,m1t,u)}writePackedSFixed32(y,u){u.length&&this.writeMessage(y,f1t,u)}writePackedFixed64(y,u){u.length&&this.writeMessage(y,p1t,u)}writePackedSFixed64(y,u){u.length&&this.writeMessage(y,x1t,u)}writeBytesField(y,u){this.writeTag(y,2),this.writeBytes(u)}writeFixed32Field(y,u){this.writeTag(y,5),this.writeFixed32(u)}writeSFixed32Field(y,u){this.writeTag(y,5),this.writeSFixed32(u)}writeFixed64Field(y,u){this.writeTag(y,1),this.writeFixed64(u)}writeSFixed64Field(y,u){this.writeTag(y,1),this.writeSFixed64(u)}writeVarintField(y,u){this.writeTag(y,0),this.writeVarint(u)}writeSVarintField(y,u){this.writeTag(y,0),this.writeSVarint(u)}writeStringField(y,u){this.writeTag(y,2),this.writeString(u)}writeFloatField(y,u){this.writeTag(y,5),this.writeFloat(u)}writeDoubleField(y,u){this.writeTag(y,1),this.writeDouble(u)}writeBooleanField(y,u){this.writeVarintField(y,+u)}};function mE(y,u,p){return p?4294967296*u+(y>>>0):4294967296*(u>>>0)+(y>>>0)}function BPe(y,u,p){const _=u<=16383?1:u<=2097151?2:u<=268435455?3:Math.floor(Math.log(u)/(7*Math.LN2));p.realloc(_);for(let C=p.pos-1;C>=y;C--)p.buf[C+_]=p.buf[C]}function l1t(y,u){for(let p=0;p=0&&_>=u&&W9[this.text.charCodeAt(_)];_--)p--;this.text=this.text.substring(u,p),this.sectionIndex=this.sectionIndex.slice(u,p)}substring(u,p){const _=new fE;return _.text=this.text.substring(u,p),_.sectionIndex=this.sectionIndex.slice(u,p),_.sections=this.sections,_}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((u,p)=>Math.max(u,this.sections[p].scale),0)}addTextSection(u,p){this.text+=u.text,this.sections.push(nD.forText(u.scale,u.fontStack||p));const _=this.sections.length-1;for(let C=0;C=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function P0e(y,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we=1,je=1){const Be=fE.fromFeature(y,C,we,je);se===rf.vertical&&Be.verticalizePunctuation(re);let Ye=[];const Ue=function(_t,Et,jt,At,ns,is,xs=1){if(!_t)return[];const ks=[],ws=function(gs,Cs,Bs,Hs,cr,Ds,tr=1){let sr=0;for(let wr=0;wr0&&wc>ca&&(ca=wc)}else{const ed=jt[Ro.fontStack];if(!ed)continue;ed[eo]&&(Fl=ed[eo]);const Pu=Et[Ro.fontStack];if(!Pu)continue;const Zd=Pu.glyphs[eo];if(!Zd)continue;if(ac=Zd.metrics,pa=eo!==8203?Oc:0,tr){const Wo=Pu.ascender!==void 0?Math.abs(Pu.ascender):0,wc=Pu.descender!==void 0?Math.abs(Pu.descender):0,jm=(Wo+wc)*ul;dl-p/2;){if(L--,L<0)return!1;O-=y[L].dist(M),M=y[L]}O+=y[L].dist(y[L+1]),L++;const U=[];let W=0;for(;O

_;)W-=U.shift().angleDelta;if(W>C)return!1;L++,O+=J.dist(se)}return!0}function YPe(y){let u=0;for(let p=0;pW){const xe=(W-U)/fe,we=Jr(se.x,re.x,xe),je=Jr(se.y,re.y,xe),Be=new lb(we,je,0,re.angleTo(se),J);return!L||KPe(y,Be,O,L,u)?Be:void 0}U+=fe}}function j1t(y,u,p,_,C,M,L,O,U){const W=ZPe(_,M,L),J=XPe(_,C),se=J*L,re=y[0].x===0||y[0].x===U||y[0].y===0||y[0].y===U;return u-se=0&&tt=0&&ot=0&&re+W<=J){const pt=new lb(tt,ot,0,Ye,xe);_&&!KPe(y,pt,M,_,C)||fe.push(pt)}}se+=Be}return O||fe.length||L||(fe=QPe(y,se/2,p,_,C,M,L,!0,U)),fe}function JPe(y){let u=0,p=0;for(const L of y)u+=L.w*L.h,p=Math.max(p,L.w);y.sort((L,O)=>O.h-L.h);const _=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(u/.95)),p),h:1/0}];let C=0,M=0;for(const L of y)for(let O=_.length-1;O>=0;O--){const U=_[O];if(!(L.w>U.w||L.h>U.h)){if(L.x=U.x,L.y=U.y,M=Math.max(M,L.y+L.h),C=Math.max(C,L.x+L.w),L.w===U.w&&L.h===U.h){const W=_.pop();W&&O<_.length&&(_[O]=W)}else L.h===U.h?(U.x+=L.w,U.w-=L.w):L.w===U.w?(U.y+=L.h,U.h-=L.h):(_.push({x:U.x+L.w,y:U.y,w:U.w-L.w,h:L.h}),U.y+=L.h,U.h-=L.h);break}}return{w:C,h:M,fill:u/(C*M)||0}}function Y9(y,u){return y.idu.id?1:y.versionu.version?1:y.sxu.sx?1:y.syu.sy?1:0}function F0e(y){let u=0;for(let p=0;p0,eLe(u,_,this.iconDescriptors,M),eLe(p,_,this.patternDescriptors,M),this.iconDescriptors.sort(Y9),this.patternDescriptors.sort(Y9);let L=0;const O=C?C.data:"";O&&(L=jy(L,F0e(O))),L=jy(L,1);for(const U of this.iconDescriptors)L=jy(L,F0e(U.id)),L=jy(L,U.version),L=jy(L,U.sx),L=jy(L,U.sy);L=jy(L,1);for(const U of this.patternDescriptors)L=jy(L,F0e(U.id)),L=jy(L,U.version),L=jy(L,U.sx),L=jy(L,U.sy);this.hash=L}subsetOf(u){return this.isSubsetArray(this.iconDescriptors,u.iconDescriptors,Y9)&&this.isSubsetArray(this.patternDescriptors,u.patternDescriptors,Y9)}isSubsetArray(u,p,_){let C=0,M=0;if(u.length>p.length)return!1;for(;C{const L=C.variant.id.toString().localeCompare(M.variant.id.toString());return L!==0?L:C.variant.sx!==M.variant.sx?C.variant.sx-M.variant.sx:C.variant.sy!==M.variant.sy?C.variant.sy-M.variant.sy:0});const _=new Map;for(const C of p)_.set(C.key,C.value);return _}class tLe{constructor(u){this.sourceAtlasHash=u}}class sLe{constructor(u,p,_,C){const M=new Map,L=new Map;this.haveRenderCallbacks=[];const O=[],U=C!==void 0,W=U?new Map:void 0,J=U?$0e(u,W):u,se=U?$0e(p,W):p;this.addImages(J,M,1,O),this.addImages(se,L,2,O);const{w:re,h:fe}=JPe(O),xe=new ii({width:re||1,height:fe||1});for(const[we,je]of J.entries()){const Be=M.get(we).paddedRect;ii.copy(je.data,xe,{x:0,y:0},{x:Be.x+1,y:Be.y+1},je.data,null,je.sdf)}for(const[we,je]of se.entries()){const Be=L.get(we),Ye=Be.paddedRect;let Ue=Be.padding;const tt=Ye.x+Ue,ot=Ye.y+Ue,pt=je.data.width,Rt=je.data.height;Ue=Ue>1?Ue-1:Ue,ii.copy(je.data,xe,{x:0,y:0},{x:tt,y:ot},je.data,_),ii.copy(je.data,xe,{x:0,y:Rt-Ue},{x:tt,y:ot-Ue},{width:pt,height:Ue},_),ii.copy(je.data,xe,{x:0,y:0},{x:tt,y:ot+Rt},{width:pt,height:Ue},_),ii.copy(je.data,xe,{x:pt-Ue,y:0},{x:tt-Ue,y:ot},{width:Ue,height:Rt},_),ii.copy(je.data,xe,{x:0,y:0},{x:tt+pt,y:ot},{width:Ue,height:Rt},_),ii.copy(je.data,xe,{x:pt-Ue,y:Rt-Ue},{x:tt-Ue,y:ot-Ue},{width:Ue,height:Ue},_),ii.copy(je.data,xe,{x:0,y:Rt-Ue},{x:tt+pt,y:ot-Ue},{width:Ue,height:Ue},_),ii.copy(je.data,xe,{x:0,y:0},{x:tt+pt,y:ot+Rt},{width:Ue,height:Ue},_),ii.copy(je.data,xe,{x:pt-Ue,y:0},{x:tt-Ue,y:ot+Rt},{width:Ue,height:Ue},_)}this.lut=_,this.image=xe,this.iconPositions=M,this.patternPositions=L,U&&(this.contentDescriptor=new B0e(J,se,C,_,W))}addImages(u,p,_,C){for(const[M,L]of u.entries()){const{bin:O,imagePosition:U,imageVariant:W}=z0e(M,L,_);p.set(M,U),C.push(O),L.hasRenderCallback&&this.haveRenderCallbacks.push(W.id)}}patchUpdatedImages(u,p,_,C){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(M=>u.hasImage(M,_)),u.dispatchRenderCallbacks(this.haveRenderCallbacks,_);for(const M of u.getUpdatedImages(_)){for(const L of this.iconPositions.keys()){const O=Of.parse(L);if(Gn.isEqual(O.id,M)){const U=u.getImage(M,_);this.patchUpdatedImage(this.iconPositions.get(L),U,p,null)}}for(const L of this.patternPositions.keys()){const O=Of.parse(L);if(Gn.isEqual(O.id,M)){const U=u.getImage(M,_);this.patchUpdatedImage(this.patternPositions.get(L),U,p,C||this.lut)}}}}patchUpdatedImage(u,p,_,C=null){if(!u||!p||u.version===p.version)return;u.version=p.version;const[M,L]=u.tl,O=u.sdf;if(this.lut||O){const U={width:p.data.width,height:p.data.height},W=new ii(U);ii.copy(p.data,W,{x:0,y:0},{x:0,y:0},U,C,O),_.update(W,{position:{x:M,y:L},recreateWhenResize:!1})}else _.update(p.data,{position:{x:M,y:L},recreateWhenResize:!1})}}Mr(aD,"ImagePosition"),Mr(sLe,"ImageAtlas",{omit:["lut"]}),Mr(tLe,"ImageAtlasReference");class iD{constructor(u){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=u&&u.fontstackCompositing||"client"}loadGlyphRange(u,p,_,C,M){if(this.fontstackCompositing==="server")return void iD.loadGlyphRange(u,p,_,C,M);const L=u.split(",").map(O=>O.trim()).filter(O=>O.length>0);L.length!==0?L.length!==1?this._loadMultipleFonts(L,p,_,C,M):this._loadFont(L[0],p,_,C,M):M(new Error("Empty fontstack"))}_loadMultipleFonts(u,p,_,C,M){const L=u.map(()=>null),O={completed:0,firstError:null,callbackCalled:!1},U=(W,J,se)=>{if(!O.callbackCalled&&(J&&!O.firstError&&(O.firstError=J),se&&(L[W]=se),O.completed++,O.completed===u.length)){O.callbackCalled=!0;const re=L.filter(xe=>xe!==null);if(re.length===0)return void M(O.firstError||new Error("All fonts failed to load"));const fe=this._composeGlyphs(re);M(null,fe)}};for(let W=0;W{U(W,J,se)})}_loadFont(u,p,_,C,M){const L=`${u}:${p}`;if(this.cachedRanges.has(L)){const U=this.cachedRanges.get(L);return void bd.frame(()=>M(null,U))}const O=this.pendingRequests.get(L);O?O.push(M):(this.pendingRequests.set(L,[M]),iD.loadGlyphRange(u,p,_,C,(U,W)=>{U||this.cachedRanges.set(L,W||null);const J=this.pendingRequests.get(L);if(this.pendingRequests.delete(L),J)for(const se of J)se(U,W)}))}_composeGlyphs(u){const p={};let _,C;for(const M of u)if(_===void 0&&M.ascender!==void 0&&(_=M.ascender),C===void 0&&M.descender!==void 0&&(C=M.descender),M.glyphs)for(const L in M.glyphs)p[L]===void 0&&(p[L]=M.glyphs[L]);return{glyphs:p,ascender:_,descender:C}}}iD.loadGlyphRange=function(y,u,p,_,C){const M=256*u,L=M+255,O=_.transformRequest(_.normalizeGlyphsURL(p).replace("{fontstack}",y).replace("{range}",`${M}-${L}`),kp.Glyphs);C0(O,(U,W)=>{if(U)C(U);else if(W){const J={},se=function(re){return new G9(re).readFields(g1t,{})}(W);for(const re of se.glyphs)J[re.id]=re;C(null,{glyphs:J,ascender:se.ascender,descender:se.descender})}})};const oD=1e20,U0e=new Float64Array(256);for(let y=0;y<256;y++){const u=.5-Math.pow(y/255,.45454545454545453);U0e[y]=u*Math.abs(u)}function rLe(y,u,p,_,C,M,L,O,U){for(let W=u;W-1);U++,M[U]=O,L[U]=W,L[U+1]=oD}for(let O=0,U=0;O<_;O++){for(;L[U+1]{if(L){C.ascender=L.ascender,C.descender=L.descender;for(const O in L.glyphs)this._doesCharSupportLocalGlyph(+O)||(C.glyphs[+O]=L.glyphs[+O]);C.ranges[p]=!0}for(const O of C.requests[p]||[])O(M,L);delete C.requests[p]}))}getGlyphs(u,p){const _=[],C=this.url||Va.GLYPHS_URL;for(const M in u)for(const L of u[M])_.push({stack:M,id:L});Ls(_,({stack:M,id:L},O)=>{let U=this.entries[M];U||(U=this.entries[M]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let W=U.glyphs[L];if(W!==void 0)return void O(null,{stack:M,id:L,glyph:W});if(W=this._tinySDF(U,M,L),W)return U.glyphs[L]=W,void O(null,{stack:M,id:L,glyph:W});const J=Math.floor(L/256);if(256*J>65535)return ra("glyphs > 65535 not supported"),void O(null,{stack:M,id:L,glyph:W});if(U.ranges[J])return void O(null,{stack:M,id:L,glyph:W});let se=U.requests[J];se||(se=U.requests[J]=[],this.glyphLoader.loadGlyphRange(M,J,C,this.requestManager,(re,fe)=>{if(fe){U.ascender=fe.ascender,U.descender=fe.descender;for(const xe in fe.glyphs)this._doesCharSupportLocalGlyph(+xe)||(U.glyphs[+xe]=fe.glyphs[+xe]);U.ranges[J]=!0}for(const xe of se)xe(re,fe);delete U.requests[J]})),se.push((re,fe)=>{re?O(re):fe&&O(null,{stack:M,id:L,glyph:fe.glyphs[L]||null})})},(M,L)=>{if(M)p(M);else if(L){const O={};for(const{stack:U,id:W,glyph:J}of L)O[U]===void 0&&(O[U]={}),O[U].glyphs===void 0&&(O[U].glyphs={}),O[U].glyphs[W]=J&&{id:J.id,bitmap:J.bitmap.clone(),metrics:J.metrics},O[U].ascender=this.entries[U].ascender,O[U].descender=this.entries[U].descender;p(null,O)}})}_doesCharSupportLocalGlyph(u){return this.localGlyphMode!==q0e.none&&(this.localGlyphMode===q0e.all?!!this.localFontFamily:!!this.localFontFamily&&(iw(u)||M7(u)||RT(u)||OT(u)||DT(u)||e6(u)||(p=u)>=131072&&p<=173791||(_=>_>=66736&&_<=66815)(u)));var p}_tinySDF(u,p,_){const C=this.localFontFamily;if(!C||!this._doesCharSupportLocalGlyph(_))return;let M=u.tinySDF;if(!M){let je="400";N1t.test(p)?je="900":k1t.test(p)?je="500":S1t.test(p)&&(je="200"),M=u.tinySDF=new Z9.TinySDF({fontFamily:C,fontWeight:je,fontSize:48,buffer:6,radius:16}),M.fontWeight=je}const L=M.fontWeight;if(this.localGlyphs[L][_])return this.localGlyphs[L][_];const O=String.fromCodePoint(_),{data:U,width:W,height:J,glyphWidth:se,glyphHeight:re,glyphLeft:fe,glyphTop:xe,glyphAdvance:we}=M.draw(O);return this.localGlyphs[L][_]={id:_,bitmap:new pu({width:W,height:J},U),metrics:{width:se/2,height:re/2,left:fe/2,top:xe/2-27,advance:we/2,localGlyph:!0}}}}function aLe(y,u){return y+u[1]-u[0]}function V0e(y,u,p,_,C=1){const M=[],L=y.imagePrimary,O=L.pixelRatio,U=L.paddedRect.w-2,W=L.paddedRect.h-2,J=(y.right-y.left)*C,se=(y.bottom-y.top)*C,re=L.stretchX||[[0,U]],fe=L.stretchY||[[0,W]],xe=re.reduce(aLe,0),we=fe.reduce(aLe,0),je=U-xe,Be=W-we;let Ye=0,Ue=xe,tt=0,ot=we,pt=0,Rt=je,_t=0,Et=Be;if(L.content&&_){const At=L.content;Ye=X9(re,0,At[0]),tt=X9(fe,0,At[1]),Ue=X9(re,At[0],At[2]),ot=X9(fe,At[1],At[3]),pt=At[0]-Ye,_t=At[1]-tt,Rt=At[2]-At[0]-Ue,Et=At[3]-At[1]-ot}const jt=(At,ns,is,xs)=>{const ks=Q9(At.stretch-Ye,Ue,J,y.left*C),ws=J9(At.fixed-pt,Rt,At.stretch,xe),Ks=Q9(ns.stretch-tt,ot,se,y.top*C),ds=J9(ns.fixed-_t,Et,ns.stretch,we),gs=Q9(is.stretch-Ye,Ue,J,y.left*C),Cs=J9(is.fixed-pt,Rt,is.stretch,xe),Bs=Q9(xs.stretch-tt,ot,se,y.top*C),Hs=J9(xs.fixed-_t,Et,xs.stretch,we),cr=new us(ks,Ks),Ds=new us(gs,Ks),tr=new us(gs,Bs),sr=new us(ks,Bs),wr=new us(ws/O,ds/O),Ar=new us(Cs/O,Hs/O),tn=u*Math.PI/180;if(tn){const ca=Math.sin(tn),dl=Math.cos(tn),xi=[dl,-ca,ca,dl];cr._matMult(xi),Ds._matMult(xi),sr._matMult(xi),tr._matMult(xi)}const zr=At.stretch+At.fixed,Sn=is.stretch+is.fixed,si=ns.stretch+ns.fixed,Wn=xs.stretch+xs.fixed,Pa=y.imageSecondary;return{tl:cr,tr:Ds,bl:sr,br:tr,texPrimary:{x:L.paddedRect.x+1+zr,y:L.paddedRect.y+1+si,w:Sn-zr,h:Wn-si},texSecondary:Pa?{x:Pa.paddedRect.x+1+zr,y:Pa.paddedRect.y+1+si,w:Sn-zr,h:Wn-si}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:wr,pixelOffsetBR:Ar,minFontScaleX:Rt/O/J,minFontScaleY:Et/O/se,isSDF:p}};if(L.stretchX||L.stretchY){const At=iLe(re,je,xe),ns=iLe(fe,Be,we);for(let is=0;is0?[Ye,-Ue]:tt<0?[-Ye,Ue]:Ye===0?[Ue,Ye]:[Ue,-Ye]}(p);let fe=Math.abs(u.top-u.bottom);for(const Be of u.positionedLines)fe-=Be.lineOffset;const xe=u.positionedLines.length,we=fe/xe;let je=u.top-p[1];for(let Be=0;BeM)&&(M=xe.x),(!fe||xe.y>L)&&(L=xe.y)}const U=Math.min(M-_,L-C);let W=U/2;const J=new _N([],A1t);if(U===0)return new us(_,C);for(let fe=_;fese.d||!se.d)&&(se=fe,p&&console.log("found best %d after %d probes",Math.round(1e4*fe.d)/1e4,re)),fe.max-se.d<=u||(W=fe.h/2,J.push(new xE(fe.p.x-W,fe.p.y-W,W,y)),J.push(new xE(fe.p.x+W,fe.p.y-W,W,y)),J.push(new xE(fe.p.x-W,fe.p.y+W,W,y)),J.push(new xE(fe.p.x+W,fe.p.y+W,W,y)),re+=4)}return p&&(console.log(`num probes: ${re}`),console.log(`best distance: ${se.d}`)),se.p}function A1t(y,u){return u.max-y.max}Z9.TinySDF=class{constructor({fontSize:y=24,buffer:u=3,radius:p=8,cutoff:_=.25,fontFamily:C="sans-serif",fontWeight:M="normal",fontStyle:L="normal",lang:O=null}={}){this.buffer=u,this.radius=p,this.cutoff=_,this.lang=O;const U=this.size=y+4*u,W=this._createCanvas(U),J=this.ctx=W.getContext("2d",{willReadFrequently:!0});J.font=`${L} ${M} ${y}px ${C}`,J.textBaseline="alphabetic",J.textAlign="left",J.fillStyle="black",this.gridOuter=new Float64Array(U*U),this.gridInner=new Float64Array(U*U),this.f=new Float64Array(U),this.z=new Float64Array(U+1),this.v=new Uint16Array(U)}_createCanvas(y){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(y,y);const u=document.createElement("canvas");return u.width=u.height=y,u}draw(y){const{width:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:_,actualBoundingBoxLeft:C,actualBoundingBoxRight:M}=this.ctx.measureText(y),L=Math.ceil(p),O=Math.floor(C),U=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(M)-O)),W=Math.max(0,Math.min(this.size-this.buffer,L+Math.ceil(_))),J=U+2*this.buffer,se=W+2*this.buffer,re=Math.max(J*se,0),fe=new Uint8ClampedArray(re),xe={data:fe,width:J,height:se,glyphWidth:U,glyphHeight:W,glyphTop:L,glyphLeft:O,glyphAdvance:u};if(U===0||W===0)return xe;const{ctx:we,buffer:je,gridInner:Be,gridOuter:Ye}=this;this.lang&&(we.lang=this.lang),we.clearRect(je,je,U,W),we.fillText(y,je-O,je+L);const Ue=we.getImageData(je,je,U,W);Ye.fill(oD,0,re),Be.fill(0,0,re);let tt=3;for(let Rt=0;RtM.y!=we.y>M.y&&M.x<(we.x-xe.x)*(M.y-xe.y)/(we.y-xe.y)+xe.x&&(O=!O),U=Math.min(U,Le(M,xe,we))}}return(O?1:-1)*Math.sqrt(U)}(this.p,C),this.max=this.d+this.h*Math.SQRT2}}const M1t=Object.keys,H0e=Number.POSITIVE_INFINITY,I1t=Math.sqrt(2);function _w(y,u,p,_,C,M){const L=D0e(y)&&y.collisionPadding?y.collisionPadding:[0,0,0,0],O={top:y.top-L[1],bottom:y.bottom+L[3],left:y.left-L[0],right:y.right+L[2],scaled:!1};return _!==void 0&&function(U,W){U.top*=W,U.bottom*=W,U.left*=W,U.right*=W,U.scaled=!0}(O,_),M&&(O.left+=M[0],O.right+=M[0],O.top+=M[1],O.bottom+=M[1]),p&&function(U,W,J){if(!W)return;const se=We(W),re=new us(J?J[0]:0,J?J[1]:0),fe=new us(U.left,U.top),xe=new us(U.right,U.top),we=new us(U.left,U.bottom),je=new us(U.right,U.bottom);fe._rotateAround(se,re),xe._rotateAround(se,re),we._rotateAround(se,re),je._rotateAround(se,re),U.left=Math.min(fe.x,xe.x,we.x,je.x),U.right=Math.max(fe.x,xe.x,we.x,je.x),U.top=Math.min(fe.y,xe.y,we.y,je.y),U.bottom=Math.max(fe.y,xe.y,we.y,je.y)}(O,p,C),u?{top:Math.min(u.top,O.top),bottom:Math.max(u.bottom,O.bottom),left:Math.min(u.left,O.left),right:Math.max(u.right,O.right),scaled:u.scaled||O.scaled}:O}function cLe(y,[u,p]){let _=0,C=0;if(p===H0e){u<0&&(u=0);const M=u/I1t;switch(y){case"top-right":case"top-left":C=M-7;break;case"bottom-right":case"bottom-left":C=7-M;break;case"bottom":C=7-u;break;case"top":C=u-7}switch(y){case"top-right":case"bottom-right":_=-M;break;case"top-left":case"bottom-left":_=M;break;case"left":_=u;break;case"right":_=-u}}else{switch(u=Math.abs(u),p=Math.abs(p),y){case"top-right":case"top-left":case"top":C=p-7;break;case"bottom-right":case"bottom-left":case"bottom":C=7-p}switch(y){case"top-right":case"bottom-right":case"right":_=-u;break;case"top-left":case"bottom-left":case"left":_=u}}return[_,C]}function P1t(y,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe){const we=y.layers[0],je=we.appearances;if(je.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const Be={iconBBox:null,iconVerticalBBox:null},Ye={textBBox:null,textVerticalBBox:null},{baseIconRotate:Ue,baseTextRotate:tt,iconScaleFactor:ot}=function(Rt,_t,Et){const jt=Rt.get("icon-rotate").evaluate(_t,{},Et),At=Rt.get("text-rotate").evaluate(_t,{},Et),[ns,is]=Rt.get("icon-size-scale-range");return{baseIconRotate:jt,baseTextRotate:At,iconScaleFactor:Mt(1,ns,is)}}(_,C,M);u&&(Be.iconBBox=_w(u,Be.iconBBox,Ue),p)&&(Be.iconVerticalBBox=_w(p,Be.iconVerticalBBox,Ue+90));const pt=t$(se.horizontal);pt&&(Ye.textBBox=_w(pt,Ye.textBBox,tt,1,fe)),se.vertical&&(Ye.textVerticalBBox=_w(se.vertical,Ye.textVerticalBBox,tt+90,1,fe));for(const Rt of je)Rt.hasIconLayoutProperties()&&L1t(Be,y,we,Rt,C,M,O,Ue,L,U,u,W,ot,J,xe),Rt.hasTextLayoutProperties()&&D1t(Ye,we,Rt,C,M,fe,tt,re,pt,se.vertical);return{iconBBox:Be.iconBBox,iconVerticalBBox:Be.iconVerticalBBox,textBBox:Ye.textBBox,textVerticalBBox:Ye.textVerticalBBox}}function L1t(y,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe){const{appearanceIconOffset:we,appearanceIconRotate:je,appearanceIconSize:Be}=dLe(_,p,C,M,L,O,U,W.iconScaleFactor);let Ye=null,Ue=null,tt=null;_.hasLayoutProperty("icon-image")?tt=function(pt,Rt,_t,Et,jt,At,ns,is){let xs=null;const ks=Rt.getAppearanceValueAndResolveTokens(_t,"icon-image",Et,jt,is);if(ks){const ws=pt.getResolvedImageFromTokens(ks),Ks=_t.hasLayoutProperty("icon-size")?_t.getUnevaluatedLayoutProperty("icon-size"):Rt._unevaluatedLayout._values["icon-size"],ds=lD(ws,QN(pt.zoom,Ks,pt.worldview,is),Ks,jt,pt.zoom,Et,pt.pixelRatio,ns,pt.worldview,is);xs=At.get(ds.iconPrimary.toString())}return xs}(u,p,_,C,M,se,re,xe):J&&(tt=J.imagePrimary),tt&&(Ye=K9(tt,null,we,fe),u.allowVerticalPlacement&&(Ue=K9(tt,null,we,fe)));const ot=U>0?Be/U:1;Ye&&(y.iconBBox=_w(Ye,y.iconBBox,je,ot!==1?ot:void 0)),Ue&&(y.iconVerticalBBox=_w(Ue,y.iconVerticalBBox,je+90,ot!==1?ot:void 0))}function dLe(y,u,p,_,C,M,L,O){const U=y.hasLayoutProperty("icon-offset")?u.getAppearanceValueAndResolveTokens(y,"icon-offset",p,_,[]):null,W=U&&Array.isArray(U)?U:C,J=y.hasLayoutProperty("icon-rotate")?u.getAppearanceValueAndResolveTokens(y,"icon-rotate",p,_,[]):null,se=typeof J=="number"?J:M,re=y.hasLayoutProperty("icon-size")?u.getAppearanceValueAndResolveTokens(y,"icon-size",p,_,[]):null;return{appearanceIconOffset:W,appearanceIconRotate:se,appearanceIconSize:typeof re=="number"?re*O:L}}function D1t(y,u,p,_,C,M,L,O,U,W){const{appearanceTextOffset:J,appearanceTextRotate:se,appearanceTextSize:re}=uLe(p,u,_,C,M,L,O),fe=re/O,xe=[(J[0]-M[0])*fe,(J[1]-M[1])*fe],we=xe[0]!==0||xe[1]!==0;U&&(y.textBBox=_w(U,y.textBBox,se,fe,J,we?xe:void 0)),W&&(y.textVerticalBBox=_w(W,y.textVerticalBBox,se+90,fe,J,we?xe:void 0))}function uLe(y,u,p,_,C,M,L){const O=y.hasLayoutProperty("text-offset")?u.getAppearanceValueAndResolveTokens(y,"text-offset",p,_,[]):null,U=O&&Array.isArray(O)?[O[0]*Oc,O[1]*Oc]:C,W=y.hasLayoutProperty("text-rotate")?u.getAppearanceValueAndResolveTokens(y,"text-rotate",p,_,[]):null,J=typeof W=="number"?W:M,se=y.hasLayoutProperty("text-size")?u.getAppearanceValueAndResolveTokens(y,"text-size",p,_,[]):null;return{appearanceTextOffset:U,appearanceTextRotate:J,appearanceTextSize:typeof se=="number"?se:L}}function e$(y,u,p,_,C,M,L,O,U){if(!u||!u.usvg)return;const W=WPe(_),J=WPe(C),se=M!=="both"&&M!=="width"||!HPe(_)?1:J.width/W.width,re=M!=="both"&&M!=="height"||!GPe(_)?1:J.height/W.height;p.scaleSelf(se,re);const fe=p.toString();L.set(fe,p),O.set(fe,u);const{imagePosition:xe}=z0e(fe,u,1);U.set(fe,xe)}function hLe(y,u,p,_,C,M,L,O,U,W){if(!y)return;const J=function(se,re,fe,xe,we,je,Be){if(se.kind==="camera")return se.maxSize;if(se.kind==="composite"){const Ye=re.possiblyEvaluate(new fi(se.maxZoom,{worldview:je}),fe,Be).evaluate(we,{},fe,Be),Ue=re.possiblyEvaluate(new fi(se.minZoom,{worldview:je}),fe,Be).evaluate(we,{},fe,Be);return Math.max(Ye,Ue)}return re.possiblyEvaluate(new fi(xe,{worldview:je}),fe,Be).evaluate(we,{},fe,Be)}(u,p,_,C,M,U,W);return y.scaleSelf(J*O*L)}function lD(y,u,p,_,C,M,L,O,U,W){return{iconPrimary:hLe(y.getPrimary(),u,p,_,C,M,L,O,U,W),iconSecondary:hLe(y.getSecondary(),u,p,_,C,M,L,O,U,W)}}function R1t(y,u,p){if(!u)return;const _=p.get(y.toString()),C=p.get(u.toString());_&&C&&(_.paddedRect.w===C.paddedRect.w&&_.paddedRect.h===C.paddedRect.h||ra(`Mismatch in icon variant sizes: ${y.toString()} and ${u.toString()}`),_.usvg!==C.usvg&&ra(`Mismatch in icon variant image types: ${y.id} and ${u.id}`))}function mLe(y,u,p,_){if(!y)return;const C=u.get(p.toString());if(C&&(y.imagePrimary=C),_){const M=u.get(_.toString());y.imageSecondary=M}}function O1t(y,u){for(const p in y.horizontal)fLe(y.horizontal[p],u);fLe(y.vertical,u)}function fLe(y,u){if(y){for(const p of y.positionedLines)for(const _ of p.positionedGlyphs)if(_.image!==null){const C=_.image.toString();_.rect=u.get(C).paddedRect}}}function G0e(y){switch(y){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function F1t(y,u,p,_,C,M,L,O,U){const W=t$(M.horizontal)||M.vertical,J=p.get("icon-text-fit-padding").evaluate(_,{},C);let se,re=u;return u&&U!=="none"&&(y.allowVerticalPlacement&&M.vertical&&(se=R0e(u,M.vertical,U,J,O,L)),W&&(re=R0e(u,W,U,J,O,L))),{defaultShapedIcon:re,verticallyShapedIcon:se}}function pLe(y,u){return y*u/24}function B1t(y,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye,Ue,tt,ot,pt,Rt){let _t=L.textMaxSize.evaluate(u,{},re);_t===void 0?_t=O*L.textScaleFactor:_t*=L.textScaleFactor;const Et=y.layers[0].layout,jt=pLe(O,L.textScaleFactor),At=t$(p.horizontal)||p.vertical,ns=y.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),is=y.getAppearanceFeatureData(u.index);(je!=="none"||ns)&&is&&(is.textShaping=At,is.iconTextFitPadding=Et.get("icon-text-fit-padding").evaluate(u,{},re),is.fontScale=jt,is.textScaleFactor=L.textScaleFactor);const xs=fe.name==="globe",ks=y.tilePixelRatio*_t/24,ws=(Hs=y.overscaling,y.zoom>18&&Hs>2&&(Hs>>=1),Math.max(mr/(512*Hs),1)*Et.get("symbol-spacing")),Ks=Et.get("text-padding")*y.tilePixelRatio,ds=Et.get("icon-padding")*y.tilePixelRatio,gs=We(Et.get("text-max-angle")),Cs=Et.get("icon-rotation-alignment")==="map"&&Ue!=="point",Bs=ws/2;var Hs;y.hasAnyIconTextFit===!1&&je!=="none"&&(y.hasAnyIconTextFit=!0);const cr=u.properties?+u.properties[rb]:null,Ds=cr&&y.elevationFeatureIdToIndex?y.elevationFeatureIdToIndex.get(cr):65535,tr=(sr,wr,Ar)=>{if(wr.x<0||wr.x>=mr||wr.y<0||wr.y>=mr)return;let tn=null;if(xs){const{x:zr,y:Sn,z:si}=fe.projectTilePoint(wr.x,wr.y,Ar);tn={anchor:new lb(zr,Sn,si,0,void 0),up:fe.upVector(Ar,wr.x,wr.y)}}(function(zr,Sn,si,Wn,Pa,ca,dl,xi,ei,Vi,Ro,Fc,eo,ul,ac,Fl,ic,pa,Yd,hh,kl,ed,Pu,Zd,Wo,wc,jm,wE,Uh,mve,_D,wD){const cb=zr.addToLineVertexArray(Sn,Wn);let Wf,zp,Sw,Cw,xa,td,hl,jc=0,$p=0,nf=0,Kf=0,af=-1,jD=-1;const ug={};let jE=It("");const X0=si?si.anchor:Sn,NE=wE!=="none";let oc=0,_d=0;if(ei._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Xd=ei.layout.get("text-offset").evaluate(kl,{},Wo);oc=Xd[0]*Oc,_d=Xd[1]*Oc}else oc=ei.layout.get("text-radial-offset").evaluate(kl,{},Wo)*Oc,_d=H0e;if(zr.allowVerticalPlacement&&Pa.vertical){const Xd=Pa.vertical;if(ac)td=Y0e(Xd),xi&&(hl=Y0e(xi));else{const Lu=ei.layout.get("text-rotate").evaluate(kl,{},Wo)+90;Sw=s$(Vi,X0,Sn,Ro,Fc,eo,Xd,ul,Lu,Fl,wD),xi&&(Cw=s$(Vi,X0,Sn,Ro,Fc,eo,xi,pa,Lu,null,_D))}}if(ca){const Xd=ei.layout.get("icon-rotate").evaluate(kl,{},Wo),Lu=V0e(ca,Xd,Pu,NE,ed.iconScaleFactor),Zf=xi?V0e(xi,Xd,Pu,NE,ed.iconScaleFactor):void 0;zp=s$(Vi,X0,Sn,Ro,Fc,eo,ca,pa,Xd,null,mve);const Q0=function(Sy,ND,k6e,Dbt,Rbt,S6e,C6e,Obt,EUs,xve){const T6e=Sy.layers[0],E6e=T6e.appearances;let SE=ND.length;if(k6e&&(SE=Math.max(SE,k6e.length)),E6e.length===0)return SE;const[Fbt,Bbt]=Dbt.get("icon-size-scale-range"),zbt=Mt(1,Fbt,Bbt);for(const g$ of E6e)if(g$.hasLayoutProperty("icon-image")){const A6e=T6e.getAppearanceValueAndResolveTokens(g$,"icon-image",S6e,C6e,xve);if(A6e){const M6e=Sy.getResolvedImageFromTokens(A6e);if(M6e){const I6e=g$.hasLayoutProperty("icon-size")?g$.getUnevaluatedLayoutProperty("icon-size"):Rbt._values["icon-size"],$bt=lD(M6e,QN(Sy.zoom,I6e,Sy.worldview,xve),I6e,C6e,Sy.zoom,S6e,Sy.pixelRatio,zbt,Sy.worldview,xve),P6e=Obt.get($bt.iconPrimary.toString());P6e&&(SE=Math.max(SE,C1t(P6e)))}}}return SE}(zr,Lu,Zf,ei.layout,ei._unevaluatedLayout,kl,Wo,zr.iconAtlasPositions,0,Zd);jc=4*Q0;const x$=ei.layout.get("icon-size").evaluate(kl,{},Wo,Zd),fve=ed.compositeIconSizes?ed.compositeIconSizes[0].evaluate(kl,{},Wo,Zd):0,pve=ed.compositeIconSizes?ed.compositeIconSizes[1].evaluate(kl,{},Wo,Zd):0,kE=K0e(zr.layerIds[0],zr.iconSizeData,x$,ca.imagePrimary.usvg?1:ed.iconScaleFactor,fve,pve);zr.addSymbols(zr.icon,Lu,kE,hh,Yd,kl,void 0,si,Sn,cb.lineStartIndex,cb.lineLength,-1,Zd,Wo,wc,jm,zr.symbolInstances.length,Q0),af=zr.icon.placedSymbolArray.length-1,Zf&&($p=4*Q0,zr.addSymbols(zr.icon,Zf,kE,hh,Yd,kl,rf.vertical,si,Sn,cb.lineStartIndex,cb.lineLength,-1,Zd,Wo,wc,jm,zr.symbolInstances.length,Q0),jD=zr.icon.placedSymbolArray.length-1)}for(const Xd in Pa.horizontal){const Lu=Xd,Zf=Pa.horizontal[Lu];Wf||(jE=It(Zf.text),ac?xa=Y0e(Zf):Wf=s$(Vi,X0,Sn,Ro,Fc,eo,Zf,ul,ei.layout.get("text-rotate").evaluate(kl,{},Wo),Fl,wD));const Q0=Zf.positionedLines.length===1;if(nf+=xLe(zr,si,Sn,Zf,dl,ei,ac,kl,Fl,cb,Pa.vertical?rf.horizontal:rf.horizontalOnly,Q0?M1t(Pa.horizontal):[Lu],ug,af,ed,Zd,Wo,zr.symbolInstances.length,wc),Q0)break}Pa.vertical&&(Kf+=xLe(zr,si,Sn,Pa.vertical,dl,ei,ac,kl,Fl,cb,rf.vertical,["vertical"],ug,jD,ed,Zd,Wo,zr.symbolInstances.length,wc));let gl=-1;const Yf=(Xd,Lu)=>Xd?Math.max(Xd,Lu):Lu;gl=Yf(xa,gl),gl=Yf(td,gl),gl=Yf(hl,gl);const qh=gl>-1?1:0;zr.glyphOffsetArray.length>=65535&&ra("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),kl.sortKey!==void 0&&zr.addToSortKeyRanges(zr.symbolInstances.length,kl.sortKey),zr.symbolInstances.emplaceBack(Sn.x,Sn.y,X0.x,X0.y,X0.z,ug.right>=0?ug.right:-1,ug.center>=0?ug.center:-1,ug.left>=0?ug.left:-1,ug.vertical>=0?ug.vertical:-1,af,jD,jE,Wf!==void 0?Wf:zr.collisionBoxArray.length,Wf!==void 0?Wf+1:zr.collisionBoxArray.length,Sw!==void 0?Sw:zr.collisionBoxArray.length,Sw!==void 0?Sw+1:zr.collisionBoxArray.length,zp!==void 0?zp:zr.collisionBoxArray.length,zp!==void 0?zp+1:zr.collisionBoxArray.length,Cw||zr.collisionBoxArray.length,Cw?Cw+1:zr.collisionBoxArray.length,Ro,nf,Kf,jc,$p,qh,0,oc,_d,gl,0,NE?1:0,Uh)})(y,wr,tn,sr,p,_,M,C,y.layers[0],y.collisionBoxArray,u.index,u.sourceLayerIndex,y.index,Ks,Ye,W,0,ds,Cs,Be,u,L,J,se,re,xe,we,je,Ds,tt,ot,pt)};if(Ue==="line")for(const sr of L9(u.geometry,0,0,mr,mr)){const wr=j1t(sr,ws,gs,p.vertical||At,_,24,ks,y.overscaling,mr);for(const Ar of wr)At&&z1t(y,At.text,Bs,Ar)||tr(sr,Ar,re)}else if(Ue==="line-center"){for(const sr of u.geometry)if(sr.length>1){const wr=w1t(sr,gs,p.vertical||At,_,24,ks);wr&&tr(sr,wr,re)}}else if(u.type==="Polygon")for(const sr of H6(u.geometry,0)){const wr=E1t(sr,16);tr(sr[0],new lb(wr.x,wr.y,0,0,void 0),re)}else if(u.type==="LineString")for(const sr of u.geometry)tr(sr,new lb(sr[0].x,sr[0].y,0,0,void 0),re);else if(u.type==="Point")for(const sr of u.geometry)for(const wr of sr)tr([wr],new lb(wr.x,wr.y,0,0,void 0),re)}const W0e=255,JN=W0e*ob;function xLe(y,u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye){const Ue=lLe(0,_,U,M,L,O,C,y.allowVerticalPlacement,void 0,xe.textScaleFactor),tt=M.layout.get("text-size").evaluate(O,{},je),ot=xe.compositeTextSizes?xe.compositeTextSizes[0].evaluate(O,{},je):0,pt=xe.compositeTextSizes?xe.compositeTextSizes[1].evaluate(O,{},je):0,Rt=K0e(y.layerIds[0],y.textSizeData,tt,xe.textScaleFactor,ot,pt);y.addSymbols(y.text,Ue,Rt,U,L,O,J,u,p,W.lineStartIndex,W.lineLength,fe,we,je,Ye,!1,Be,Ue.length);for(const _t of se)re[_t]=y.text.placedSymbolArray.length-1;return 4*Ue.length}function K0e(y,u,p,_,C,M){const L=u;let O=null;return L.kind==="source"?(O=[ob*p*_],O[0]>JN&&ra(`${y}: Value for "text-size" or "icon-size" is >= ${W0e}. Reduce your "text-size" or "icon-size".`)):L.kind==="composite"&&(O=[ob*C*_,ob*M*_],(O[0]>JN||O[1]>JN)&&ra(`${y}: Value for "text-size" or "icon-size" is >= ${W0e}. Reduce your "text-size" or "icon-size".`)),O}function t$(y){for(const u in y)return y[u];return null}function s$(y,u,p,_,C,M,L,O,U,W,J){let se,re,fe,xe;if(se=J?J.top:L.top,re=J?J.bottom:L.bottom,fe=J?J.left:L.left,xe=J?J.right:L.right,D0e(L)&&L.collisionPadding){const we=L.collisionPadding;fe-=we[0],se-=we[1],xe+=we[2],re+=we[3]}if(U){const we=new us(fe,se),je=new us(xe,se),Be=new us(fe,re),Ye=new us(xe,re),Ue=We(U);let tt=new us(0,0);W&&(tt=new us(W[0],W[1])),we._rotateAround(Ue,tt),je._rotateAround(Ue,tt),Be._rotateAround(Ue,tt),Ye._rotateAround(Ue,tt),fe=Math.min(we.x,je.x,Be.x,Ye.x),xe=Math.max(we.x,je.x,Be.x,Ye.x),se=Math.min(we.y,je.y,Be.y,Ye.y),re=Math.max(we.y,je.y,Be.y,Ye.y)}return y.emplaceBack(u.x,u.y,u.z,p.x,p.y,fe,se,xe,re,O,_,C,M),y.length-1}function Y0e(y){D0e(y)&&y.collisionPadding&&(y.top-=y.collisionPadding[1],y.bottom+=y.collisionPadding[3]);const u=y.bottom-y.top;return u>0?Math.max(10,u):null}function z1t(y,u,p,_){const C=y.compareText;if(u in C){const M=C[u];for(let L=M.length-1;L>=0;L--)if(_.dist(M[L])Ue&&(tt(pt,xs,_t,Et,ns,is),tt(xs,Rt,ns,is,jt,At))}tt(se,re,_,M,C,M),tt(re,fe,C,M,C,L),tt(fe,xe,C,L,_,L),tt(xe,se,_,L,_,M),we-=Ue,je-=Ue,Be+=Ue,Ye+=Ue;const ot=1/Math.max(Be-we,Ye-je);return{scale:ot,x:we*ot,y:je*ot,x2:Be*ot,y2:Ye*ot,projection:u}}function yLe(y,{x:u,y:p},_=0){return new us(((u-_)*y.scale-y.x)*mr,(p*y.scale-y.y)*mr)}const $1t=N(new Float32Array(16));class ww{constructor(u){this.spec=u,this.name=u.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(u,p){return{x:0,y:0,z:0}}unproject(u,p){return new di(0,0)}projectTilePoint(u,p,_){return{x:u,y:p,z:0}}locationPoint(u,p,_,C=!0){return u._coordinatePoint(u.locationCoordinate(p,_),C)}pixelsPerMeter(u,p){return ch(1,u)*p}pixelSpaceConversion(u,p,_){return 1}farthestPixelDistance(u){return gLe(u,u.pixelsPerMeter)}pointCoordinate(u,p,_,C){const M=u.horizonLineFromTop(!1),L=new us(p,Math.max(M,_));return u.rayIntersectionCoordinate(u.pointRayIntersection(L,C))}pointCoordinate3D(u,p,_){const C=new us(p,_);if(u.elevation)return u.elevation.pointCoordinate(C);{const M=this.pointCoordinate(u,C.x,C.y,0);return[M.x,M.y,M.z]}}isPointAboveHorizon(u,p){if(u.elevation&&u.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(u,p.x,p.y);const _=u.horizonLineFromTop();return p.y<_}createInversionMatrix(u,p){return $1t}createTileMatrix(u,p,_){let C,M,L;const O=_.canonical,U=N(new Float64Array(16));if(this.isReprojectedInTileSpace){const W=ek(O,this);C=1,M=W.x+_.wrap*W.scale,L=W.y,P(U,U,[C/W.scale,C/W.scale,u.pixelsPerMeter/p])}else C=p/u.zoomScale(O.z),M=(O.x+Math.pow(2,O.z)*_.wrap)*C,L=O.y*C;return A(U,U,[M,L,0]),P(U,U,[C/mr,C/mr,1]),U}upVector(u,p,_){return[0,0,1]}upVectorScale(u,p,_){return{metersToTile:1}}}class U1t extends ww{constructor(u){super(u),this.range=[4,7],this.center=u.center||[-96,37.5];const[p,_]=this.parallels=u.parallels||[29.5,45.5],C=Math.sin(We(p));this.n=(C+Math.sin(We(_)))/2,this.c=1+C*(2*this.n-C),this.r0=Math.sqrt(this.c)/this.n}project(u,p){const{n:_,c:C,r0:M}=this,L=We(u-this.center[0]),O=We(p),U=Math.sqrt(C-2*_*Math.sin(O))/_;return{x:U*Math.sin(L*_),y:U*Math.cos(L*_)-M,z:0}}unproject(u,p){const{n:_,c:C,r0:M}=this,L=M+p;let O=Math.atan2(u,Math.abs(L))*Math.sign(L);L*_<0&&(O-=Math.PI*Math.sign(u)*Math.sign(L));const U=We(this.center[0])*_;O=Es(O,-Math.PI-U,Math.PI-U);const W=Mt(He(O/_)+this.center[0],-180,180),J=Math.asin(Mt((C-(u*u+L*L)*_*_)/(2*_),-1,1)),se=Mt(He(J),-85.051129,vm);return new di(W,se)}}const cD=1.340264,dD=-.081106,uD=893e-6,hD=.003796,r$=Math.sqrt(3)/2;class q1t extends ww{project(u,p){p=p/180*Math.PI,u=u/180*Math.PI;const _=Math.asin(r$*Math.sin(p)),C=_*_,M=C*C*C;return{x:.5*(u*Math.cos(_)/(r$*(cD+3*dD*C+M*(7*uD+9*hD*C)))/Math.PI+.5),y:1-.5*(_*(cD+dD*C+M*(uD+hD*C))/Math.PI+1),z:0}}unproject(u,p){u=(2*u-.5)*Math.PI;let _=p=(2*(1-p)-1)*Math.PI,C=_*_,M=C*C*C;for(let J,se,re,fe=0;fe<12&&(se=_*(cD+dD*C+M*(uD+hD*C))-p,re=cD+3*dD*C+M*(7*uD+9*hD*C),J=se/re,_=Mt(_-J,-Math.PI/3,Math.PI/3),C=_*_,M=C*C*C,!(Math.abs(J)<1e-12));++fe);const L=r$*u*(cD+3*dD*C+M*(7*uD+9*hD*C))/Math.cos(_),O=Math.asin(Math.sin(_)/r$),U=Mt(180*L/Math.PI,-180,180),W=Mt(180*O/Math.PI,-85.051129,vm);return new di(U,W)}}class V1t extends ww{constructor(u){super(u),this.wrap=!0,this.supportsWorldCopies=!0}project(u,p){return{x:.5+u/360,y:.5-p/360,z:0}}unproject(u,p){const _=360*(u-.5),C=Mt(360*(.5-p),-85.051129,vm);return new di(_,C)}}const gE=Math.PI/2;function n$(y){return Math.tan((gE+y)/2)}class H1t extends ww{constructor(u){super(u),this.center=u.center||[0,30];const[p,_]=this.parallels=u.parallels||[30,30];let C=We(p),M=We(_);this.southernCenter=C+M<0,this.southernCenter&&(C=-C,M=-M);const L=Math.cos(C),O=n$(C);this.n=C===M?Math.sin(C):Math.log(L/Math.cos(M))/Math.log(n$(M)/O),this.f=L*Math.pow(n$(C),this.n)/this.n}project(u,p){p=We(p),this.southernCenter&&(p=-p),u=We(u-this.center[0]);const _=1e-6,{n:C,f:M}=this;M>0?p<-gE+_&&(p=-gE+_):p>gE-_&&(p=gE-_);const L=M/Math.pow(n$(p),C);let O=L*Math.sin(C*u),U=M-L*Math.cos(C*u);return O=.5*(O/Math.PI+.5),U=.5*(U/Math.PI+.5),{x:O,y:this.southernCenter?U:1-U,z:0}}unproject(u,p){u=(2*u-.5)*Math.PI,this.southernCenter&&(p=1-p),p=(2*(1-p)-.5)*Math.PI;const{n:_,f:C}=this,M=C-p,L=Math.sign(M),O=Math.sign(_)*Math.sqrt(u*u+M*M);let U=Math.atan2(u,Math.abs(M))*L;M*_<0&&(U-=Math.PI*Math.sign(u)*L);const W=Mt(He(U/_)+this.center[0],-180,180),J=Mt(He(2*Math.atan(Math.pow(C/O,1/_))-gE),-85.051129,vm);return new di(W,this.southernCenter?-J:J)}}class vLe extends ww{constructor(u){super(u),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(u,p){return{x:by(u),y:ig(p),z:0}}unproject(u,p){const _=ym(u),C=Xc(p);return new di(_,C)}}const bLe=We(vm);class G1t extends ww{project(u,p){const _=(p=We(p))*p,C=_*_;return{x:.5*((u=We(u))*(.8707-.131979*_+C*(C*(.003971*_-.001529*C)-.013791))/Math.PI+.5),y:1-.5*(p*(1.007226+_*(.015085+C*(.028874*_-.044475-.005916*C)))/Math.PI+1),z:0}}unproject(u,p){u=(2*u-.5)*Math.PI;let _=p=(2*(1-p)-1)*Math.PI,C=25,M=0,L=_*_;do{L=_*_;const W=L*L;M=(_*(1.007226+L*(.015085+W*(.028874*L-.044475-.005916*W)))-p)/(1.007226+L*(.045255+W*(.259866*L-.311325-.005916*11*W))),_=Mt(_-M,-bLe,bLe)}while(Math.abs(M)>1e-6&&--C>0);L=_*_;const O=Mt(He(u/(.8707+L*(L*(L*L*L*(.003971-.001529*L)-.013791)-.131979))),-180,180),U=He(_);return new di(O,U)}}const _Le=We(vm);class W1t extends ww{project(u,p){p=We(p),u=We(u);const _=Math.cos(p),C=2/Math.PI,M=Math.acos(_*Math.cos(u/2)),L=Math.sin(M)/M,O=.5*(u*C+2*_*Math.sin(u/2)/L)||0,U=.5*(p+Math.sin(p)/L)||0;return{x:.5*(O/Math.PI+.5),y:1-.5*(U/Math.PI+1),z:0}}unproject(u,p){let _=u=(2*u-.5)*Math.PI,C=p=(2*(1-p)-1)*Math.PI,M=25;const L=1e-6;let O=0,U=0;do{const W=Math.cos(C),J=Math.sin(C),se=2*J*W,re=J*J,fe=W*W,xe=Math.cos(_/2),we=Math.sin(_/2),je=2*xe*we,Be=we*we,Ye=1-fe*xe*xe,Ue=Ye?1/Ye:0,tt=Ye?Math.acos(W*xe)*Math.sqrt(1/Ye):0,ot=.5*(2*tt*W*we+2*_/Math.PI)-u,pt=.5*(tt*J+C)-p,Rt=.5*Ue*(fe*Be+tt*W*xe*re)+1/Math.PI,_t=Ue*(je*se/4-tt*J*we),Et=.125*Ue*(se*we-tt*J*fe*je),jt=.5*Ue*(re*xe+tt*Be*W)+.5,At=_t*Et-jt*Rt;O=(pt*_t-ot*jt)/At,U=(ot*Et-pt*Rt)/At,_=Mt(_-O,-Math.PI,Math.PI),C=Mt(C-U,-_Le,_Le)}while((Math.abs(O)>L||Math.abs(U)>L)&&--M>0);return new di(He(_),He(C))}}class wLe extends ww{constructor(u){super(u),this.center=u.center||[0,0],this.parallels=u.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(We(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(u,p){const{scale:_,cosPhi:C}=this;return{x:We(u)*C*_+.5,y:-Math.sin(We(p))/C*_+.5,z:0}}unproject(u,p){const{scale:_,cosPhi:C}=this,M=-(p-.5)/_,L=Mt(He((u-.5)/_)/C,-180,180),O=Math.asin(Mt(M*C,-1,1)),U=Mt(He(O),-85.051129,vm);return new di(L,U)}}class K1t extends vLe{constructor(u){super(u),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(u,p,_){const C=Ln(u,p,_);return rt(C,C,Tn(Js(_))),{x:C[0],y:C[1],z:C[2]}}locationPoint(u,p,_){const C=ag(p.lat,p.lng),M=Te([],C),L=_?u._centerAltitude+_:u.elevation?u.elevation.getAtPointOrZero(u.locationCoordinate(p),u._centerAltitude):u._centerAltitude;Pe(C,C,M,ch(1,0)*mr*L);const O=N(new Float64Array(16));return T(O,u.pixelMatrix,u.globeMatrix),rt(C,C,O),new us(C[0],C[1])}pixelsPerMeter(u,p){return ch(1,0)*p}pixelSpaceConversion(u,p,_){const C=ch(1,u)*p,M=Jr(ch(1,45)*p,C,_);return this.pixelsPerMeter(u,p)/M}createTileMatrix(u,p,_){const C=Ia(Js(_.canonical));return T(new Float64Array(16),u.globeMatrix,C)}createInversionMatrix(u,p){const{center:_}=u,C=Tn(Js(p));return B(C,C,We(_.lng)),D(C,C,We(_.lat)),P(C,C,[u._pixelsPerMercatorPixel,u._pixelsPerMercatorPixel,1]),Float32Array.from(C)}pointCoordinate(u,p,_,C){return Rs(u,p,_,!0)||new fu(0,0)}pointCoordinate3D(u,p,_){const C=this.pointCoordinate(u,p,_,0);return[C.x,C.y,C.z]}isPointAboveHorizon(u,p){return!Rs(u,p.x,p.y,!1)}farthestPixelDistance(u){const p=function(C,M){const L=C.cameraToCenterDistance,O=C._centerAltitude*M,U=C._camera,W=C._camera.forward(),J=me([],Me([],W,-L),[0,0,O]),se=C.worldSize/(2*Math.PI),re=[0,0,-se],fe=C.width/C.height,xe=Math.tan(C.fovAboveCenter),we=Me([],U.up(),xe),je=Me([],U.right(),xe*fe),Be=Te([],me([],me([],W,we),je)),Ye=[];let Ue;if(new R6(J,Be).closestPointOnSphere(re,se,Ye)){const tt=me([],Ye,re),ot=nt([],tt,J);Ue=Math.cos(C.fovAboveCenter)*ce(ot)}else{const tt=nt([],J,re),ot=nt([],re,J);Te(ot,ot);const pt=ce(tt)-se;Ue=Math.sqrt(pt*(pt+2*se));const Rt=Math.acos(Ue/(se+pt))-Math.acos(ye(W,ot));Ue*=Math.cos(Rt)}return 1.01*Ue}(u,this.pixelsPerMeter(u.center.lat,u.worldSize)),_=Li(u.zoom);if(_>0){const C=gLe(u,ch(1,u.center.lat)*u.worldSize),M=u.worldSize/(2*Math.PI),L=Math.max(u.width,u.height)/u.worldSize*Math.PI;return Jr(p,C+M*(1-Math.cos(L)),Math.pow(_,10))}return p}upVector(u,p,_){return Ln(p,_,u,1)}upVectorScale(u){return{metersToTile:Ps(An(Js(u)))}}}function jLe(y){const u=y.parallels,p=!!u&&Math.abs(u[0]+u[1])<.01;switch(y.name){case"mercator":return new vLe(y);case"equirectangular":return new V1t(y);case"naturalEarth":return new G1t(y);case"equalEarth":return new q1t(y);case"winkelTripel":return new W1t(y);case"albers":return p?new wLe(y):new U1t(y);case"lambertConformalConic":return p?new wLe(y):new H1t(y);case"globe":return new K1t(y)}throw new Error(`Invalid projection name: ${y.name}`)}class Y1t{constructor(u,p){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=p,this.appearances=u;const _=u.map(C=>function(M){if(!M.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const L=M.condition.expression;return{featureDependent:!q1(L),stateDependent:!Bf(L),zoomDependent:!Jx(L,["zoom"]),pitchDependent:!Jx(L,["pitch"]),brightnessDependent:!Jx(L,["brightness","measure-light"]),worldviewDependent:!Jx(L,["worldview"])}}(C));this.anyFeatureDependent=_.some(C=>C.featureDependent),this.anyStateDependent=_.some(C=>C.stateDependent)}update(u,p){const _=this.lastParams,C=!_||_.zoom!==u.zoom||_.pitch!==(u.pitch||0)||_.brightness!==(u.brightness||0)||_.worldview!==u.worldview;this.lastParams={zoom:u.zoom,pitch:u.pitch||0,brightness:u.brightness||0,worldview:u.worldview};const M=p&&this.anyStateDependent;if(!C&&!M&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!M){const L=this.evaluateAllFeatures(u);return L===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=L,{kind:"all-features",appearanceIndex:L})}return{kind:"per-feature"}}evaluateAllFeatures(u){for(let p=0;p{for(let C=0;CL-O),M=new Map;for(const L of C){const O=_.get(L);M.set(L,new Gi(O))}return p&&(this.cachedBatchIndices=C,this.cachedBatchSegments=M),{batchIndices:C,batchSegments:M}}snapshotSymbolVertexData(u,p){const _=u*vE;return this.layoutVertexArray.uint16.slice(_,_+p*vE)}restoreSymbolVertexData(u,p){this.layoutVertexArray.uint16.set(p,u*vE)}updateSymbolVertexData(u,p,_,C,M,L,O,U,W,J,se,re,fe){const xe=this.layoutVertexArray.uint16,we=u*vE;xe[we]=p,xe[we+1]=_,xe[we+2]=C,xe[we+3]=M,xe[we+4]=L,xe[we+5]=O,xe[we+6]=U,xe[we+7]=W,xe[we+8]=J,xe[we+9]=se,xe[we+10]=re,xe[we+11]=fe}upload(u,p,_,C,M,L){this.isEmpty()||(_&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Yvt.members,!!L),this.indexBuffer=u.createIndexBuffer(this.indexArray,p),this.dynamicLayoutVertexBuffer=u.createVertexBuffer(this.dynamicLayoutVertexArray,Xvt.members,!0),this.opacityVertexBuffer=u.createVertexBuffer(this.opacityVertexArray,X1t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=u.createVertexBuffer(this.iconTransitioningVertexArray,t1t.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,Zvt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||M)&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,Qvt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=u.createVertexBuffer(this.orientationVertexArray,e1t.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=u.createVertexBuffer(this.featureIdArray,Jvt.members,!1))),(_||C)&&(this.programConfigurations.upload(u),this.uboBinder&&this.uboBinder.upload(u)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}Mr(Z0e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class X0e{constructor(u,p,_){this.layoutVertexArray=new u,this.layoutAttributes=p,this.indexArray=new _,this.segments=new Gi,this.collisionVertexArray=new JT,this.collisionVertexArrayExt=new gy}upload(u){this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=u.createVertexBuffer(this.collisionVertexArray,s1t.members,!0),this.collisionVertexBufferExt=u.createVertexBuffer(this.collisionVertexArrayExt,r1t.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Mr(X0e,"CollisionBuffers");class lg{constructor(u){this.collisionBoxArray=u.collisionBoxArray,this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(L=>L.fqid),this.index=u.index,this.pixelRatio=u.pixelRatio,this.sourceLayerIndex=u.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=N([]),this.placementViewportMatrix=N([]);const p=this.layers[0]._unevaluatedLayout._values;this.worldview=u.worldview,this.localizable=u.localizable,this.maxUniformBufferBindings=u.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=u.maxUniformBlockSizeDwords,this.disableSymbolUBO=u.disableSymbolUBO,this.textSizeData=QN(this.zoom,p["text-size"],this.worldview,u.availableImages),this.iconSizeData=QN(this.zoom,p["icon-size"],this.worldview,u.availableImages);const _=this.layers[0].layout,C=_.get("symbol-sort-key"),M=_.get("symbol-z-order");this.lut=u.lut,this.canOverlap=_.get("text-allow-overlap")||_.get("icon-allow-overlap")||_.get("text-ignore-placement")||_.get("icon-ignore-placement"),this.sortFeaturesByKey=M!=="viewport-y"&&C.constantOr(1)!==void 0,this.sortFeaturesByY=(M==="viewport-y"||M==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=_.get("text-writing-mode").map(L=>rf[L]),this.stateDependentLayerIds=this.layers.filter(L=>L.isStateDependent()).map(L=>L.id),this.sourceID=u.sourceID,this.projection=u.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(u){const p=this.layers[0].getAppearances();if(!p||p.length===0)return!1;const _=Array.isArray(u)?u:[u];return p.some(C=>_.some(M=>C.hasLayoutProperty(M)))}getAppearanceFeatureData(u){return this.featureAppearanceData.get(u)}createArrays(){this.text=new Z0e(new Xm(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("text")||u.startsWith("symbol"))),this.icon=new Z0e(new Xm(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("icon")||u.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new M0e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new M0e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Z7,this.lineVertexArray=new Dp,this.symbolInstances=new k6}calculateGlyphDependencies(u,p,_,C,M){for(const L of u){const O=L.codePointAt(0);if(O===void 0)break;if(p[O]=!0,C&&M&&O<=65535){const U=rD[L];U&&(p[U.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(u,p,_,C,M,L,O){if(!u.hasLayoutProperty("icon-size"))return O*L;let U=1;const W=u.getUnevaluatedLayoutProperty("icon-size"),J=QN(this.zoom,W,this.worldview,M),se=pE(J,p);if(J.kind!=="constant"&&J.kind!=="camera"||(U=se.uSize),J.kind==="composite"){const{minZoom:re,maxZoom:fe}=J,xe=W.possiblyEvaluate(new fi(re,{worldview:this.worldview}),C),we=W.possiblyEvaluate(new fi(fe,{worldview:this.worldview}),C),je=xe.evaluate(_,{},C,M);U=je+(we.evaluate(_,{},C,M)-je)*se.uSizeT}return J.kind==="source"&&(U=W.possiblyEvaluate(new fi(this.zoom,{worldview:this.worldview}),C).evaluate(_,{},C,M)),U*L}updateFootprints(u,p){}updateReplacement(u,p){if(p.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=p.updateTime;const _=p.getReplacementRegionsForTile(u.toUnwrapped(),!0);return!k9(this.activeReplacements,_)&&(this.activeReplacements=_,!0)}getResolvedImageFromTokens(u){return typeof u=="string"?Au.build(u):u}populate(u,p,_,C){const M=this.layers[0],L=M.layout,O=this.projection.name==="globe",U=L.get("text-font"),W=L.get("text-field"),J=L.get("icon-image"),[se,re]=L.get("icon-size-scale-range"),fe=Mt(p.scaleFactor||1,se,re),[xe,we]=L.get("text-size-scale-range"),je=Mt(p.scaleFactor||1,xe,we),Be=(W.value.kind!=="constant"||W.value.value instanceof hu&&!W.value.value.isEmpty()||W.value.value.toString().length>0)&&(U.value.kind!=="constant"||U.value.value.length>0),Ye=J.value.kind!=="constant"||!!J.value.value||Object.keys(J.parameters).length>0,Ue=this.hasAnyAppearanceLayoutProperty("icon-image"),tt=L.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!Be&&!Ye&&!Ue)return;const ot=p.iconDependencies,pt=p.glyphDependencies,Rt=p.availableImages,_t=new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),Et=jt=>{const At=jt.id.toString();ot.has(At)?ot.get(At).push(jt):ot.set(At,[jt])};for(const jt of u){const{feature:At,id:ns,index:is,sourceLayerIndex:xs}=jt,ks=M._featureFilter.needGeometry,ws=Hf(At,ks);if(!M._featureFilter.filter(_t,ws,_))continue;if(ks||(ws.geometry=bm(At,_,C)),O&&At.type!==1&&_.z<=5){const Ds=ws.geometry,tr=.98078528056,sr=(wr,Ar)=>ye(Ln(wr.x,wr.y,_,1),Ln(Ar.x,Ar.y,_,1)){if(!Ds.getLayoutProperty("icon-image"))return;const tr=this.getCombinedIconPrimary(Ds,gs,ws,_,Rt,Hs,fe);tr&&Et(tr)}),Ks){const Ds=U.evaluate(ws,{},_).join(","),tr=L.get("text-rotation-alignment")==="map"&&L.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes(rf.vertical);for(const sr of Ks.sections)if(sr.image){const wr=sr.image.getPrimary().scaleSelf(this.pixelRatio*je),Ar=wr.id.toString(),tn=ot.get(Ar)||[];tn.push(wr),ot.set(Ar,tn)}else{const wr=n6(Ks.toString()),Ar=sr.fontStack||Ds,tn=pt[Ar]=pt[Ar]||{};this.calculateGlyphDependencies(sr.text,tn,tr,this.allowVerticalPlacement,wr)}}}if(L.get("symbol-placement")==="line"&&(this.features=function(jt){const At={},ns={},is=[];let xs=0;function ks(gs){is.push(jt[gs]),xs++}function ws(gs,Cs,Bs){const Hs=ns[gs];return delete ns[gs],ns[Cs]=Hs,is[Hs].geometry[0].pop(),is[Hs].geometry[0]=is[Hs].geometry[0].concat(Bs[0]),Hs}function Ks(gs,Cs,Bs){const Hs=At[Cs];return delete At[Cs],At[gs]=Hs,is[Hs].geometry[0].shift(),is[Hs].geometry[0]=Bs[0].concat(is[Hs].geometry[0]),Hs}function ds(gs,Cs,Bs){const Hs=Bs?Cs[0].at(-1):Cs[0][0];return`${gs}:${Hs.x}:${Hs.y}`}for(let gs=0;gsgs.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 jt of p.elevationFeatures)this.elevationFeatureIdToIndex.set(jt.id,this.elevationFeatures.length),this.elevationFeatures.push(jt)}}else L.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((jt,At)=>jt.sortKey-At.sortKey)}getCombinedIconPrimary(u,p,_,C,M,L,O){let U,W;if(u.hasLayoutProperty("icon-image")){const J=p.getAppearanceValueAndResolveTokens(u,"icon-image",_,C,M);U=this.getResolvedImageFromTokens(J)}else{const J=p.getValueAndResolveTokens("icon-image",_,C,M);U=this.getResolvedImageFromTokens(J)}if(U){const J=u.hasLayoutProperty("icon-size")?u.getUnevaluatedLayoutProperty("icon-size"):p._unevaluatedLayout._values["icon-size"];W=lD(U,QN(this.zoom,J,this.worldview,M),J,C,this.zoom,L,this.pixelRatio,O,this.worldview,M).iconPrimary}return W}updateSymbolInstanceIconVertices(u,p,_,C,M,L){const{canonical:O,availableImages:U,globalProperties:W,layer:J,iconScaleFactor:se,featureState:re,layoutIconOffset:fe,layoutIconSize:xe,layoutIconRotate:we}=L;if(u.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(p.activeAppearanceIndex===_)return{vertexOffsetDelta:u.numIconVertices,hasChanges:!1};const je=_>=0?J.appearances[_]:null;if(je){const Be=this.getCombinedIconPrimary(je,J,C,O,U,{sortKey:void 0,text:void 0,icon:null,index:u.featureIndex,sourceLayerIndex:u.featureIndex,geometry:[],properties:p.properties,type:"Point",id:p.id},se);if(!Be)return{vertexOffsetDelta:0,hasChanges:!1};const Ye=Be.toString(),Ue=this.iconAtlasPositions&&this.iconAtlasPositions.get(Ye);if(Ue){const{appearanceIconOffset:tt,appearanceIconRotate:ot}=dLe(je,J,C,O,fe,we,xe,se);let pt=K9(Ue,void 0,tt,J.layout.get("icon-anchor").evaluate(C,re,O));const Rt=Ue.sdf,_t=J.layout.get("icon-text-fit").constantOr("none");_t!=="none"&&p.textShaping&&p.iconTextFitPadding&&p.fontScale&&(pt=R0e(pt,p.textShaping,_t,p.iconTextFitPadding,tt,p.fontScale));const Et=this.calculateEffectiveAppearanceIconSize(je,W.zoom,C,O,U,se,xe),jt=0,At=1+(Math.min(JN,Math.round(Et*ob))<<1),ns=V0e(pt,ot,Rt,_t!=="none",se);p.isUsingAppearanceIconVertexData||(p.isUsingAppearanceIconVertexData=!0,p.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(M,u.numIconVertices));const is=Math.floor(u.numIconVertices/4),xs=Math.min(ns.length,is);let ks=M;for(let Ks=0;Ks0||u.numVerticalGlyphVertices>0;if(!tt)return{vertexOffsetDelta:tt?u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices:0,hasChanges:!1};if(p.activeAppearanceIndex===_)return{vertexOffsetDelta:u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices,hasChanges:!1};const ot=_>=0?U.appearances[_]:null;if(ot&&p.textShaping){const{appearanceTextOffset:pt,appearanceTextRotate:Rt,appearanceTextSize:_t}=uLe(ot,U,C,O,re,xe,fe);p.fontScale=pLe(_t,p.textScaleFactor);const Et=ot.getUnevaluatedLayoutProperty("text-size");let jt=this.textSizeData,At=Be,ns=Ye;ot.hasLayoutProperty("text-size")&&(jt=QN(this.zoom,Et,this.worldview,Ue),At=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,ns=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const is=p.textShaping.bottom-re[1],xs=p.textShaping.left-re[0],ks=p.textShaping.right-re[0];p.textShaping.top=pt[1]+(p.textShaping.top-re[1]),p.textShaping.bottom=pt[1]+is,p.textShaping.left=pt[0]+xs,p.textShaping.right=pt[0]+ks;const ws=lLe(0,p.textShaping,pt,U,!1,C,J,this.allowVerticalPlacement,Rt),Ks=_t&&jt.kind==="composite"?Et.possiblyEvaluate(new fi(At,{}),O).evaluate(C,se,O):we,ds=_t&&jt.kind==="composite"?Et.possiblyEvaluate(new fi(ns,{}),O).evaluate(C,se,O):je,gs=K0e(ot.name,jt,_t,W,Ks,ds),Cs=Array.isArray(gs)?gs[1]:_t,Bs=0,Hs=1+(Math.min(JN,Math.round(Cs*ob))<<1);p.isUsingAppearanceTextVertexData||(p.isUsingAppearanceTextVertexData=!0,p.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(M,u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices));for(let cr=0;cr0){const W=new Set(Object.keys(u).map(J=>{const se=Number(J);return!isNaN(se)&&Number.isSafeInteger(se)&&String(se)===J?se:J}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(W,M[0],p,U,_,u,O),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(W,M[0],p,U,_,u,O)}}}updateRoadElevation(u){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let p=!1;const _=Jm(u),C=1/_;let M=!1,L=!1;for(let O=0;O0||re>0,je=fe>0,Be=this.elevationFeatures[U.elevationFeatureIndex];if(Be){const Ye=new us(U.tileAnchorX,U.tileAnchorY),Ue=.075+Be.pointElevation(Ye);U.zOffset!==Ue&&(p=!0,U.zOffset=Ue),Ue!==0&&(this.hasAnyZOffset=!0);const tt=Be.computeSlopeNormal(Ye,C),ot=yt(Ie(),ae(0,0,1),tt);Qe(W,W,ot),Qe(J,J,ot),W[2]*=_,J[2]*=_,W[0]===1&&W[1]===0&&W[2]===0&&J[0]===0&&J[1]===1&&J[2]===0||(M=M||we,L=L||je)}if(we&&(a$(this.text.orientationVertexArray,se,W,J),a$(this.text.orientationVertexArray,re,W,J)),je){const{placedIconSymbolIndex:Ye,verticalPlacedIconSymbolIndex:Ue}=U;Ye>=0&&a$(this.icon.orientationVertexArray,fe,W,J),Ue>=0&&a$(this.icon.orientationVertexArray,xe,W,J)}}M||(this.text.orientationVertexArray=void 0),L||(this.icon.orientationVertexArray=void 0),p&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const u=(M,L,O)=>{_+=L,_>M.length&&M.resize(_);for(let U=-L;U<0;U++)M.emplace(U+_,O)},p=(M,L,O)=>{C+=L,C>M.length&&M.resize(C);for(let U=-L;U<0;U++)M.emplace(U+C,O)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let _=0,C=0;for(let M=0;M0;if((O>0||U>0)&&(u(this.text.zOffsetVertexArray,O,J),u(this.text.zOffsetVertexArray,U,J)),se){const{placedIconSymbolIndex:re,verticalPlacedIconSymbolIndex:fe}=L;re>=0&&p(this.icon.zOffsetVertexArray,W,J),fe>=0&&p(this.icon.zOffsetVertexArray,L.numVerticalIconVertices,J)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(u,p,_,C,M){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(u),this.iconCollisionBox.upload(u)),this.text.upload(u,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(L=>L.appearances&&L.appearances.length>0)),this.icon.upload(u,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(u,p,_,C,M,L=!1){const O={hasLayoutChanges:!1,hasUboChanges:!1};if(!u||!_||!this.featureAppearanceData)return O;const U=p||{},W=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,J=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!W&&!J)return O;const se=this.layers[0],re=se.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===se.appearancesVersion||(this.featureAppearances=new Y1t(se.appearances,se.appearancesVersion));const fe=this.featureAppearances.update(C,L);if(fe.kind==="no-changes")return O;let xe=1,we=0,je=!1,Be=!1;if(W){const[pt,Rt]=re.get("icon-size-scale-range");xe=Mt(1,pt,Rt)}let Ye=1,Ue=0,tt=!1;if(J){const[pt,Rt]=re.get("text-size-scale-range");Ye=Mt(1,pt,Rt)}const ot=new Map;if(M&&_)for(const pt of _){const Rt=M.getImage(pt,se.scope);if(Rt){const _t=new Of(pt.toString());ot.set(_t.toString(),Rt)}}for(let pt=0;ptks.isActive({globals:C,feature:At,canonical:u,featureState:jt})):-1;ns=xs>=0?xs:-1}const is=_t.activeAppearanceIndex!==ns;if(J){const xs=re.get("text-size"),ks=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,ws=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Ks={canonical:u,layer:se,featureState:jt,availableImages:_,textScaleFactor:Ye,imageMap:ot,layoutTextOffset:re.get("text-offset").evaluate(At,jt,u).map(gs=>gs*Oc),layoutTextSize:xs.evaluate(At,jt,u),layoutTextRotate:re.get("text-rotate").evaluate(At,jt,u),layoutMinZoomSize:xs.evaluate(At,{zoom:ks},u),layoutMaxZoomSize:xs.evaluate(At,{zoom:ws},u),layoutTextSizeMinZoom:ks,layoutTextSizeMaxZoom:ws},ds=this.updateSymbolInstanceTextVertices(Rt,_t,ns,At,Ue,Ks);Ue+=ds.vertexOffsetDelta,tt=tt||ds.hasChanges}if(W){const xs={canonical:u,layer:se,featureState:jt,availableImages:_,globalProperties:C,iconScaleFactor:xe,layoutIconOffset:re.get("icon-offset").evaluate(At,jt,u),layoutIconSize:re.get("icon-size").evaluate(At,jt,u,_),layoutIconRotate:re.get("icon-rotate").evaluate(At,jt,u)},ks=this.updateSymbolInstanceIconVertices(Rt,_t,ns,At,we,xs);we+=ks.vertexOffsetDelta,je=je||ks.hasChanges}if(is){const xs=Rt.featureIndex,ks=C?C.brightness:null,ws=jt||{},Ks=ns>=0?se.appearances[ns]:null;this.text.uboBinder&&(this.text.uboBinder.layer=se,Be=this.text.uboBinder.updateFeaturePaintForAppearance(xs,At,ws,u,_,ks,Ks)||Be),this.icon.uboBinder&&(this.icon.uboBinder.layer=se,Be=this.icon.uboBinder.updateFeaturePaintForAppearance(xs,At,ws,u,_,ks,Ks)||Be)}_t.activeAppearanceIndex=ns}return je&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),tt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:je||tt,hasUboChanges:Be}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=jLe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(u,p){const _=this.lineVertexArray.length;if(u.segment!==void 0)for(const{x:C,y:M}of p)this.lineVertexArray.emplaceBack(C,M);return{lineStartIndex:_,lineLength:this.lineVertexArray.length-_}}addSymbols(u,p,_,C,M,L,O,U,W,J,se,re,fe,xe,we,je,Be,Ye){const Ue=u.indexArray,tt=u.layoutVertexArray,ot=u.globeExtVertexArray,pt=Ye,Rt=u.uboBinder?u.uboBinder.getCurrentBatchIndex():void 0,_t=u.segments.prepareSegment(4*pt,tt,Ue,this.canOverlap?L.sortKey:void 0,Rt),Et=this.glyphOffsetArray.length,jt=_t.vertexLength,At=this.allowVerticalPlacement&&O===rf.vertical?Math.PI/2:0,ns=L.text&&L.text.sections;let is=tt.length,xs=-1;for(let Ks=0;Ks=0)){const Ks=4*ks;for(let ds=0;ds=0?p.rightJustifiedTextSymbolIndex:p.centerJustifiedTextSymbolIndex>=0?p.centerJustifiedTextSymbolIndex:p.leftJustifiedTextSymbolIndex>=0?p.leftJustifiedTextSymbolIndex:p.verticalPlacedTextSymbolIndex>=0?p.verticalPlacedTextSymbolIndex:C),L=O0e(this.textSizeData,u,M)/Oc;return this.tilePixelRatio*L}getSymbolInstanceIconSize(u,p,_){const C=this.icon.placedSymbolArray.get(_),M=O0e(this.iconSizeData,u,C);return this.tilePixelRatio*M}_commitDebugCollisionVertexUpdate(u,p,_,C){u.emplaceBack(p,-_,-_,C),u.emplaceBack(p,_,-_,C),u.emplaceBack(p,_,_,C),u.emplaceBack(p,-_,_,C)}_updateTextDebugCollisionBoxes(u,p,_,C,M,L,O){for(let U=C;U0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(u,p){const _=u.placedSymbolArray.get(p),C=_.vertexStartIndex+4*_.numGlyphs;for(let M=_.vertexStartIndex;MC[O]-C[U]||M[U]-M[O]),L}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let u=0;uthis.symbolInstances.get(p).zOffset-this.symbolInstances.get(u).zOffset)}addToSortKeyRanges(u,p){const _=this.sortKeyRanges.at(-1);_&&_.sortKey===p?_.symbolInstanceEnd=u+1:this.sortKeyRanges.push({sortKey:p,symbolInstanceStart:u,symbolInstanceEnd:u+1})}sortFeatures(u){if(this.sortFeaturesByY&&this.sortedAngle!==u)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(u),this.sortedAngle=u,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const p of this.symbolInstanceIndexes){const _=this.symbolInstances.get(p);this.featureSortOrder.push(_.featureIndex);const{rightJustifiedTextSymbolIndex:C,centerJustifiedTextSymbolIndex:M,leftJustifiedTextSymbolIndex:L,verticalPlacedTextSymbolIndex:O,placedIconSymbolIndex:U,verticalPlacedIconSymbolIndex:W}=_;C>=0&&this.addIndicesForPlacedSymbol(this.text,C),M>=0&&M!==C&&this.addIndicesForPlacedSymbol(this.text,M),L>=0&&L!==M&&L!==C&&this.addIndicesForPlacedSymbol(this.text,L),O>=0&&this.addIndicesForPlacedSymbol(this.text,O),U>=0&&this.addIndicesForPlacedSymbol(this.icon,U),W>=0&&this.addIndicesForPlacedSymbol(this.icon,W)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(u,p){const _=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const C of this.symbolsByBatch.values())for(const M of C){const L=this.symbolInstances.get(M.index);M.rotatedY=0|Math.round(u*L.tileAnchorX+p*L.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let C=0;CM.rotatedY-L.rotatedY||L.featureIndex-M.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(u,p){for(const _ of u){const C=_.batchIndex;if(C===void 0)continue;const M=p.get(C);if(!M){_.primitiveOffset=this.text.indexArray.length,_.primitiveLength=0;continue}_.primitiveOffset=this.text.indexArray.length;const L=this.text.indexArray.length;for(const{index:O}of M){const U=this.symbolInstances.get(O),{rightJustifiedTextSymbolIndex:W,centerJustifiedTextSymbolIndex:J,leftJustifiedTextSymbolIndex:se,verticalPlacedTextSymbolIndex:re}=U;W>=0&&this.addIndicesForPlacedSymbol(this.text,W),J>=0&&J!==W&&this.addIndicesForPlacedSymbol(this.text,J),se>=0&&se!==J&&se!==W&&this.addIndicesForPlacedSymbol(this.text,se),re>=0&&this.addIndicesForPlacedSymbol(this.text,re)}_.primitiveLength=this.text.indexArray.length-L}}rebuildIconSegmentIndices(u,p){for(const _ of u){const C=_.batchIndex;if(C===void 0)continue;const M=p.get(C);if(!M){_.primitiveOffset=this.icon.indexArray.length,_.primitiveLength=0;continue}_.primitiveOffset=this.icon.indexArray.length;const L=this.icon.indexArray.length;for(const{index:O}of M){const U=this.symbolInstances.get(O),{placedIconSymbolIndex:W,verticalPlacedIconSymbolIndex:J}=U;W>=0&&this.addIndicesForPlacedSymbol(this.icon,W),J>=0&&this.addIndicesForPlacedSymbol(this.icon,J)}_.primitiveLength=this.icon.indexArray.length-L}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const u=Math.sin(this.sortedAngle),p=Math.cos(this.sortedAngle),_=this.getOrCreateSortedSymbolsByBatch(u,p),C=Array.from(_.keys()).sort((M,L)=>M-L);for(const M of C){const L=_.get(M);for(const{index:O}of L){const U=this.symbolInstances.get(O);this.featureSortOrder.push(U.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),_),this.rebuildIconSegmentIndices(this.icon.segments.get(),_),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(u){const p=this.symbolInstances.get(this.text.symbolInstanceIndices[u]).elevationFeatureIndex;let _;return this.elevationFeatures&&p_ in y?String(y[_]):"")}let kLe,SLe,Q0e;Mr(lg,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),lg.addDynamicAttributes=yE;class CLe{constructor(u){this.type=u.property.overrides?u.property.overrides.runtimeType:E0,this.defaultValue=u}evaluate(u){if(u.formattedSection){const p=this.defaultValue.property.overrides;if(p&&p.hasOverride(u.formattedSection))return p.getOverride(u.formattedSection)}return u.feature&&u.featureState?this.defaultValue.evaluate(u.feature,u.featureState):this.defaultValue.property.specification.default}eachChild(u){this.defaultValue.isConstant()||u(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Mr(CLe,"FormatSectionOverride",{omit:["defaultValue"]});const J0e=()=>Q0e||(Q0e={layout:kLe||(kLe=new ko({"symbol-placement":new rr(Yt.layout_symbol["symbol-placement"]),"symbol-spacing":new rr(Yt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new rr(Yt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new lr(Yt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new rr(Yt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new rr(Yt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new rr(Yt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new rr(Yt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new rr(Yt.layout_symbol["icon-ignore-placement"]),"icon-optional":new rr(Yt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new rr(Yt.layout_symbol["icon-rotation-alignment"]),"icon-size":new lr(Yt.layout_symbol["icon-size"]),"icon-size-scale-range":new rr(Yt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new lr(Yt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new lr(Yt.layout_symbol["icon-text-fit-padding"]),"icon-image":new lr(Yt.layout_symbol["icon-image"]),"icon-image-use-theme":new rr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new lr(Yt.layout_symbol["icon-rotate"]),"icon-padding":new rr(Yt.layout_symbol["icon-padding"]),"icon-keep-upright":new rr(Yt.layout_symbol["icon-keep-upright"]),"icon-offset":new lr(Yt.layout_symbol["icon-offset"]),"icon-anchor":new lr(Yt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new rr(Yt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new rr(Yt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new rr(Yt.layout_symbol["text-rotation-alignment"]),"text-field":new lr(Yt.layout_symbol["text-field"]),"text-font":new lr(Yt.layout_symbol["text-font"]),"text-size":new lr(Yt.layout_symbol["text-size"]),"text-size-scale-range":new rr(Yt.layout_symbol["text-size-scale-range"]),"text-max-width":new lr(Yt.layout_symbol["text-max-width"]),"text-line-height":new lr(Yt.layout_symbol["text-line-height"]),"text-letter-spacing":new lr(Yt.layout_symbol["text-letter-spacing"]),"text-justify":new lr(Yt.layout_symbol["text-justify"]),"text-radial-offset":new lr(Yt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new rr(Yt.layout_symbol["text-variable-anchor"]),"text-anchor":new lr(Yt.layout_symbol["text-anchor"]),"text-max-angle":new rr(Yt.layout_symbol["text-max-angle"]),"text-writing-mode":new rr(Yt.layout_symbol["text-writing-mode"]),"text-rotate":new lr(Yt.layout_symbol["text-rotate"]),"text-padding":new rr(Yt.layout_symbol["text-padding"]),"text-keep-upright":new rr(Yt.layout_symbol["text-keep-upright"]),"text-transform":new lr(Yt.layout_symbol["text-transform"]),"text-offset":new lr(Yt.layout_symbol["text-offset"]),"text-allow-overlap":new rr(Yt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new rr(Yt.layout_symbol["text-ignore-placement"]),"text-optional":new rr(Yt.layout_symbol["text-optional"]),visibility:new rr(Yt.layout_symbol.visibility)})),paint:SLe||(SLe=new ko({"icon-opacity":new lr(Yt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new lr(Yt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new lr(Yt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new lr(Yt.paint_symbol["text-emissive-strength"]),"icon-color":new lr(Yt.paint_symbol["icon-color"]),"icon-halo-color":new lr(Yt.paint_symbol["icon-halo-color"]),"icon-halo-width":new lr(Yt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new lr(Yt.paint_symbol["icon-halo-blur"]),"icon-translate":new rr(Yt.paint_symbol["icon-translate"]),"icon-translate-anchor":new rr(Yt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new rr(Yt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new lr(Yt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new lr(Yt.paint_symbol["text-occlusion-opacity"]),"text-color":new lr(Yt.paint_symbol["text-color"],{runtimeType:ah,getOverride:y=>y.textColor,hasOverride:y=>!!y.textColor}),"text-halo-color":new lr(Yt.paint_symbol["text-halo-color"]),"text-halo-width":new lr(Yt.paint_symbol["text-halo-width"]),"text-halo-blur":new lr(Yt.paint_symbol["text-halo-blur"]),"text-translate":new rr(Yt.paint_symbol["text-translate"]),"text-translate-anchor":new rr(Yt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new rr(Yt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new rr(Yt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new rr(Yt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new rr(Yt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new lr(Yt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},Q0e);class i$ extends lh{constructor(u,p,_,C){super(u,J0e(),p,_,C,u.layout?u.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=N([]),this.hasOcclusionOpacityProperties=u.paint!==void 0&&("icon-occlusion-opacity"in u.paint||"text-occlusion-opacity"in u.paint)}_handleSpecialPaintPropertyUpdate(u){u!=="icon-occlusion-opacity"&&u!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(u,p){super.recalculate(u,p),this.appearances&&this.appearances.forEach(C=>{C.recalculate(u,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 _=this.layout.get("text-writing-mode");if(_){const C=[];for(const M of _)C.includes(M)||C.push(M);this.layout._values["text-writing-mode"]=C}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(u,p,_,C){return this._saturation===u&&this._contrast===p&&this._brightnessMin===_&&this._brightnessMax===C||(this._colorAdjustmentMatrix=function(M,L,O,U){M=uo(M),L=Jn(L);const W=j(),J=M/3,se=1-2*J,re=[se,J,J,0,J,se,J,0,J,J,se,0,0,0,0,1],fe=.5-.5*L,xe=U-O;return T(W,[xe,0,0,0,0,xe,0,0,0,0,xe,0,O,O,O,1],[L,0,0,0,0,L,0,0,0,0,L,0,fe,fe,fe,1]),T(W,W,re),W}(u,p,_,C),this._saturation=u,this._contrast=p,this._brightnessMin=_,this._brightnessMax=C),this._colorAdjustmentMatrix}getValueAndResolveTokens(u,p,_,C){const M=this.layout.get(u).evaluate(p,{},_,C),L=this._unevaluatedLayout._values[u];return L.isDataDriven()||PT(L.value)||!M?M:NLe(p.properties,M)}getAppearanceValueAndResolveTokens(u,p,_,C,M){const L=u.getLayoutProperty(p);if(!L)return;const O=L.evaluate(_,{},C,M),U=u.getUnevaluatedLayoutProperties()._values[p];return U.isDataDriven()||PT(U.value)||!O||typeof O!="string"?O:NLe(_.properties,O)}createBucket(u){return new lg(u)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const u of J0e().paint.overridableProperties){if(!i$.hasPaintOverride(this.layout,u))continue;const p=this.paint.get(u),_=new CLe(p),C=new KL(_,p.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let M=null;M=p.value.kind==="constant"||p.value.kind==="source"?new MN("source",C):new eg("composite",C,p.value.zoomStops,p.value.interpolationType),this.paint._values[u]=new O0(p.property,M,p.parameters)}}_handleOverridablePaintPropertyUpdate(u,p,_){return!(!this.layout||p.isDataDriven()||_.isDataDriven())&&i$.hasPaintOverride(this.layout,u)}static hasPaintOverride(u,p){const _=u.get("text-field"),C=J0e().paint.properties[p];let M=!1;const L=O=>{for(const U of O)if(C.overrides&&C.overrides.hasOverride(U))return void(M=!0)};if(_.value.kind==="constant"&&_.value.value instanceof hu)L(_.value.value.sections);else if(_.value.kind==="source"){const O=W=>{M||(W instanceof Ap&&Rl(W.value)===q_?L(W.value.sections):W instanceof W_?L(W.sections):W.eachChild(O))},U=_.value;U._styleExpression&&O(U._styleExpression.expression)}return M}getProgramIds(){return["symbol"]}getDefaultProgramParams(u,p,_){return{config:new eb(this,{zoom:p,lut:_}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let TLe,ELe,ALe,MLe;var o$=fa([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function l$(y,u,p,_,C,M,L,O){const U=[y,u,1,p,_,1,C,M,1],W=[L,O,1],J=g([],U),[se,re,fe]=Re(W,W,J);return v(U,U,[se,0,0,0,re,0,0,0,fe])}function ILe(y,u,p,_,C,M,L,O){const U=function(W,J,se,re,fe,xe,we,je){const Be=l$(0,0,1,0,1,1,0,1),Ye=l$(W,J,se,re,fe,xe,we,je);return v(Ye,Ye,g([],Be))}(y,u,p,_,C,M,L,O);return[U[2]/U[8]/mr,U[5]/U[8]/mr]}function c$(y){return[y[0],Math.min(Math.max(y[1],-85.051129),vm)]}class PLe extends Aa{constructor(u,p,_,C){super(),this.id=u,this.dispatcher=_,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(C),this.options=p,this._dirty=!1}load(u,p){if(this._loaded=p||!1,this.fire(new Gs("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return u&&(this.coordinates=u),this._loaded=!0,void this._finishLoading();this._imageRequest=dN(this.map._requestManager.transformRequest(this.url,kp.Image),(_,C)=>{this._imageRequest=null,this._loaded=!0,_?this.fire(new hr(_)):C&&(this.image=C,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,u&&(this.coordinates=u),this._finishLoading())})}loaded(){return this._loaded}updateImage(u){return u.url?(this._imageRequest&&u.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=u.url,this.load(u.coordinates,this._loaded),this):this}setTexture(u){if(!(u.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new eD(this.map.painter.context,u.handle),this.width=u.dimensions[0],this.height=u.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Gs("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(u){this.map=u,this.load()}onRemove(u){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof eD||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(u){if(this.coordinates=u,this._boundsArray=void 0,this._unsupportedCoords=!1,!u.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let p=u[0][1],_=u[0][1];for(const M of u)M[1]>_&&(_=M[1]),M[1]vm?this.onNorthPole=!0:C<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const M=u.map(fu.fromLngLat);this.tileID=function(L){let O=1/0,U=1/0,W=-1/0,J=-1/0;for(const we of L)O=Math.min(O,we.x),U=Math.min(U,we.y),W=Math.max(W,we.x),J=Math.max(J,we.y);const se=Math.max(W-O,J-U),re=Math.max(0,Math.floor(-Math.log2(se))),fe=Math.pow(2,re);let xe=Math.floor((O+W)/2*fe);return xe>1&&(xe-=1),new qt(re,xe,Math.floor((U+J)/2*fe))}(M),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Gs("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof eD||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(u){for(const je in this.tiles){const Be=this.tiles[je];Be.state!=="loaded"&&(Be.state="loaded",Be.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const p=ek(new qt(0,0,0),this.map.transform.projection),_=[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(je){const Be=je[1].x-je[0].x,Ye=je[1].y-je[0].y,Ue=je[2].x-je[1].x,tt=je[2].y-je[1].y,ot=je[3].x-je[2].x,pt=je[3].y-je[2].y,Rt=je[0].x-je[3].x,_t=je[0].y-je[3].y,Et=Be*tt-Ue*Ye,jt=Ue*pt-ot*tt,At=ot*_t-Rt*pt,ns=Rt*Ye-Be*_t;return Et>0&&jt>0&&At>0&&ns>0||Et<0&&jt<0&&At<0&&ns<0}(_))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const C=ek(this.tileID,this.map.transform.projection),[M,L,O,U]=this.coordinates.map(je=>{const Be=C.projection.project(je[0],je[1]);return yLe(C,Be)._round()});this.perspectiveTransform=ILe(M.x,M.y,L.x,L.y,O.x,O.y,U.x,U.y);const W=this._boundsArray=new Y1;W.emplaceBack(M.x,M.y,0,0),W.emplaceBack(L.x,L.y,mr,0),W.emplaceBack(U.x,U.y,0,mr),W.emplaceBack(O.x,O.y,mr,mr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=u.createVertexBuffer(W,o$.members),this.boundsSegments=Gi.simpleSegment(0,0,4,2);const J=[],se=function(je){return[c$(je[0]),c$(je[1]),c$(je[2]),c$(je[3])]}(this.coordinates),[re,fe,xe,we]=function(je){let Be=je[0][0],Ye=Be,Ue=je[0][1],tt=Ue;for(let ot=1;otYe&&(Ye=je[ot][0]),je[ot][1]tt&&(tt=je[ot][1]);return[Be,Ue,Ye-Be,tt-Ue]}(se);{const je=new Y1,[Be,Ye,Ue,tt]=function(ws){let Ks=ws[0].x,ds=Ks,gs=ws[0].y,Cs=gs;for(let Bs=1;Bsds&&(ds=ws[Bs].x),ws[Bs].yCs&&(Cs=ws[Bs].y);return[Ks,gs,ds-Ks,Cs-gs]}(_),ot=ws=>[(ws.x-Be)/Ue,(ws.y-Ye)/tt],[pt,Rt,_t,Et]=_.map(ot),jt=function(ws,Ks,ds,gs,Cs,Bs,Hs,cr){const Ds=l$(0,0,1,0,1,1,0,1);return v(Ds,Ds,g([],l$(ws,Ks,ds,gs,Cs,Bs,Hs,cr)))}(pt[0],pt[1],Rt[0],Rt[1],_t[0],_t[1],Et[0],Et[1]);this.elevatedGlobePerspectiveTransform=ILe(pt[0],pt[1],Rt[0],Rt[1],_t[0],_t[1],Et[0],Et[1]);const At=(ws,Ks)=>{J.push(ws.lng);const ds=Math.round((ws.lng-re)/xe*mr),gs=Math.round((ws.lat-fe)/we*mr),Cs=ot(Ks),Bs=Re([],[Cs[0],Cs[1],1],jt),Hs=Math.round(Bs[0]/Bs[2]*mr),cr=Math.round(Bs[1]/Bs[2]*mr);je.emplaceBack(ds,gs,Hs,cr)},ns=_[3].x-_[0].x,is=_[3].y-_[0].y,xs=_[2].x-_[1].x,ks=_[2].y-_[1].y;for(let ws=0;ws<65;ws++){const Ks=ws/64,ds=[_[0].x+Ks*ns,_[0].y+Ks*is],gs=[_[1].x+Ks*xs,_[1].y+Ks*ks],Cs=gs[0]-ds[0],Bs=gs[1]-ds[1];for(let Hs=0;Hs<65;Hs++){const cr=Hs/64,Ds={x:ds[0]+Cs*cr,y:ds[1]+Bs*cr};At(p.projection.unproject(Ds.x,Ds.y),Ds)}}this.elevatedGlobeVertexBuffer=u.createVertexBuffer(je,o$.members)}{this.maxLongitudeTriangleSize=0;let je=[],Be=new Go;const Ye=(Ue,tt,ot)=>{Be.emplaceBack(Ue,tt,ot);const pt=J[Ue],Rt=J[tt],_t=J[ot],Et=Math.min(Math.min(pt,Rt),_t),jt=Math.max(Math.max(pt,Rt),_t)-Et;jt>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=jt),je.push(Et+jt/2)};for(let Ue=0;Ue<64;Ue++)for(let tt=0;tt<64;tt++){const ot=65*Ue+tt,pt=ot+1,Rt=ot+65,_t=Rt+1;Ye(ot,Rt,pt),Ye(pt,Rt,_t)}[je,Be]=function(Ue,tt){const ot=Array.from({length:Ue.length},(_t,Et)=>Et);ot.sort((_t,Et)=>Ue[_t]-Ue[Et]);const pt=[],Rt=new Go;for(let _t=0;_t{L.segments.push({vertexOffset:0,primitiveOffset:se,vertexLength:p.segments[0].vertexLength,primitiveLength:re,sortKey:void 0,vaos:{}})},U=.51*this.maxLongitudeTriangleSize;if(Math.abs(_[0]-C)<=U){const se=dr(_,0,_.length,C+U);return se===_.length||O(se,rc(_,se+1,_.length,C+360-U)-se),L}C<_[0]&&(C+=360);const W=rc(_,0,_.length,C-U);if(W===_.length)return O(0,_.length),L;O(0,W-0);const J=dr(_,W+1,_.length,C+U);return J!==_.length&&O(J,_.length-J),L}}const eve=1024,J1t=(Math.pow(eve,2)-1)/268170240;class LLe extends lh{constructor(u,p,_,C){super(u,{layout:ALe||(ALe=new ko({visibility:new rr(Yt.layout_raster.visibility)})),paint:MLe||(MLe=new ko({"raster-opacity":new rr(Yt.paint_raster["raster-opacity"]),"raster-color":new F0(Yt.paint_raster["raster-color"]),"raster-color-mix":new rr(Yt.paint_raster["raster-color-mix"]),"raster-color-range":new rr(Yt.paint_raster["raster-color-range"]),"raster-hue-rotate":new rr(Yt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new rr(Yt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new rr(Yt.paint_raster["raster-brightness-max"]),"raster-saturation":new rr(Yt.paint_raster["raster-saturation"]),"raster-contrast":new rr(Yt.paint_raster["raster-contrast"]),"raster-resampling":new rr(Yt.paint_raster["raster-resampling"]),"raster-fade-duration":new rr(Yt.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new rr(Yt.paint_raster["raster-emissive-strength"]),"raster-array-band":new rr(Yt.paint_raster["raster-array-band"]),"raster-elevation":new rr(Yt.paint_raster["raster-elevation"]),"raster-elevation-reference":new rr(Yt.paint_raster["raster-elevation-reference"]),"raster-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this.updateColorRamp(),this._curRampRange=[NaN,NaN]}getProgramIds(){return["raster"]}hasColorMap(){return!!this._transitionablePaint._values["raster-color"].value.value}tileCoverLift(){return this.paint.get("raster-elevation")}isDraped(u){return!(u&&u._source instanceof PLe&&(u._source.onNorthPole||u._source.onSouthPole))&&this.paint.get("raster-elevation")===0}_handleSpecialPaintPropertyUpdate(u){u!=="raster-color"&&u!=="raster-color-range"||(this._curRampRange=[NaN,NaN],this.updateColorRamp())}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}updateColorRamp(u){if(!this.hasColorMap()||!this._curRampRange)return;const p=this._transitionablePaint._values["raster-color"].value.expression,[_,C]=u||this._transitionablePaint._values["raster-color-range"].value.expression.evaluate({zoom:0})||[NaN,NaN];isNaN(_)&&isNaN(C)||_===this._curRampRange[0]&&C===this._curRampRange[1]||(this.colorRamp=pi({expression:p,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:_,end:C}],resolution:eve}),this.colorRampTexture=null,this._curRampRange=[_,C])}is3D(u){return this.paint.get("raster-elevation")>0}}let DLe,RLe,OLe,FLe,BLe,zLe,$Le;class ULe extends lh{constructor(u,p,_,C){super(u,{layout:DLe||(DLe=new ko({visibility:new rr(Yt["layout_raster-particle"].visibility)})),paint:RLe||(RLe=new ko({"raster-particle-array-band":new rr(Yt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new rr(Yt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new F0(Yt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new rr(Yt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new rr(Yt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new rr(Yt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new rr(Yt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new rr(Yt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._updateColorRamp(),this.lastInvalidatedAt=bd.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(u){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(u){return!1}_handleSpecialPaintPropertyUpdate(u){u!=="raster-particle-color"&&u!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),u==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const u=this._transitionablePaint._values["raster-particle-color"].value.expression,p=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=pi({expression:u,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:p}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=bd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class ebt extends lh{constructor(u,p){super(u,{},p,null),this.implementation=u,u.slot&&(this.slot=u.slot)}is3D(u){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(u){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(u){this.implementation.onAdd&&this.implementation.onAdd(u,u.painter.context.gl)}onRemove(u){this.implementation.onRemove&&this.implementation.onRemove(u,u.painter.context.gl)}}function tve(y,u,p){const _=[0,0,1],C=et([]);return Jt(C,C,p?-We(y)+Math.PI:We(y)),Dt(C,C,-We(u)),Qe(_,_,C),Te(_,_)}class qLe{constructor(u,p){this.feature=u,this.instancedDataOffset=p,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class VLe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new eE,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(u){const p=16*u,_=this.instancedDataArray.float32;let C=Math.floor(_[p+2]);const M=1.05*(_[p+2]-C);return C/=100,[_[p]%1*1.05,_[p+1]%1*1.05,M,C]}tileCoordinatesForInstance(u){const p=16*u,_=this.instancedDataArray.float32;let C=_[p+0];return C=C>mr?C-mr:C,new us(Math.trunc(C),Math.trunc(_[p+1]))}translationForInstance(u){const p=16*u,_=this.instancedDataArray.float32;return[_[p+4],_[p+5],_[p+6]]}rotationScaleForInstance(u){const p=16*u,_=this.instancedDataArray.float32;return[_[p+7],_[p+8],_[p+9],_[p+10],_[p+11],_[p+12],_[p+13],_[p+14],_[p+15]]}transformForInstance(u){const p=16*u,_=this.instancedDataArray.float32;return[_[p+7],_[p+8],_[p+9],_[p+4],_[p+10],_[p+11],_[p+12],_[p+5],_[p+13],_[p+14],_[p+15],_[p+6],0,0,0,1]}}class sve{constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaledZ=this.canonical.z+Math.log2(u.overscaling),this.layers=u.layers,this.layerIds=this.layers.map(p=>p.fqid),this.projection=u.projection,this.index=u.index,this.worldview=u.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=u.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(u,p){}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,p,_,C){this.tileToMeter=Jm(_);const M=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:O,id:U,index:W,sourceLayerIndex:J}of u){const se=U??(O.properties&&Object.hasOwn(O.properties,"id")?O.properties.id:void 0),re=Hf(O,M);if(!this.layers[0]._featureFilter.filter(new fi(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),re,_))continue;const fe={id:se,sourceLayerIndex:J,index:W,geometry:M?re.geometry:bm(O,_,C),properties:O.properties,type:O.type,patterns:{}},xe=this.addFeature(fe,fe.geometry,re,L,_);xe&&p.featureIndex.insert(O,fe.geometry,W,J,this.index,this.instancesPerModel[xe].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const u=this.layers[0].modelManager,p=this.layers[0].scope;let _=0;for(const C of this.modelUris){const M=u.getModel(C,p);if(!M)continue;const L=this.instancesPerModel[C];if(L){const O=.5*Ee(M.aabb.max,M.aabb.min)*L.maxScale+L.maxXYTranslationDistance,U=Math.min(mr,Math.max(O/this.tileToMeter,256));_=Math.max(U,_)}}return _}update(u,p,_,C){for(const M in this.instancesPerModel){const L=this.instancesPerModel[M];for(const O in u)Object.hasOwn(L.idToFeaturesIndex,O)&&(this.evaluate(L.features[L.idToFeaturesIndex[O]],u[O],L,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let u=!1;for(const p in this.instancesPerModel){const _=this.instancesPerModel[p];for(const C of _.features){const M=this.layers[0],L=C.feature,O=this.canonical,U=M.paint.get("model-rotation").evaluate(L,{},O),W=M.paint.get("model-scale").evaluate(L,{},O),J=M.paint.get("model-translation").evaluate(L,{},O);Ce(C.rotation,U)&&Ce(C.scale,W)&&Ce(C.translation,J)||(this.evaluate(C,C.featureStates,_,!0),u=!0)}}return u}updateReplacement(u,p,_,C){if(p.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=p.updateTime;const M=p.getReplacementRegionsForTile(u.toUnwrapped(),!0);if(k9(this.activeReplacements,M))return!1;this.activeReplacements=M;let L=!1;for(const O in this.instancesPerModel){const U=this.instancesPerModel[O],W=U.instancedDataArray;for(const J of U.features){const se=J.instancedDataOffset,re=J.instancedDataCount;for(let fe=0;femr;we=je?we-mr:we;const Be=Math.floor(we),Ye=Math.floor(W.float32[xe+1]);let Ue=!1;for(const tt of this.activeReplacements)if(!bIe(tt,_,S9.Model,C)&&!(tt.min.x>Be||Be>tt.max.x||tt.min.y>Ye||Ye>tt.max.y)&&(Ue=kIe(NIe(Be,Ye,u.canonical,tt.footprintTileId.canonical),tt.footprint),Ue))break;W.float32[xe]=Ue?we+mr:we,L=L||Ue!==je}}}return L}isEmpty(){for(const u in this.instancesPerModel)if(this.instancesPerModel[u].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(u){if(!this.uploaded)for(const p in this.instancesPerModel){const _=this.instancesPerModel[p];_.instancedDataArray.length<0||_.instancedDataArray.length===0||(_.instancedDataBuffer?_.instancedDataBuffer.updateData(_.instancedDataArray):_.instancedDataBuffer=u.createVertexBuffer(_.instancedDataArray,mvt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(u){for(const _ in this.instancesPerModel){const C=this.instancesPerModel[_];C.instancedDataArray.length!==0&&C.instancedDataBuffer&&C.instancedDataBuffer.destroy()}const p=this.layers[0].modelManager;if(u&&p&&this.modelUris&&this.modelsRequested)for(const _ of this.modelUris)p.removeModel(_,"",!0)}addFeature(u,p,_,C,M){const L=this.layers[0],O=L.layout.get("model-id"),U=L.layout.get("model-allow-density-reduction"),W=O.evaluate(_,{},this.canonical);if(!W)return ra(`modelId is not evaluated for layer ${L.id} and it is not going to get rendered.`),W;!W.includes("://")&&!this.styleDefinedModelURLs[W]||this.modelUris.includes(W)||this.modelUris.push(W),this.instancesPerModel[W]||(this.instancesPerModel[W]=new VLe);const J=this.instancesPerModel[W],se=J.instancedDataArray,re=new qLe(_,se.length);let fe;C&&(fe=E.getElevationFeature(u,C));for(const xe of p)for(const we of xe){if(we.x<0||we.x>=mr||we.y<0||we.y>=mr)continue;if(this.lookupDim!==0&&U){const Be=(this.lookupDim-1)/mr,Ye=this.lookupDim*(we.y*Be|0)+we.x*Be|0;if(this.lookup){if(this.lookup[Ye]!==0)continue;this.lookup[Ye]=1}}this.instanceCount++;const je=se.length;if(se.resize(je+1),C){J.instancesRoadElevation||(J.instancesRoadElevation=[]);const Be=fe?fe.pointElevation(new us(we.x,we.y)):0;J.instancesRoadElevation.push(Be)}J.instancesEvaluatedElevation.push(0),se.float32[16*je]=we.x,se.float32[16*je+1]=we.y}return re.instancedDataCount=J.instancedDataArray.length-re.instancedDataOffset,re.instancedDataCount>0&&(u.id&&(J.idToFeaturesIndex[u.id]=J.features.length),J.features.push(re),this.evaluate(re,{},J,!1)),W}getModelUris(){return this.modelUris}evaluate(u,p,_,C){const M=this.layers[0],L=u.feature,O=this.canonical,U=u.rotation=M.paint.get("model-rotation").evaluate(L,p,O),W=u.scale=M.paint.get("model-scale").evaluate(L,p,O),J=u.translation=M.paint.get("model-translation").evaluate(L,p,O),se=Object.assign({},M.paint.get("model-color").evaluate(L,p,O));se.a=M.paint.get("model-color-mix-intensity").evaluate(L,p,O);const re=[];this.maxVerticalOffset0?Math.sqrt(fe):0;_.maxScale=Math.max(Math.max(_.maxScale,W[0]),Math.max(W[1],W[2])),_.maxXYTranslationDistance=Math.max(_.maxXYTranslationDistance,xe),this.maxScale=Math.max(Math.max(this.maxScale,W[0]),Math.max(W[1],W[2])),dPe(re,U,W);const we=Math.round(100*se.a)+se.b/1.05;for(let je=0;je10?this.tileToMeter:Jm(O,ot)),Ue[Ye+4]=J[0],Ue[Ye+5]=J[1],Ue[Ye+6]=J[2]+(_.instancesRoadElevation?_.instancesRoadElevation[Be]:0)+tt,Ue[Ye+7]=re[0],Ue[Ye+8]=re[1],Ue[Ye+9]=re[2],Ue[Ye+10]=re[4],Ue[Ye+11]=re[5],Ue[Ye+12]=re[6],Ue[Ye+13]=re[8],Ue[Ye+14]=re[9],Ue[Ye+15]=re[10],_.instancesEvaluatedElevation[Be]=J[2]}}}Mr(sve,"ModelBucket",{omit:["layers"]}),Mr(VLe,"PerModelAttributes"),Mr(qLe,"ModelFeature");class bE{constructor(u,p,_){this._demTile=u,this._dem=this._demTile.dem,this._scale=p,this._offset=_}static create(u,p,_){const C=_||u.findDEMTileFor(p);if(!C||!C.dem)return;const M=C.dem,L=C.tileID,O=1<W.fqid),this.stateDependentLayerIds=this.layers.filter(W=>W.isStateDependent()).map(W=>W.id),this.modelTraits|=uE.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,C&&(this.modelTraits|=uE.HasMapboxMeshFeatures),M&&(this.modelTraits|=uE.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=L,this.worldview=U,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const W of p)this.nodesInfo.push(new KLe(W)),GLe(W,O.featureIndexArray.length,O.grid),O.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,O.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(u,p){for(const _ of this.getNodesInfo()){const C=_.node;C.footprint&&p.push({footprint:C.footprint,id:u})}}updateAppearances(u,p,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(u){const p=Object.keys(u).length!==0;if(p&&!this.stateDependentLayers.length)return;const _=p?this.stateDependentLayers:this.layers;if(!pr(u,this.states))for(const C of _)this.evaluate(C,u);this.states=structuredClone(u)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(u){if(!this.needsUpload)return;const p=this.getNodesInfo();for(const _ of p){const C=_.node;this.uploaded?this.updatePbrBuffer(C):b0e(C,u,!0)}for(const _ of p)q9(_.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(u){let p=!1;if(!u.meshes)return p;for(const _ of u.meshes)_.pbrBuffer&&(_.pbrBuffer.updateData(_.featureArray),p=!0);if(u.lodMeshes)for(const _ of u.lodMeshes)_.pbrBuffer&&(_.pbrBuffer.updateData(_.featureArray),p=!0);return p}needsReEvaluation(u,p,_){const C=u.transform.projectionOptions,M=u.style.getBrightness(),L=this.brightness!==M;if(!this.uploaded||this.dirty||C.name!==this.projection.name||xD(_.paint.get("model-color").value,L)||xD(_.paint.get("model-color-mix-intensity").value,L)||xD(_.paint.get("model-roughness").value,L)||xD(_.paint.get("model-emissive-strength").value,L)||xD(_.paint.get("model-height-based-emissive-strength-multiplier").value,L)){this.projection=C,this.brightness=M;const O=this.getNodesInfo();for(const U of O)U.state=null;return!0}return!1}evaluateTransform(u,p){if(u.transform.zoom===this.zoom)return;this.zoom=u.transform.zoom;const _=this.getNodesInfo(),C=this.id.canonical;for(const M of _){const L=M.feature;M.evaluatedTranslation=p.paint.get("model-translation").evaluate(L,{},C),M.evaluatedScale=p.paint.get("model-scale").evaluate(L,{},C)}}evaluate(u,p){const _=this.getNodesInfo();for(const C of _){if(!C.node.meshes)continue;const M=C.feature,L=p&&p[M.id];if(pr(L,C.state))continue;C.state=structuredClone(L);const O=C.node.meshes&&C.node.meshes[0].featureData,U=C.evaluatedColor[2],W=C.evaluatedRMEA[2],J=this.id.canonical;if(C.hasTranslucentParts=!1,O){for(let se=0;se=pt)continue;const Ks=rve[ws],ds=Math.abs(Ks);ds>At&&(jt=Ks,At=ds,ns=ks,is=xs)}if(At>.1){const xs=1-(pt+.5*Math.abs(ns*is))/xe;let ks=p._dem.get(_t,Rt)+jt*xs;const ws=p._dem.get(_t+ns,Rt+is),Ks=p._dem.get(_t-ns,Rt-is,!0);(ks-ws)*(ks-Ks)>0&&(ks=(ws+Ks)/2),rve[Et]=p._dem.set(_t,Rt,ks),tk[Et]=pt}}}}}O&&(p._demTile.needsDEMTextureUpload=!0,p._dem._timestamp=bd.now())}setFilter(u){this.filter=u?GT(u):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(u=>this.filter.filter(new fi(this.id.overscaledZ,{worldview:this.worldview}),u.feature,this.id.canonical)):this.nodesInfo}destroy(){const u=this.getNodesInfo();for(const p of u)q9(p.node),_0e(p.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(u,p){if(p.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=p.updateTime;const _=p.getReplacementRegionsForTile(u.toUnwrapped());for(const C of this.getNodesInfo()){const M=C.node.footprint;C.hiddenByReplacement=!!M&&!_.some(L=>L.footprint===M)}}getHeightAtTileCoord(u,p){const _=[0,0,0],C=N([]);for(const M of this.getNodesInfo()){const L=M.node.meshes[0],O=L.transformedAabb;if(uO.max[0]||p>O.max[1])continue;if(M.node.hidden===!0)return{height:1/0,maxHeight:M.feature.properties.height,hidden:!1,verticalScale:M.evaluatedScale[2]};if(S(C,M.node.globalMatrix),_[0]=u,_[1]=p,_[2]=0,rt(_,_,C),M.node.meshBVH){const se=_[0],re=_[1];d$[0]=se-1,d$[1]=re-1,d$[2]=-1e3,u$[0]=se+1,u$[1]=re+1,u$[2]=1e3;const fe=M.node.meshBVH.findHighestPoint(d$,u$);if(fe!==null)return{height:fe,maxHeight:M.feature.properties.height,hidden:M.hiddenByReplacement,verticalScale:M.evaluatedScale[2]};continue}const U=(_[0]-L.aabb.min[0])/(L.aabb.max[0]-L.aabb.min[0])*YN|0,W=Math.min(63,(_[1]-L.aabb.min[1])/(L.aabb.max[1]-L.aabb.min[1])*YN|0)*YN+Math.min(63,U),J=L.heightmap[W];if(J<0&&M.node.footprint){const se=[];if(M.node.footprint.grid.query(new us(u,p),new us(u,p),se),se.length>0)return{height:void 0,maxHeight:M.feature.properties.height,hidden:M.hiddenByReplacement,verticalScale:M.evaluatedScale[2]};continue}return M.hiddenByReplacement?void 0:{height:J,maxHeight:M.feature.properties.height,hidden:!1,verticalScale:M.evaluatedScale[2]}}}}function xD(y,u){return y instanceof MN&&!y.isLightConstant&&u}function YLe(y,u,p,_,C,M,L,O){let U=(61440&u|(61440&u)>>4)>>8,W=(3840&u|(3840&u)>>4)>>4,J=240&u|(240&u)>>4;const se=15&u|(15&u)<<4;p[3]>0&&(U=Jr(U,255*p[0],p[3]),W=Jr(W,255*p[1],p[3]),J=Jr(J,255*p[2],p[3]));const re=se/255;U*=re,W*=re,J*=re;const fe=U<<8|W,xe=J<<8|Math.floor(255*_[3]),we=function(_t){const Et=Mt(_t,0,2);return Math.min(Math.round(.5*Et*255),255)}(_[2])<<8|15*_[0]<<4|15*_[1],je=Mt(C[0],0,1),Be=Mt(C[1],0,1),Ye=Mt(C[2],0,1),Ue=Mt(C[3],0,1);let tt,ot,pt,Rt;if(je!==Be&&L!==M&&Be!==je){const _t=L-M;ot=1/(_t*(Be-je)),pt=-(M+_t*je)/(_t*(Be-je));const Et=Mt(C[4],-1,1);Rt=Math.pow(10,Et),tt=255*Ye<<8|255*Ue}else tt=65535,ot=0,pt=1,Rt=1;if(y.emplaceBack(fe,xe,we,tt,ot,pt,Rt),O){const _t=O.length;O.clear();for(let Et=0;Et<_t;Et++)O.emplaceBack(fe,xe,we,tt,ot,pt,Rt)}}function tbt(y,u,p){const _=y.node;let C=0;const M=p&uE.HasMeshoptCompression;for(const L of _.meshes){if(_.lights&&_.lightMeshIndex===C||!L.featureData)continue;L.featureArray=new X1,L.featureArray.reserve(L.featureData.length);let O=u;for(const U of L.featureData){const W=M?65535&U:U>>16&65535,J=M?U>>16&65535:65535&U,se=(15&J)<8?15&J:0,re=y.evaluatedRMEA[se],fe=y.evaluatedColor[se],xe=y.emissionHeightBasedParams[se];let we;if(O&&se===2&&_.lights&&(we=new X1,we.resize(10*_.lights.length)),YLe(L.featureArray,W,fe,re,xe,L.aabb.min[2],L.aabb.max[2],we),we&&O){O=!1;const je=_.meshes[_.lightMeshIndex];je.featureArray=we,je.featureArray._trim()}}L.featureArray._trim(),C++}if(_.lodMeshes){for(const L of _.lodMeshes)if(L.featureData){L.featureArray=new X1,L.featureArray.reserve(L.featureData.length);for(const O of L.featureData){const U=M?O>>16&65535:65535&O,W=(15&U)<8?15&U:0;YLe(L.featureArray,M?65535&O:O>>16&65535,y.evaluatedColor[W],y.evaluatedRMEA[W],y.emissionHeightBasedParams[W],L.aabb.min[2],L.aabb.max[2],null)}L.featureArray._trim()}}}Mr(h$,"Tiled3dModelBucket",{omit:["layers"]}),Mr(KLe,"Tiled3dModelFeature");const sbt=["id","tile","layer","source","sourceLayer","state"];class sk{constructor(u,p,_,C,M){this.type="Feature",this._vectorTileFeature=u,this._z=p,this._x=_,this._y=C,this.properties=u?u.properties:{},this.id=M}clone(){const u=new sk(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(u.state=Object.assign({},this.state)),this.layer&&(u.layer=Object.assign({},this.layer)),this.source&&(u.source=this.source),this.sourceLayer&&(u.sourceLayer=this.sourceLayer),u}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(u){this._geometry=u}toJSON(){const u={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const p of sbt)this[p]!==void 0&&(u[p]=this[p]);return u}}class rk extends Aa{constructor(u,p,_,C){super(),this.id=u,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(u,p){return iPe(this.map._requestManager.transformRequest(u,kp.Model).url,p)}async loadModel(u,p,_){try{const C=await this.loadGLTFFromURI(p.uri,_);if(_.aborted)return;const M=this._modelsInfo.get(u);if(!M)return;const L=k0e(C),O=M.modelSpec,U=new uPe(u,O.uri,O.position,O.orientation,L);rk.applyModelSpecification(U,O),U.computeBoundsAndApplyParent(),this.models.push(U),M.model=U}catch(C){if(C instanceof Error&&C.name==="AbortError")return;const M=C instanceof Error?C.message:"Unknown error";this.fire(new hr(new Error(`Could not load model ${u} from ${p.uri}: ${M}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const u=this._abortController.signal,p=[];for(const _ in this._options.models){const C=this._options.models[_],M=this._modelsInfo.get(_);if(M&&M.model){M.modelSpec=C;const L=M.model;L.position=C.position!=null?new di(C.position[0],C.position[1]):new di(0,0),L.orientation=C.orientation!=null?C.orientation:[0,0,0],rk.applyModelSpecification(L,C),L.computeBoundsAndApplyParent(),this.models.push(L)}else M?M.modelSpec=C:(this._modelsInfo.set(_,{modelSpec:C,model:null}),p.push(this.loadModel(_,C,u)))}p.length!==0?(await Promise.allSettled(p),u.aborted||this.fire(new Gs("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Gs("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(u,p){p.nodeOverrides&&rk.convertNodeOverrides(u,p.nodeOverrides),p.materialOverrides&&rk.convertMaterialOverrides(u,p.materialOverrides),p.nodeOverrideNames&&(u.nodeOverrideNames=[...p.nodeOverrideNames]),p.materialOverrideNames&&(u.materialOverrideNames=[...p.materialOverrideNames]),p.featureProperties&&(u.featureProperties=p.featureProperties)}static convertNodeOverrides(u,p){if(Array.isArray(p)&&p.every(_=>typeof _=="string")){u.nodeOverrideNames=[];for(const _ of p)u.nodeOverrideNames.push(_)}else Object.entries(p).forEach(([_,C])=>{const M={orientation:[0,0,0]};if(Object.hasOwn(C,"orientation")){const L=C.orientation;L&&(M.orientation=L)}u.nodeOverrides.set(_,M)})}static convertMaterialOverrides(u,p){if(Array.isArray(p)&&p.every(_=>typeof _=="string")){u.materialOverrideNames=[];for(const _ of p)u.materialOverrideNames.push(_)}else Object.entries(p).forEach(([_,C])=>{const M={color:new Wa(1,1,1),colorMix:0,emissionStrength:0,opacity:1},L=C["model-color"];L!==void 0&&(M.color.r=L[0],M.color.g=L[1],M.color.b=L[2]);const O=C["model-color-mix-intensity"];O!==void 0&&(M.colorMix=O);const U=C["model-emissive-strength"];U!==void 0&&(M.emissionStrength=U);const W=C["model-opacity"];W!==void 0&&(M.opacity=W),u.materialOverrides.set(_,M)})}onAdd(u){this.map=u,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const u of this._modelsInfo.values())if(u.model==null)return!1;return!0}getModels(){return this.models}loadTile(u,p){}serialize(){return this._options}setProperty(u,p){return!1}reload(){this.cancelModelRequests();const u=u6(this.id,this.scope);this.map.style.clearSource(u),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(u){this.cancelModelRequests()}setModels(u){this.models=[];const p=new Map;for(const _ in u){const C=u[_],M=this._modelsInfo.get(_);M&&M.modelSpec.uri===C.uri&&p.set(_,M)}if(this._modelsInfo.size!==p.size){this.cancelModelRequests();for(const[_,C]of p)C.model||p.delete(_)}this._modelsInfo=p,this._options.models=u,this.load()}}function nve(y,u,p,_){const C=1<U>=ot.vertexArrayOffset&&Utt.polygon).flat());const je=fe?O:null,[Be,Ye]=GIe(M,_,se,J,W,L,je,re,xe,M.center.lat,y.tileID.canonical),Ue=y.queryGeometry;return HIe(Be,Ye,Ue.isPointQuery()?Ue.screenBounds:Ue.screenGeometry)}},building:class extends lh{constructor(y,u,p,_){super(y,{layout:FIe||(FIe=new ko({visibility:new rr(Yt.layout_building.visibility),"building-facade":new lr(Yt.layout_building["building-facade"]),"building-facade-floors":new lr(Yt.layout_building["building-facade-floors"]),"building-facade-unit-width":new lr(Yt.layout_building["building-facade-unit-width"]),"building-facade-window":new lr(Yt.layout_building["building-facade-window"]),"building-roof-shape":new lr(Yt.layout_building["building-roof-shape"]),"building-height":new lr(Yt.layout_building["building-height"]),"building-base":new lr(Yt.layout_building["building-base"]),"building-flood-light-wall-radius":new lr(Yt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new lr(Yt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new lr(Yt.layout_building["building-flip-roof-orientation"])})),paint:BIe||(BIe=new ko({"building-opacity":new rr(Yt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new rr(Yt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new rr(Yt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new rr(Yt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new rr(Yt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new rr(Yt.paint_building["building-vertical-scale"]),"building-cast-shadows":new rr(Yt.paint_building["building-cast-shadows"]),"building-color":new lr(Yt.paint_building["building-color"]),"building-emissive-strength":new lr(Yt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new rr(Yt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new rr(Yt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new rr(Yt.paint_building["building-front-cutoff"]),"building-flood-light-color":new rr(Yt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new rr(Yt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new rr(Yt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new lr({type:"string",default:"default","property-type":"data-driven"})}))},u,p,_),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}prepare(){return jPe()}createBucket(y){return new wPe(y)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(y){return!0}queryRadius(y){return 0}queryIntersectsFeature(y,u,p,_,C,M,L,O,U,W){let J=this.layout.get("building-height").evaluate(u,p);const se=this.layout.get("building-base").evaluate(u,p),re=y.tile.getBucket(this).getFootprint(u);if(re){if(re.hiddenFlags!==0)return!1;J=re.height}const[fe,xe]=GIe(M,_,se,J,new us(0,0),L,null,[0,0],1,M.center.lat,y.tileID.canonical),we=y.queryGeometry;return HIe(fe,xe,we.isPointQuery()?we.screenBounds:we.screenGeometry)}},line:class extends lh{constructor(y,u,p,_){const C=PPe();super(y,C,u,p,_),C.layout&&(this.layout=new py(C.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1,this.lineBlendFbos=null,this.lineBlendDensityReadback=null}_handleSpecialPaintPropertyUpdate(y){if(y==="line-gradient"){const u=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=u._styleExpression&&u._styleExpression.expression instanceof Q_,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(y,u){super.recalculate(y,u),this.paint._values["line-floorwidth"]=(()=>{if(sD)return sD;const p=PPe();return sD=new Kvt(p.paint.properties["line-width"].specification),sD.useIntegerZoom=!0,sD})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,y)}createBucket(y){return new H9(y)}getProgramIds(){const y=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&y.push("lineBlendComposite"),y}getDefaultProgramParams(y,u,p){if(y==="lineBlendComposite")return{};const _=MPe(this);return{config:new eb(this,{zoom:u,lut:p}),defines:_,overrideFog:!1}}queryRadius(y){const u=y,p=LPe(st("line-width",this,u),st("line-gap-width",this,u)),_=st("line-offset",this,u);return p/2+Math.abs(_)+Ut(this.paint.get("line-translate"))}queryIntersectsFeature(y,u,p,_,C,M){if(y.queryGeometry.isAboveHorizon)return!1;const L=Pt(y.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),M.angle,y.pixelToTileUnitsFactor),O=y.pixelToTileUnitsFactor/2*LPe(this.paint.get("line-width").evaluate(u,p),this.paint.get("line-gap-width").evaluate(u,p)),U=this.paint.get("line-offset").evaluate(u,p);return U&&(_=function(W,J){const se=[],re=new us(0,0);for(let fe=0;fe=3){for(let xe=0;xe{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 ZLe{constructor(u){this._stringToNumber={},this._numberToString=[];for(let p=0;p=0&&re[3]>=0&&W.insert(U,re[0],re[1],re[2],re[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new L6(new G9(this.rawTileData)).layers,this.sourceLayerCoder=new ZLe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const u in this.vtLayers)this.vtFeatures[u]=[]}return this.vtLayers}query(u,p){const{tilespaceGeometry:_,transform:C,tileTransform:M,pixelPosMatrix:L,availableImages:O,worldview:U}=p;this.loadVTLayers(),this.serializedLayersCache.clear();const W=p.queryRadius?p.queryRadius:0,J=_.bufferedTilespaceBounds,se=this.grid.queryKeys(J.min.x,J.min.y,J.max.x,J.max.y,(we,je,Be,Ye)=>Ze(_.bufferedTilespaceGeometry,we-W,je-W,Be+W,Ye+W));se.sort(ibt);let re=null;C.elevation&&se.length>0&&(re=bE.create(C.elevation,this.tileID));const fe={};let xe;for(let we=0;we(Ye||(Ye=bm(Ue,this.tileID.canonical,M)),tt.queryIntersectsFeature(_,Ue,ot,Ye,this.z,C,L,re,pt,p.scope)))}return fe}loadMatchingFeature(u,p,_,C,M,L){const{featureIndex:O,bucketIndex:U,sourceLayerIndex:W,layoutVertexArrayOffset:J}=p,se=this.bucketLayerIDs[U],re=_.layers,fe=Object.keys(re);if(fe.length&&!Ja(fe,se))return;const xe=_.sourceCache,we=this.sourceLayerCoder.decode(W),je=this.vtLayers[we].feature(O),Be=this.getId(je,we);for(let Ye=0;Ye`${O.key}: ${O.message}`).join(", ");return void ra(`Failed to create expression for promoteId: ${L}`)}this.promoteIdExpression=M.value}_=this.promoteIdExpression.evaluate({zoom:0},u)}else _=u.properties[C];typeof _=="boolean"&&(_=Number(_))}return _}}function QLe(y,u,p,_,C){return $s(y,(M,L)=>{const O=u instanceof py?u.get(L):null;return O&&O.evaluate?O.evaluate(p,_,void 0,C):O})}function ibt(y,u){return u-y}function JLe(y,u){const p={};if(!u)return p;for(const _ of y){const C=_.layerIds.map(M=>u.getLayer(M)).filter(Boolean);if(C.length!==0){_.layers=C,_.stateDependentLayerIds&&(_.stateDependentLayers=_.stateDependentLayerIds.map(M=>C.filter(L=>L.id===M)[0])),_.updateExpressions&&_.updateExpressions(C);for(const M of C)p[M.fqid]=_}}return p}Mr(XLe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const cg=32,Y0=33,jw=new Uint16Array(8184);for(let y=0;y<2046;y++){let u=y+2,p=0,_=0,C=0,M=0,L=0,O=0;for(1&u?C=M=L=cg:p=_=O=cg;(u>>=1)>1;){const W=p+C>>1,J=_+M>>1;1&u?(C=p,M=_,p=L,_=O):(p=C,_=M,C=L,M=O),L=W,O=J}const U=4*y;jw[U+0]=p,jw[U+1]=_,jw[U+2]=C,jw[U+3]=M}const Z0=new Uint16Array(2178),Nw=new Uint8Array(1089),m$=new Uint16Array(1089);function e6e(y){return y===0?-.03125:y===32?.03125:0}const t6e={Other:0,Symbol:1,FillExtrusion:2},s6e={type:2,extent:mr,loadGeometry:()=>[[new us(0,0),new us(8193,0),new us(8193,8193),new us(0,8193),new us(0,0)]]};class obt{constructor(){this.tasks={},this.taskQueue=[],Qr(["process"],this),this.invoker=new abt(this.process),this.nextId=0}add(u,p){const _=this.nextId++,C=function({type:M,renderSourceType:L,zoom:O}){O=O||0;const U=L===t6e.Symbol;return M==="message"?0:M!=="maybePrepare"||U?M!=="parseTile"||U?M==="parseTile"&&U?300-O:M==="maybePrepare"&&U?400-O:500:200-O:100-O}(p);if(C===0){try{u()}finally{}return null}return this.tasks[_]={fn:u,metadata:p,priority:C,id:_},this.taskQueue.push(_),this.invoker.trigger(),{cancel:()=>{delete this.tasks[_]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(_=>!!this.tasks[_]),!this.taskQueue.length)return;const u=this.pick();if(u===null)return;const p=this.tasks[u];if(delete this.tasks[u],this.taskQueue.length&&this.invoker.trigger(),!p)return;p.fn()}finally{}}pick(){let u=null,p=1/0;for(let C=0;Cu[L])return null}else{const O=1/_[L];let U=(y[L]-p[L])*O,W=(u[L]-p[L])*O;if(U>W){const J=U;U=W,W=J}if(U>C&&(C=U),WM)return null}return C}function o6e(y,u,p,_,C,M,L,O,U,W,J){const se=_-y,re=C-u,fe=M-p,xe=L-y,we=O-u,je=U-p,Be=J[1]*je-J[2]*we,Ye=J[2]*xe-J[0]*je,Ue=J[0]*we-J[1]*xe,tt=se*Be+re*Ye+fe*Ue;if(Math.abs(tt)<1e-15)return null;const ot=1/tt,pt=W[0]-y,Rt=W[1]-u,_t=W[2]-p,Et=(pt*Be+Rt*Ye+_t*Ue)*ot;if(Et<0||Et>1)return null;const jt=Rt*fe-_t*re,At=_t*se-pt*fe,ns=pt*re-Rt*se,is=(J[0]*jt+J[1]*At+J[2]*ns)*ot;return is<0||Et+is>1?null:(xe*jt+we*At+je*ns)*ot}function l6e(y,u,p){return(y-u)/(p-u)}function c6e(y,u,p,_,C,M,L,O,U){const W=1<{const Ye=je?1:0,Ue=(fe+1)*we-Ye,tt=xe*we,ot=(xe+1)*we-Ye;Be[0]=fe*we,Be[1]=tt,Be[2]=Ue,Be[3]=ot};let se=new a6e(U);const re=[];for(let fe=0;fe=1;U/=2){const fe=O.at(-1);se=new a6e(U);for(let xe=0;xe0;){const{idx:xe,t:we,nodex:je,nodey:Be,depth:Ye}=fe.pop();if(this.leaves[xe]){c6e(je,Be,Ye,u,p,_,C,se,re);const tt=1<=ws[2])return we}continue}let Ue=0;for(let tt=0;tt=W[J[_t]]&&(J.splice(_t,0,tt),Rt=!0);Rt||(J[Ue]=tt),Ue++}}for(let tt=0;tt=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+(u+1)}static pack(u,p){const _=[0,0,0,0],C=f$.getUnpackVector(p);let M=Math.floor((u+C[3])/C[2]);return _[2]=M%256,M=Math.floor(M/256),_[1]=M%256,M=Math.floor(M/256),_[0]=M,_}getPixels(){return new Mi({width:this.stride,height:this.stride},this.pixels)}backfillBorder(u,p,_){if(this.dim!==u.dim)throw new Error("dem dimension mismatch");let C=p*this.dim,M=p*this.dim+this.dim,L=_*this.dim,O=_*this.dim+this.dim;switch(p){case-1:C=M-1;break;case 1:M=C+1}switch(_){case-1:L=O-1;break;case 1:O=L+1}const U=-p*this.dim,W=-_*this.dim;for(let J=L;J=1;_--){const C=_===1?1:0,M=_===2?1:0;for(let L=0;L>>1^-(1&y[u]);return y}function _bt(y,u){switch(u){case"uint32":return y;case"uint16":for(let p=0;p>4|(61440&_)>>8|(240&C)<<4|61440&C,y[p+1]=15&_|(3840&_)>>4|(15&C)<<8|(3840&C)<<4}return y;case"uint8":for(let p=0;p>6|(192&C)>>4|(192&M)>>2|192&L,y[p+1]=(48&_)>>4|(48&C)>>2|48&M|(48&L)<<2,y[p+2]=(12&_)>>2|12&C|(12&M)<<2|(12&L)<<4,y[p+3]=3&_|(3&C)<<2|(3&M)<<4|(3&L)<<6}return y;default:throw new Error(`Invalid pixel format, "${u}"`)}}Mr(f$,"DEMData"),Mr(d6e,"DemMinMaxQuadTree",{omit:["dem"]});var Bp=Uint8Array,gD=Uint16Array,wbt=Int32Array,h6e=new Bp([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]),m6e=new Bp([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]),jbt=new Bp([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f6e=function(y,u){for(var p=new gD(31),_=0;_<31;++_)p[_]=u+=1<>1|(21845&_c)<<1;g6e[_c]=((65280&(_E=(61680&(_E=(52428&_E)>>2|(13107&_E)<<2))>>4|(3855&_E)<<4))>>8|(255&_E)<<8)>>1}var yD=function(y,u,p){for(var _=y.length,C=0,M=new gD(u);C<_;++C)y[C]&&++M[y[C]-1];var L,O=new gD(u);for(C=1;C>U]=W;return L},vD=new Bp(288);for(_c=0;_c<144;++_c)vD[_c]=8;for(_c=144;_c<256;++_c)vD[_c]=9;for(_c=256;_c<280;++_c)vD[_c]=7;for(_c=280;_c<288;++_c)vD[_c]=8;var y6e=new Bp(32);for(_c=0;_c<32;++_c)y6e[_c]=5;var Sbt=yD(vD,9),Cbt=yD(y6e,5),ove=function(y){for(var u=y[0],p=1;pu&&(u=y[p]);return u},Ny=function(y,u,p){var _=u/8|0;return(y[_]|y[_+1]<<8)>>(7&u)&p},lve=function(y,u){var p=u/8|0;return(y[p]|y[p+1]<<8|y[p+2]<<16)>>(7&u)},Tbt=function(y){return(y+7)/8|0},Ebt=["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"],ky=function(y,u,p){var _=new Error(u||Ebt[y]);if(_.code=y,Error.captureStackTrace&&Error.captureStackTrace(_,ky),!p)throw _;return _},Abt=new Bp(0),Mbt=typeof TextDecoder<"u"&&new TextDecoder;try{Mbt.decode(Abt,{stream:!0})}catch{}const Ibt={gzip_data:"gzip"};class dg extends Error{constructor(u){super(u),this.name="MRTError"}}const Pbt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},v6e={uint32:1,uint16:2,uint8:4},Lbt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let cve;class p${constructor(u=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=u}getLayer(u){const p=this.layers[u];if(!p)throw new dg(`Layer '${u}' not found`);return p}getHeaderLength(u){const p=new Uint8Array(u),_=new DataView(u);if(p[0]!==13)throw new dg("File is not a valid MRT.");return _.getUint32(1,!0)}parseHeader(u){const p=new Uint8Array(u),_=this.getHeaderLength(u);if(p.length<_)throw new dg(`Expected header with length >= ${_} but got buffer of length ${p.length}`);const C=new cve(p.subarray(0,_)).readFields(ubt,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==C.x||this.y!==C.y||this.z!==C.z))throw new dg(`Invalid attempt to parse header ${C.z}/${C.x}/${C.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=C.x,this.y=C.y,this.z=C.z;for(const M of C.layers)this.layers[M.name]=new b6e(M,{cacheSize:this._cacheSize});return this}createDecodingTask(u){const p=[],_=this.getLayer(u.layerName);for(let C of u.blockIndices){const M=_.dataIndex[C],L=M.firstByte-u.firstByte,O=M.lastByte-u.firstByte;if(_._blocksInProgress.has(C))continue;const U={layerName:_.name,firstByte:L,lastByte:O,pixelFormat:_.pixelFormat,blockIndex:C,blockShape:[M.bands.length].concat(_.bandShape),buffer:_.buffer,codec:M.codec.codec,filters:M.filters.map(W=>W.filter)};_._blocksInProgress.add(C),p.push(U)}return new _6e(p,()=>{p.forEach(C=>_._blocksInProgress.delete(C.blockIndex))},(C,M)=>{if(p.forEach(L=>_._blocksInProgress.delete(L.blockIndex)),C)throw C;M.forEach(L=>{this.getLayer(L.layerName).processDecodedData(L)})})}}class b6e{constructor({version:u,name:p,units:_,tileSize:C,pixelFormat:M,buffer:L,dataIndex:O},U){if(this.version=u,this.version!==1)throw new dg(`Cannot parse raster layer encoded with MRT version ${u}`);this.name=p,this.units=_,this.tileSize=C,this.buffer=L,this.pixelFormat=Pbt[M],this.dataIndex=O,this.bandShape=[C+2*L,C+2*L,v6e[this.pixelFormat]],this._decodedBlocks=new ave(U?U.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return v6e[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:u})=>u).flat()}processDecodedData(u){const p=u.blockIndex.toString();this._decodedBlocks.get(p)||this._decodedBlocks.put(p,u.data)}getBlockForBand(u){let p=0;switch(typeof u){case"string":for(const[_,C]of this.dataIndex.entries()){for(const[M,L]of C.bands.entries())if(L===u)return{bandIndex:p+M,blockIndex:_,blockBandIndex:M};p+=C.bands.length}break;case"number":for(const[_,C]of this.dataIndex.entries()){if(u>=p&&uthis.cacheSize)throw new dg(`Number of blocks to decode (${M.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:p,lastByte:_,blockIndices:C}}hasBand(u){const{blockIndex:p}=this.getBlockForBand(u);return p>=0}hasDataForBand(u){const{blockIndex:p}=this.getBlockForBand(u);return p>=0&&!!this._decodedBlocks.get(p.toString())}getBandView(u){const{blockIndex:p,blockBandIndex:_}=this.getBlockForBand(u);if(p<0)throw new dg(`Band not found: ${JSON.stringify(u)}`);const C=this._decodedBlocks.get(p.toString());if(!C)throw new dg(`Data for band ${JSON.stringify(u)} of layer "${this.name}" not decoded.`);const M=this.dataIndex[p],L=this.bandShape.reduce((W,J)=>W*J,1),O=_*L,U=C.subarray(O,O+L);return{data:U,bytes:new Uint8Array(U.buffer).subarray(U.byteOffset,U.byteOffset+U.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:M.offset,scale:M.scale}}}p$.setPbf=function(y){cve=y};class _6e{constructor(u,p,_){this.tasks=u,this._onCancel=p,this._onComplete=_,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(u,p){this._finalized||(this._onComplete(u,p),this._finalized=!0)}}p$.performDecoding=function(y,u){const p=new Uint8Array(y);return Promise.all(u.tasks.map(_=>{const{layerName:C,firstByte:M,lastByte:L,pixelFormat:O,blockShape:U,blockIndex:W,filters:J,codec:se}=_,re=p.subarray(M,L+1),fe=new Uint32Array(U[0]*U[1]*U[2]);let xe;if(se!=="gzip_data")throw new dg(`Unhandled codec: ${se}`);return xe=function(we,je){if(!globalThis.DecompressionStream&&je==="gzip_data")return Promise.resolve((ot=function(_t){_t[0]==31&&_t[1]==139&&_t[2]==8||ky(6,"invalid gzip data");var Et=_t[3],jt=10;4&Et&&(jt+=2+(_t[10]|_t[11]<<8));for(var At=(Et>>3&1)+(Et>>4&1);At>0;At-=!_t[jt++]);return jt+(2&Et)}(Be=we),ot+8>Be.length&&ky(6,"invalid gzip data"),function(_t,Et,jt,At){var ns=_t.length;if(!ns||Et.f&&!Et.l)return jt||new Bp(0);var is=!jt,xs=is||Et.i!=2,ks=Et.i;is&&(jt=new Bp(3*ns));var ws=function(Wo){var wc=jt.length;if(Wo>wc){var jm=new Bp(Math.max(2*wc,Wo));jm.set(jt),jt=jm}},Ks=Et.f||0,ds=Et.p||0,gs=Et.b||0,Cs=Et.l,Bs=Et.d,Hs=Et.m,cr=Et.n,Ds=8*ns;do{if(!Cs){Ks=Ny(_t,ds,1);var tr=Ny(_t,ds+1,3);if(ds+=3,!tr){var sr=_t[(xi=Tbt(ds)+4)-4]|_t[xi-3]<<8,wr=xi+sr;if(wr>ns){ks&&ky(0);break}xs&&ws(gs+sr),jt.set(_t.subarray(xi,wr),gs),Et.b=gs+=sr,Et.p=ds=8*wr,Et.f=Ks;continue}if(tr==1)Cs=Sbt,Bs=Cbt,Hs=9,cr=5;else if(tr==2){var Ar=Ny(_t,ds,31)+257,tn=Ny(_t,ds+10,15)+4,zr=Ar+Ny(_t,ds+5,31)+1;ds+=14;for(var Sn=new Bp(zr),si=new Bp(19),Wn=0;Wn>4)<16)Sn[Wn++]=xi;else{var Vi=0,Ro=0;for(xi==16?(Ro=3+Ny(_t,ds,3),ds+=2,Vi=Sn[Wn-1]):xi==17?(Ro=3+Ny(_t,ds,7),ds+=3):xi==18&&(Ro=11+Ny(_t,ds,127),ds+=7);Ro--;)Sn[Wn++]=Vi}}var Fc=Sn.subarray(0,Ar),eo=Sn.subarray(Ar);Hs=ove(Fc),cr=ove(eo),Cs=yD(Fc,Hs),Bs=yD(eo,cr)}else ky(1);if(ds>Ds){ks&&ky(0);break}}xs&&ws(gs+131072);for(var ul=(1<>4;if((ds+=15&Vi)>Ds){ks&&ky(0);break}if(Vi||ky(2),ic<256)jt[gs++]=ic;else{if(ic==256){Fl=ds,Cs=null;break}var pa=ic-254;ic>264&&(pa=Ny(_t,ds,(1<<(kl=h6e[Wn=ic-257]))-1)+x6e[Wn],ds+=kl);var Yd=Bs[lve(_t,ds)&ac],hh=Yd>>4;if(Yd||ky(3),ds+=15&Yd,eo=kbt[hh],hh>3){var kl=m6e[hh];eo+=lve(_t,ds)&(1<Ds){ks&&ky(0);break}xs&&ws(gs+131072);var ed=gs+pa;if(gsWo.length)&&(jm=Wo.length),new Bp(Wo.subarray(0,jm))}(jt,0,gs):jt.subarray(0,gs)}(Be.subarray(ot,-8),{i:2},new Bp(((Ue=Be)[(tt=Ue.length)-4]|Ue[tt-3]<<8|Ue[tt-2]<<16|Ue[tt-1]<<24)>>>0),Ye)));var Be,Ye,Ue,tt,ot;const pt=Ibt[je];if(!pt)throw new Error(`Unhandled codec: ${je}`);const Rt=new globalThis.DecompressionStream(pt);return new Response(new Blob([we]).stream().pipeThrough(Rt)).arrayBuffer().then(_t=>new Uint8Array(_t))}(re,se).then(we=>(function(je,Be){je.readFields(gbt,Be)}(new cve(we),fe),new Lbt[O](fe.buffer))),xe.then(we=>{for(let je=J.length-1;je>=0;je--)switch(J[je]){case"delta_filter":vbt(we,U);break;case"zigzag_filter":bbt(we);break;case"bitshuffle_filter":_bt(we,O);break;default:throw new dg(`Unhandled filter "${J[je]}"`)}return{layerName:C,blockIndex:W,data:we}}).catch(we=>{throw we})}))},Mr(_6e,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Mr(p$,"MapboxRasterTile"),Mr(b6e,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const w6e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class dve{static from(u){if(!(u instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[p,_]=new Uint8Array(u,0,2);if(p!==219)throw new Error("Data does not appear to be in a KDBush format.");const C=_>>4;if(C!==1)throw new Error(`Got v${C} data when expected v1.`);const M=w6e[15&_];if(!M)throw new Error("Unrecognized array type.");const[L]=new Uint16Array(u,2,1),[O]=new Uint32Array(u,4,1);return new dve(O,L,M,u)}constructor(u,p=64,_=Float64Array,C){if(isNaN(u)||u<0)throw new Error(`Unpexpected numItems value: ${u}.`);this.numItems=+u,this.nodeSize=Math.min(Math.max(+p,2),65535),this.ArrayType=_,this.IndexArrayType=u<65536?Uint16Array:Uint32Array;const M=w6e.indexOf(this.ArrayType),L=2*u*this.ArrayType.BYTES_PER_ELEMENT,O=u*this.IndexArrayType.BYTES_PER_ELEMENT,U=(8-O%8)%8;if(M<0)throw new Error(`Unexpected typed array class: ${_}.`);C&&C instanceof ArrayBuffer?(this.data=C,this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+O+U,2*u),this._pos=2*u,this._finished=!0):(this.data=new ArrayBuffer(8+L+O+U),this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+O+U,2*u),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+M]),new Uint16Array(this.data,2,1)[0]=p,new Uint32Array(this.data,4,1)[0]=u)}add(u,p){const _=this._pos>>1;return this.ids[_]=_,this.coords[this._pos++]=u,this.coords[this._pos++]=p,_}finish(){const u=this._pos>>1;if(u!==this.numItems)throw new Error(`Added ${u} items when expected ${this.numItems}.`);return uve(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(u,p,_,C){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:M,coords:L,nodeSize:O}=this,U=[0,M.length-1,0],W=[];for(;U.length;){const J=U.pop()||0,se=U.pop()||0,re=U.pop()||0;if(se-re<=O){for(let je=re;je<=se;je++){const Be=L[2*je],Ye=L[2*je+1];Be>=u&&Be<=_&&Ye>=p&&Ye<=C&&W.push(M[je])}continue}const fe=re+se>>1,xe=L[2*fe],we=L[2*fe+1];xe>=u&&xe<=_&&we>=p&&we<=C&&W.push(M[fe]),(J===0?u<=xe:p<=we)&&(U.push(re),U.push(fe-1),U.push(1-J)),(J===0?_>=xe:C>=we)&&(U.push(fe+1),U.push(se),U.push(1-J))}return W}within(u,p,_){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:C,coords:M,nodeSize:L}=this,O=[0,C.length-1,0],U=[],W=_*_;for(;O.length;){const J=O.pop()||0,se=O.pop()||0,re=O.pop()||0;if(se-re<=L){for(let je=re;je<=se;je++)N6e(M[2*je],M[2*je+1],u,p)<=W&&U.push(C[je]);continue}const fe=re+se>>1,xe=M[2*fe],we=M[2*fe+1];N6e(xe,we,u,p)<=W&&U.push(C[fe]),(J===0?u-_<=xe:p-_<=we)&&(O.push(re),O.push(fe-1),O.push(1-J)),(J===0?u+_>=xe:p+_>=we)&&(O.push(fe+1),O.push(se),O.push(1-J))}return U}}function uve(y,u,p,_,C,M){if(C-_<=p)return;const L=_+C>>1;j6e(y,u,L,_,C,M),uve(y,u,p,_,L-1,1-M),uve(y,u,p,L+1,C,1-M)}function j6e(y,u,p,_,C,M){for(;C>_;){if(C-_>600){const W=C-_+1,J=p-_+1,se=Math.log(W),re=.5*Math.exp(2*se/3),fe=.5*Math.sqrt(se*re*(W-re)/W)*(J-W/2<0?-1:1);j6e(y,u,p,Math.max(_,Math.floor(p-J*re/W+fe)),Math.min(C,Math.floor(p+(W-J)*re/W+fe)),M)}const L=u[2*p+M];let O=_,U=C;for(bD(y,u,_,p),u[2*C+M]>L&&bD(y,u,_,C);OL;)U--}u[2*_+M]===L?bD(y,u,_,U):(U++,bD(y,u,U,C)),U<=p&&(_=U+1),p<=U&&(C=U-1)}}function bD(y,u,p,_){hve(y,p,_),hve(u,2*p,2*_),hve(u,2*p+1,2*_+1)}function hve(y,u,p){const _=y[u];y[u]=y[p],y[p]=_}function N6e(y,u,p,_){const C=y-p,M=u-_;return C*C+M*M}c.$=_L,c.A=Of,c.B=2,c.C=Wa,c.D=aD,c.E=Aa,c.F=JPe,c.G=bL,c.H=d6,c.I=Gn,c.J=mT,c.K=fN,c.L=ave,c.M=VL,c.N=MT,c.O=v7,c.P=us,c.Q=PT,c.R=kp,c.S=lw,c.T=K0,c.U=L0,c.V=YL,c.W=Jx,c.X=q1,c.Y=Bf,c.Z=ih,c._=pN,c.a=function(y){return Va.API_CDN_URL_REGEX.test(y)},c.a$=rk,c.a0=Tp,c.a1=Lp,c.a2=/^(.*)-use-theme$/,c.a3=/^(.*)-transition$/,c.a4=HL,c.a5=y7,c.a6=Yt,c.a7=LN,c.a8=ko,c.a9=rr,c.aA=function(y){let u=1/0,p=1/0,_=-1/0,C=-1/0;for(const M of y)u=Math.min(u,M.x),p=Math.min(p,M.y),_=Math.max(_,M.x),C=Math.max(C,M.y);return{min:new us(u,p),max:new us(_,C)}},c.aB=Mt,c.aC=T,c.aD=at,c.aE=mu,c.aF=qe,c.aG=by,c.aH=i9,c.aI=q0,c.aJ=ig,c.aK=gr,c.aL=class{constructor(y){this.entries={},this.scheduler=y}request(y,u,p,_){const C=this.entries[y]=this.entries[y]||{callbacks:[]};if(C.result){const[M,L]=C.result;return this.scheduler?this.scheduler.add(()=>{_(M,L)},u):_(M,L),()=>{}}return C.callbacks.push(_),C.cancel||(C.cancel=p((M,L)=>{C.result=[M,L];for(const O of C.callbacks)this.scheduler?this.scheduler.add(()=>{O(M,L)},u):O(M,L);setTimeout(()=>delete this.entries[y],3e3)})),()=>{C.result||(C.callbacks=C.callbacks.filter(M=>M!==_),C.callbacks.length||(C.cancel(),delete this.entries[y]))}}},c.aM=function(y){if("provider"in y&&!y.provider)return null;let u=y.provider;if(!u&&"url"in y&&y.url&&(u=function(C){try{const M=new URL(C).pathname.split("/").pop()||"",L=M.lastIndexOf(".");return L>=0?M.slice(L+1):""}catch{return""}}(y.url)),!u)return null;const p=Va.TILE_PROVIDER_URLS[u];if(!p)return null;let _;try{_=new URL(p,Va.API_URL).href}catch{return new Error(`TileProvider "${u}" has an invalid URL: "${p}"`)}return{name:u,url:_}},c.aN=function(y,u,p,_,C){const M=function(O,U){if(O)return C(O);if(U){y.url&&U.tiles&&y.tiles&&delete y.tiles;const W=r6e(y,U,u);if(W instanceof Error)return C(W);C(null,W)}},L=function(O,U,W){if(!O)return null;if(!U&&!W)return O;W=W||O.worldview_default;const J=Object.values(O.language||{});if(J.length===0)return null;const se=Object.values(O.worldview||{});if(se.length===0)return null;const re=J.every(xe=>xe===U),fe=se.every(xe=>xe===W);return re&&fe?O:U in(O.language_options||{})||W in(O.worldview_options||{})?null:O.language_options&&O.worldview_options?O:null}(y.data,p,_);return L?bd.frame(()=>M(null,L)):y.url?P1(u.transformRequest(u.normalizeSourceURL(y.url,null,p,_),kp.Source),M):bd.frame(()=>{const{data:O,...U}=y;M(null,U)})},c.aO=function(y,u){const p=y.url&&!y.tiles?u.transformRequest(y.url,kp.Source):void 0;return{request:p,options:p?Object.assign({},y,{url:p.url}):y}},c.aP=function(y,u,p){return u?r6e(y,u,p):y.tiles&&y.tiles.length>0?{tiles:y.tiles}:new Error('TileJSON is missing required "tiles" property')},c.aQ=function(y,u,p){const _=JSON.stringify(y.request);return y.data&&(this.deduped.entries[_]={result:[null,y.data]}),this.deduped.request(_,{type:"parseTile",renderSourceType:y.renderSourceType,zoom:y.tileZoom},C=>{const M=C0(y.request,(L,O,U)=>{L?M1(L)?C(null,null):C(L):O&&C(null,{rawData:O,vectorTile:p?void 0:new L6(new G9(O)),responseHeaders:new Map(U.entries())})});return()=>{M.cancel(),C(null,null)}},u)},c.aR=function(y){return y?{cacheControl:y.get("cache-control"),expires:y.get("expires")}:{cacheControl:void 0,expires:void 0}},c.aS=function(y){k0++,k0>ly&&(y.getActor().send("enforceCacheSizeLimit",oy),k0=0)},c.aT=async function(y,u){const p=n6e.get(y);if(p)return p;const _=ive.get(y);if(_!==void 0)return _;const C=import(u).catch(M=>{throw new Error(`TileProvider "${y}" failed to load: ${M instanceof Error?M.message:String(M)}`)}).then(M=>{const L=M.default;if(typeof L!="function")throw new Error(`TileProvider "${y}" module must default-export a class`);if(typeof L.prototype.loadTile!="function")throw new Error(`TileProvider "${y}" class must have a loadTile method`);return n6e.set(y,L),L}).finally(()=>{ive.delete(y)});return ive.set(y,C),C},c.aU=Wt,c.aV=LLe,c.aW=ULe,c.aX=di,c.aY=PLe,c.aZ=function(y,u){const p=document.createElement("video");p.muted=!0,p.onloadstart=function(){u(null,p)};for(let _=0;_{}}},c.a_=eD,c.aa=class{constructor(y){this.specification=y}possiblyEvaluate(y,u){return Po(y.expression.evaluate(u))}interpolate(y,u,p){return{x:Jr(y.x,u.x,p),y:Jr(y.y,u.y,p),z:Jr(y.z,u.z,p),azimuthal:Jr(y.azimuthal,u.azimuthal,p),polar:Jr(y.polar,u.polar,p)}}},c.ab=fi,c.ac=eg,c.ad=fu,c.ae=rt,c.af=ce,c.ag=Kt,c.ah=py,c.ai=Li,c.aj=Jr,c.ak=mr,c.al=qz,c.am=We,c.an=Xr,c.ao=Ls,c.ap=class{constructor(y,u,p){this.target=y,this.parent=u,this.mapId=p,this.callbacks={},this.cancelCallbacks={},Qr(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new obt}send(y,u,p,_,C=!1,M){const L=Math.round(1e18*Math.random()).toString(36).substring(0,10);p&&(p.metadata=M,this.callbacks[L]=p);const O=new Set;return this.target.postMessage({id:L,type:y,hasCallback:!!p,targetMapId:_,mustQueue:C,sourceMapId:this.mapId,data:my(u,O)},O),{cancel:()=>{p&&delete this.callbacks[L],this.target.postMessage({id:L,type:"",targetMapId:_,sourceMapId:this.mapId})}}}receive(y){const u=y.data;if(!u)return;const p=u.id;if(p&&(!u.targetMapId||this.mapId===u.targetMapId))if(u.type===""){const _=this.cancelCallbacks[p];delete this.cancelCallbacks[p],_&&_.cancel()}else if(u.mustQueue||ci(self)){const _=this.callbacks[p],C=this.scheduler.add(()=>this.processTask(p,u),_&&_.metadata||{type:"message"});C&&(this.cancelCallbacks[p]=C)}else this.processTask(p,u)}processTask(y,u){if(delete this.cancelCallbacks[y],u.type===""){const p=this.callbacks[y];delete this.callbacks[y],p&&(u.error?p(fy(u.error)):p(null,fy(u.data)))}else{const p=new Set,_=u.hasCallback?(M,L)=>{this.target.postMessage({id:y,type:"",sourceMapId:this.mapId,error:M?my(M):null,data:my(L,p)},p)}:()=>{},C=fy(u.data);if(this.parent[u.type])this.parent[u.type](u.sourceMapId,C,_);else if(this.parent.getWorkerSource){const M=u.type.split("."),{source:L,scope:O}=C;this.parent.getWorkerSource(u.sourceMapId,{type:M[0],source:L,scope:O,uid:0})[M[1]](C,_)}else _(new Error(`Could not find function ${u.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},c.aq=class{constructor(y){this.specification=y}possiblyEvaluate(y,u){return function([p,_]){const C=Po([1,p,_]);return{x:C.x,y:C.y,z:C.z}}(y.expression.evaluate(u))}interpolate(y,u,p){return{x:Jr(y.x,u.x,p),y:Jr(y.y,u.y,p),z:Jr(y.z,u.z,p)}}},c.ar=function(y,u,p=0,_=!0){const C=new us(p,p),M=y.sub(C),L=u.add(C),O=[M,new us(L.x,M.y),L,new us(M.x,L.y)];return _&&O.push(M.clone()),O},c.as=function(y,u){const p=[];for(let _=0;_this.buckets[se].layers.some(re=>L.has(re.fqid))),U=Object.keys(this.buckets).some(se=>this.buckets[se].layers.some(re=>re.hasTransition&&re.hasTransition())),W=this._firstPrepareComplete&&M!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(u));const J=this._lastUpdatedBrightness!==_;this._lastAvailableImagesCount=M,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||_||this._hasAppearances||O||U||W)&&(!(this._hasAppearances||O||U||W)&&this._lastUpdatedBrightness&&_&&Math.abs(this._lastUpdatedBrightness-_)<.001||(this.updateBuckets(u,J,void 0,W||O||U,L,C),this._lastUpdatedBrightness=_))}evaluateQueryRenderedFeaturePadding(){let y=0;for(const u in this.buckets){const p=this.buckets[u];p.evaluateQueryRenderedFeaturePadding&&(y=Math.max(y,p.evaluateQueryRenderedFeaturePadding()))}return y}queryRenderedFeatures(y,u,p,_,C,M,L){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const O=this.evaluateQueryRenderedFeaturePadding(),U=function(W,J){const se=$([],[.5*W.width,.5*-W.height,1]);return A(se,se,[1,-1,0]),T(se,se,W.calculateProjMatrix(J.toUnwrapped())),Float32Array.from(se)}(C,this.tileID);return this.latestFeatureIndex.query(y,{tilespaceGeometry:u,pixelPosMatrix:U,transform:_,availableImages:p,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:O,scope:L})}querySourceFeatures(y,u){const p=this.latestFeatureIndex;if(!p||!p.rawTileData)return;const _=p.loadVTLayers(),C=u?u.sourceLayer:"",M=_._geojsonTileLayer||_[C];if(!M)return;const L=GT(u&&u.filter),{z:O,x:U,y:W}=this.tileID.canonical,J={z:O,x:U,y:W};for(let se=0;sep)_=!1;else if(u)if(this.expirationTimep.appearances&&p.appearances.length>0))return!0;return!1}updateBuckets(y,u,p,_,C,M){if(!this.latestFeatureIndex||!y.style)return;const L=M||y.style.listImages(),O=y.style.getBrightness(),U=C||new Set;for(const W in this.buckets){if(!y.style.hasLayer(W))continue;const J=this.buckets[W],se=J.layers[0],re=se.sourceLayer||"_geojsonTileLayer",fe=y.style.getLayerSourceCache(se),xe=J.layers.some(ot=>U.has(ot.fqid)),we=(_||xe)&&J instanceof lg?y.style.getOwnLayer(W):void 0;let je=p&&p[re]||{};fe&&!p&&(je=fe._state.getState(re,void 0));const Be=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},Ye=Object.keys(je).length>0&&!u;J.hasAppearances=J.layers.some(ot=>ot.appearances&&ot.appearances.length>0);const Ue=Ye?J.stateDependentLayers:J.layers;if(Ye&&J.stateDependentLayers.length!==0||u||xe||_){const ot=this.latestFeatureIndex.loadVTLayers()[re];if(J.update(je,ot,L,Be,Ue,u,O,this.tileID.canonical),(_||xe)&&(!u||u&&J instanceof lg&&(!J.text.uboBinder||J.text.uboBinder.isLightConstant||!J.icon.uboBinder||J.icon.uboBinder.isLightConstant))&&J instanceof lg&&we&&we.type==="symbol"){const pt=J;pt.text&&pt.text.uboBinder&&pt.text.uboBinder.updateDynamicExpressions(we,ot,this.tileID.canonical,L,je,O),pt.icon&&pt.icon.uboBinder&&pt.icon.uboBinder.updateDynamicExpressions(we,ot,this.tileID.canonical,L,je,O)}if(J instanceof lg){const pt=J,Rt=y.context;pt.text&&pt.text.uboBinder&&pt.text.uboBinder.upload(Rt),pt.icon&&pt.icon.uboBinder&&pt.icon.uboBinder.upload(Rt)}}if(Ye&&J.stateDependentLayers.length!==0||u||J.hasAppearances){const ot={zoom:y.transform.zoom,pitch:y.transform.pitch,brightness:y.style.getBrightness()||0,worldview:y.worldview},pt=J.updateAppearances(this.tileID.canonical,je,L,ot,y.imageManager,Ye&&J.stateDependentLayers.length!==0);if(pt&&pt.hasUboChanges){const Rt=y.context;J instanceof lg&&J.text&&J.text.uboBinder&&J.text.uboBinder.upload(Rt),J instanceof lg&&J.icon&&J.icon.uboBinder&&J.icon.uboBinder.upload(Rt)}}(J instanceof H9||J instanceof w9)&&y._terrain&&y._terrain.enabled&&fe&&J.uploadPending()&&y._terrain._clearRenderCacheForTile(fe.id,this.tileID);const tt=y&&y.style&&y.style.getOwnLayer(W);tt&&(this.queryPadding=Math.max(this.queryPadding,tt.queryRadius(J)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;we--){const je=4*we,Be=jw[je+0],Ye=jw[je+1],Ue=jw[je+2],tt=jw[je+3],ot=Be+Ue>>1,pt=Ye+tt>>1,Rt=ot+pt-Ye,_t=pt+Be-ot,Et=Ye*Y0+Be,jt=tt*Y0+Ue,At=pt*Y0+ot,ns=Math.hypot((Z0[2*Et+0]+Z0[2*jt+0])/2-Z0[2*At+0],(Z0[2*Et+1]+Z0[2*jt+1])/2-Z0[2*At+1])>=16;Nw[At]=Nw[At]||(ns?1:0),we<1022&&(Nw[At]=Nw[At]||Nw[(Ye+_t>>1)*Y0+(Be+Rt>>1)]||Nw[(tt+_t>>1)*Y0+(Ue+Rt>>1)])}const J=new Y1,se=new Go;let re=0;function fe(we,je){const Be=je*Y0+we;return m$[Be]===0&&(J.emplaceBack(Z0[2*Be+0],Z0[2*Be+1],we*mr/cg,je*mr/cg),m$[Be]=++re),m$[Be]-1}function xe(we,je,Be,Ye,Ue,tt){const ot=we+Be>>1,pt=je+Ye>>1;if(Math.abs(we-Ue)+Math.abs(je-tt)>1&&Nw[pt*Y0+ot])xe(Ue,tt,we,je,ot,pt),xe(Be,Ye,Ue,tt,ot,pt);else{const Rt=fe(we,je),_t=fe(Be,Ye),Et=fe(Ue,tt);se.emplaceBack(Rt,_t,Et)}}return xe(0,0,cg,cg,cg,0),xe(cg,cg,0,0,0,cg),{vertices:J,indices:se}}(this.tileID.canonical,u);_=M.vertices,C=M.indices}else{_=new Y1,C=new Go;for(const{x:L,y:O}of p)_.emplaceBack(L,O,0,0);const M=Iu(_.int16.subarray(0,4*_.length),void 0,4);for(let L=0;L0&&(L=S(new Float64Array(16),u.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(y,_,u,C,L,M),this._makeGlobeTileDebugTextBuffer(y,_,u,C,L,M)}_globePoint(y,u,p,_,C,M,L){let O=Ln(y,u,p);if(M){const U=1<.5?re=-1:se<-.5&&(re=1);let fe=(y/mr+p.x)/U+re,xe=(u/mr+p.y)/U;fe=(fe-W)*_._pixelsPerMercatorPixel+W,xe=(xe-J)*_._pixelsPerMercatorPixel+J;const we=[fe*_.worldSize,xe*_.worldSize,0];rt(we,we,M),O=Ys(O,we,L)}return rt(O,O,C)}_makeGlobeTileDebugBorderBuffer(y,u,p,_,C,M){const L=new zf,O=new yy,U=new K1,W=(se,re,fe,xe,we)=>{const je=(fe-se)/(we-1),Be=(xe-re)/(we-1),Ye=L.length;for(let Ue=0;UeW*se+re;for(let se=0;se1)return!1;const p=u.getSource().maxzoom,_=1<1)return u;const C=_.getSource().maxzoom,M=1<{const O=this.getAtTileOffset(y,C,M,L),U=_.upVector(y.canonical,C.x,C.y);return Me(U,U,O*_.upVectorScale(y.canonical,u,p).metersToTile),U}}getForTilePoints(y,u,p,_){if(this.isUsingMockSource())return!1;const C=bE.create(this,y,_);return!!C&&(u.forEach(M=>{M[2]=this.exaggeration()*C.getElevationAt(M[0],M[1],p,!0)}),!0)}getMinMaxForTile(y){if(this.isUsingMockSource())return null;const u=this.findDEMTileFor(y);if(!u||!u.dem)return null;const p=u.dem.tree,_=u.tileID,C=1<0&&(_+=(y[C]-0)*(y[C]-0)),u[C]<0&&(_+=(0-u[C])*(0-u[C]));return _},c.cP=function(y){return y*y*y*y*y},c.cQ=VN,c.cR=45,c.cS=T6,c.cT=function(y,u,p){const _=Math.sqrt(y*y+u*u+p*p),C=_>0?Math.acos(p/_)*aa:0;let M=y!==0||u!==0?Math.atan2(-u,-y)*aa+90:0;return M<0&&(M+=360),[_,M,C]},c.cU=ae,c.cV=Po,c.cW=Jm,c.cX=me,c.cY=So,c.cZ=oe,c.c_=function(y){return[Math.pow(y[0],1/2.2),Math.pow(y[1],1/2.2),Math.pow(y[2],1/2.2)]},c.ca=Zt,c.cb=3,c.cc=2,c.cd=7,c.ce=6,c.cf=ve,c.cg=ne,c.ch=de,c.ci=0,c.cj=1,c.ck=4,c.cl=5,c.cm=hs,c.cn=F6,c.co=lPe,c.cp=qt,c.cq=Ir,c.cr=function(y,u,p,_,C,M,L,O,U){if(U.name==="globe")return Ir(y,u,new qt(p,_,C),!1);const W=ek({z:p,x:_,y:C},U);return new So([(M+W.x/W.scale)*u,u*(W.y/W.scale),L],[(M+W.x2/W.scale)*u,u*(W.y2/W.scale),O])},c.cs=function(y,u,p){return y[0]=Math.min(u[0],p[0]),y[1]=Math.min(u[1],p[1]),y[2]=Math.min(u[2],p[2]),y[3]=Math.min(u[3],p[3]),y},c.ct=function(y,u,p){return y[0]=Math.max(u[0],p[0]),y[1]=Math.max(u[1],p[1]),y[2]=Math.max(u[2],p[2]),y[3]=Math.max(u[3],p[3]),y},c.cu=function(y){const u=Math.round((y+45+360)%360/90)%4;return bt[u]},c.cv=vm,c.cw=Nt,c.cx=6,c.cy=function(y){const u=N(new Float64Array(16));T(u,y.pixelMatrix,y.globeMatrix);const p=[0,Qm,0],_=[0,Vf,0];return rt(p,p,u),rt(_,_,u),[p[0]>0&&p[0]<=y.width&&p[1]>0&&p[1]<=y.height&&!ai(y,new di(y.center.lat,90)),_[0]>0&&_[0]<=y.width&&_[1]>0&&_[1]<=y.height&&!ai(y,new di(y.center.lat,-90))]},c.cz=function(y,u){const{scale:p}=y.tileTransform,_=p*mr/(y.tileSize*Math.pow(2,u.zoom-y.tileID.overscaledZ+y.tileID.canonical.z)),C=u.inverseAdjustmentMatrix;return new Float32Array([C[0]*_,C[1]*_,C[2]*_,C[3]*_])},c.d=function(y){return Va.API_TILEJSON_REGEX.test(y)},c.d$=Yn,c.d0=k0e,c.d1=uPe,c.d2=V,c.d3=class{static calculate(y,u,p){const _=new Set,C=new Map,M=new Set,L=new Set;for(const U of Object.values(y))for(const[W,J]of Object.entries(U.floors)){M.add(W),J.isDefault&&L.add(W),J.conflicts&&C.set(W,J.conflicts);const se=W===u,re=J.connections&&u&&J.connections.has(u);(se||re)&&_.add(W)}const O=U=>{const W=C.get(U)||new Set;for(const J of _)if((C.get(J)||new Set).has(U)||W.has(J))return!0;return!1};if(p)for(const U of p)M.has(U)&&(O(U)||_.add(U));for(const U of L)_.has(U)||O(U)||_.add(U);return _}},c.d4=Z9,c.d5=q0e,c.d6=I1,c.d7=function(){return{API_URL:Va.API_URL,DRACO_URL:Va.DRACO_URL,MESHOPT_URL:Va.MESHOPT_URL,MESHOPT_SIMD_URL:Va.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Va.BUILDING_GEN_URL}},c.d8=i6,c.d9=oN,c.dA=rs,c.dB=Gi,c.dC=Mi,c.dD=Ps,c.dE=zf,c.dF=Go,c.dG=function(y,u){return[Math.pow(y[0],2.2)*u,Math.pow(y[1],2.2)*u,Math.pow(y[2],2.2)*u]},c.dH=x,c.dI=function(y,u){var p=Math.sin(u),_=Math.cos(u);return y[0]=_,y[1]=p,y[2]=0,y[3]=-p,y[4]=_,y[5]=0,y[6]=0,y[7]=0,y[8]=1,y},c.dJ=Re,c.dK=Ha,c.dL=Jn,c.dM=uo,c.dN=eve,c.dO=function(y,u){const p=[0,0,0];return rt(p,p,Tn(Js(u.canonical))),rt(p,p,y),p},c.dP=y=>({u_matrix:new $0(y),u_texsize:new Uf(y),u_pixels_to_tile_units:new fw(y),u_device_pixel_ratio:new wl(y),u_width_scale:new wl(y),u_floor_width_scale:new wl(y),u_image:new $N(y),u_units_to_pixels:new Uf(y),u_tile_units_to_pixels:new wl(y),u_alpha_discard_threshold:new wl(y),u_trim_offset:new Uf(y),u_trim_fade_range:new Uf(y),u_trim_gradient_mix_range:new Uf(y),u_trim_color:new T6(y),u_zbias_factor:new wl(y),u_tile_to_meter:new wl(y),u_ground_shadow_factor:new UN(y),u_pattern_transition:new wl(y)}),c.dQ=y=>({u_matrix:new $0(y),u_pixels_to_tile_units:new fw(y),u_device_pixel_ratio:new wl(y),u_width_scale:new wl(y),u_floor_width_scale:new wl(y),u_units_to_pixels:new Uf(y),u_dash_image:new $N(y),u_gradient_image:new $N(y),u_image_height:new wl(y),u_texsize:new Uf(y),u_tile_units_to_pixels:new wl(y),u_alpha_discard_threshold:new wl(y),u_trim_offset:new Uf(y),u_trim_fade_range:new Uf(y),u_trim_gradient_mix_range:new Uf(y),u_trim_color:new T6(y),u_zbias_factor:new wl(y),u_tile_to_meter:new wl(y),u_ground_shadow_factor:new UN(y)}),c.dR=y=>({u_camera_to_center_distance:new wl(y),u_extrude_scale:new fw(y),u_device_pixel_ratio:new wl(y),u_matrix:new $0(y),u_inv_rot_matrix:new $0(y),u_merc_center:new Uf(y),u_tile_id:new UN(y),u_zoom_transition:new wl(y),u_up_dir:new UN(y),u_emissive_strength:new wl(y)}),c.dS=sg,c.dT=n1t,c.dU=class{constructor(y,u,p,_){this.context=y,this.format=_,this.size=p,this.texture=y.gl.createTexture();const[C,M,L]=this.size,{gl:O}=y;O.bindTexture(O.TEXTURE_3D,this.texture),y.pixelStoreUnpackFlipY.set(!1),y.pixelStoreUnpack.set(1),y.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in u&&u.data&&O.texImage3D(O.TEXTURE_3D,0,this.format,C,M,L,0,x0e(this.format),g0e(this.format),u.data)}bind(y,u){const{context:p}=this,{gl:_}=p;_.bindTexture(_.TEXTURE_3D,this.texture),y!==this.minFilter&&(_.texParameteri(_.TEXTURE_3D,_.TEXTURE_MAG_FILTER,y),_.texParameteri(_.TEXTURE_3D,_.TEXTURE_MIN_FILTER,y),this.minFilter=y),u!==this.wrapS&&(_.texParameteri(_.TEXTURE_3D,_.TEXTURE_WRAP_S,u),_.texParameteri(_.TEXTURE_3D,_.TEXTURE_WRAP_T,u),this.wrapS=u)}destroy(){const{gl:y}=this.context;y.deleteTexture(this.texture),this.texture=null}},c.dV=wi,c.dW=(y,u,p,_,C,M)=>{const L=y.transform,O=L.projection.name==="globe";let U;if(M.paint.get("circle-pitch-alignment")==="map")if(O){const J=Ha(L.zoom,u.canonical)*L._pixelsPerMercatorPixel;U=Float32Array.from([J,0,0,J])}else U=L.calculatePixelsToTileUnitsMatrix(p);else U=new Float32Array([L.pixelsToGLUnits[0],0,0,L.pixelsToGLUnits[1]]);const W={u_camera_to_center_distance:y.transform.getCameraToCenterDistance(L.projection),u_matrix:y.translatePosMatrix(u.projMatrix,p,M.paint.get("circle-translate"),M.paint.get("circle-translate-anchor")),u_device_pixel_ratio:bd.devicePixelRatio,u_extrude_scale:U,u_inv_rot_matrix:Qo,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:M.paint.get("circle-emissive-strength")};if(O){W.u_inv_rot_matrix=_,W.u_merc_center=C,W.u_tile_id=[u.canonical.x,u.canonical.y,1<{const J=y.transform,se=J.pitch<15?TPe(.07,.7,Mt((14-J.zoom)/5,0,1)):.07,re=p.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:APe(y,u,p,_),u_texsize:u.imageAtlasTexture?u.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:J.calculatePixelsToTileUnitsMatrix(u),u_device_pixel_ratio:C,u_width_scale:M,u_floor_width_scale:L,u_image:0,u_tile_units_to_pixels:EPe(u,J),u_units_to_pixels:[1/J.pixelsToGLUnits[0],1/J.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:O,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(re?null:p.lut).toArray01(),u_zbias_factor:se,u_tile_to_meter:Jm(u.tileID.canonical,0),u_ground_shadow_factor:U,u_pattern_transition:W}},c.d_=(y,u,p,_,C,M,L,O,U,W)=>{const J=y.transform,se=J.calculatePixelsToTileUnitsMatrix(u),re=p.paint.get("line-trim-color-use-theme").constantOr("default")==="none",fe=J.pitch<15?TPe(.07,.7,Mt((14-J.zoom)/5,0,1)):.07;return{u_matrix:APe(y,u,p,_),u_pixels_to_tile_units:se,u_device_pixel_ratio:M,u_width_scale:L,u_floor_width_scale:O,u_units_to_pixels:[1/J.pixelsToGLUnits[0],1/J.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:C,u_texsize:IPe(p)&&u.lineAtlasTexture?u.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:EPe(u,y.transform),u_alpha_discard_threshold:0,u_trim_offset:U,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(re?null:p.lut).toArray01(),u_zbias_factor:fe,u_tile_to_meter:Jm(u.tileID.canonical,0),u_ground_shadow_factor:W}},c.da=It,c.db=In,c.dc=function(y){const u=y.indexOf(tg);return u>=0?y.slice(0,u):y},c.dd=jPe,c.de=function(y){return y.includes(tg)},c.df=function(y){const u=y.lastIndexOf(tg);return u>=0?y.slice(u+1):""},c.dg=function(y){const u=[],p=y.id;return p===void 0&&u.push({message:`layers.${p}: missing required property "id"`}),y.render===void 0&&u.push({message:`layers.${p}: missing required method "render"`}),y.renderingMode&&y.renderingMode!=="2d"&&y.renderingMode!=="3d"&&u.push({message:`layers.${p}: property "renderingMode" must be either "2d" or "3d"`}),u},c.dh=function(y,u,p,_){return y.type==="custom"?new ebt(y,u):new nbt[y.type](y,u,p,_)},c.di=Kr,c.dj=GT,c.dk=q7,c.dl=class extends sk{constructor(y,u){super(y._vectorTileFeature,y._z,y._x,y._y,y.id),y.state&&(this.state=Object.assign({},y.state)),this.target=u.target,this.namespace=u.namespace,u.properties&&(this.properties=u.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=y.source,this.sourceLayer=y.sourceLayer,this.layer=y.layer)}toJSON(){const y=super.toJSON();return y.target=this.target,y.namespace=this.namespace,y}},c.dm=qT,c.dn=function(y){return y({pluginStatus:oh,pluginURL:Ip}),qT.on("pluginStateChange",y),y},c.dp=r9,c.dq=class extends rg{constructor(y){super(y),this.current=new Float32Array(9)}set(y,u,p){if(!this.fetchUniformLocation(y,u))return;const _=this.current;for(let C=0;C<9;C++)if(p[C]!==_[C]){_.set(p),this.gl.uniformMatrix3fv(this.location,!1,_);break}}},c.dr=ut,c.ds=function(y,u,p){const _=Li(p.zoom),C=y.style.map._antialias,M=y.terrain&&y.terrain.exaggeration()>0;return _===0&&!C&&!M},c.dt=function(y){const u=y.pixelsPerMeter,p=u/ch(1,y.center.lat),_=N(new Float64Array(16));return A(_,_,[y.point.x,y.point.y,0]),P(_,_,[p,p,u]),Float32Array.from(_)},c.du=Rr,c.dv=function(y){const u=80.051129;y=Mt(y,-80.051129,u)/u*90;const p=Math.pow(Math.abs(Math.sin(We(y))),3);return Math.round(p*(iE.length-1))},c.dw=function(y,u,p,_){const C=u.getNorth(),M=u.getSouth(),L=u.getWest(),O=u.getEast(),U=1<0){const xe=180/_;v(fe,fe,[xe/W+1,0,0,0,xe/J+1,0,-.5*xe/se,.5*xe/re,1])}return fe[2]=U,fe[5]=y.x,fe[8]=y.y,fe},c.dx=Tn,c.dy=Js,c.dz=function(y,u,p){const _=N(new Float64Array(16)),C=(u/(1<d?(y[0]=u[0]/_,y[1]=u[1]/_,y[2]=u[2]/_):(y[0]=1,y[1]=0,y[2]=0),p},c.eB=nve,c.eC=U9,c.eD=$9,c.eE=[1,1,1],c.eF=bE,c.eG=function(y,u,p,_){var C=u[0],M=u[1],L=u[2],O=u[3];return y[0]=C+_*(p[0]-C),y[1]=M+_*(p[1]-M),y[2]=L+_*(p[2]-L),y[3]=O+_*(p[3]-O),y},c.eH=uE,c.eI=Bh,c.eJ=class{constructor(){this._updateTime=0,this._sourceIds=[],this._activeRegions=[],this._prevRegions=[],this._globalClipBounds={min:new us(1/0,1/0),max:new us(-1/0,-1/0)}}clear(){this._activeRegions.length>0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(y,u=!1){const p=wIe(new us(0,0),new us(mr,mr),y),_=[];if(u&&!o0e(p,this._globalClipBounds))return _;for(const C of this._activeRegions){if(C.hiddenByOverlap||!o0e(p,C))continue;const M=G0t(C.min,C.max,y);_.push({min:M.min,max:M.max,sourceId:this._sourceIds[C.priority],footprint:C.footprint,footprintTileId:C.tileId,order:C.order,clipMask:C.clipMask,clipScope:C.clipScope})}return _}setSources(y){this._setSources(y.map(u=>({getSourceId:()=>u.cache.id,getFootprints:()=>{const p=[];for(const _ of u.cache.getVisibleCoordinates()){const C=u.cache.getTile(_).buckets[u.layer];C&&C.updateFootprints(_.toUnwrapped(),p)}return p},getOrder:()=>u.order,getClipMask:()=>u.clipMask,getClipScope:()=>u.clipScope})))}_addSource(y){const u=y.getFootprints();if(u.length===0)return;const p=y.getOrder(),_=y.getClipMask(),C=y.getClipScope();for(const M of u){if(!M.footprint)continue;const L=wIe(M.footprint.min,M.footprint.max,M.id);this._activeRegions.push({min:L.min,max:L.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:M.id,footprint:M.footprint,order:p,clipMask:_,clipScope:C})}this._sourceIds.push(y.getSourceId())}_computeReplacement(){this._activeRegions.sort((u,p)=>u.priority-p.priority||N9(u.min,p.min)||N9(u.max,p.max)||u.order-p.order||u.clipMask-p.clipMask||function(_,C){const M=(L,O)=>L+O;return _.length-C.length||_.reduce(M,"").localeCompare(C.reduce(M,""))}(u.clipScope,p.clipScope));let y=this._activeRegions.length!==this._prevRegions.length;if(!y){let u=0;for(;!y&&u!==this._activeRegions.length;){const p=this._activeRegions[u],_=this._prevRegions[u];y=p.priority!==_.priority||!_Ie(p,_)||p.order!==_.order||p.clipMask!==_.clipMask||!pr(p.clipScope,_.clipScope),this._activeRegions[u].hiddenByOverlap=_.hiddenByOverlap,++u}}if(y){++this._updateTime;for(const p of this._activeRegions)p.order!==K6&&(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 u=p=>{const _=this._activeRegions;if(p>=_.length)return p;const C=_[p].priority;for(;p<_.length&&_[p].priority===C;)++p;return p};if(this._sourceIds.length>1){let p=0,_=u(p);for(;p!==_;){let C=p;const M=p;for(;C!==_;){const L=this._activeRegions[C];L.hiddenByOverlap=!1;for(let O=0;O=0;u--)this._addSource(y[u]);this._computeReplacement()}},c.eK=Y1,c.eL=o$,c.eM=yy,c.eN=K6,c.eO=class{constructor(y){this._createGrid(y),this._createPoles(y)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const y of this._poleSegments)y.destroy();for(const y of this._gridSegments)y.withSkirts.destroy(),y.withoutSkirts.destroy()}_fillGridMeshWithLods(y,u){const p=new zf,_=new Go,C=[],M=y+1+2,L=u[0]+1,O=u[0]+1+(1+u.length),U=(W,J,se)=>{let re=W===M-1?W-2:W===0?W:W-1;return re+=se?24575:0,[re,J]};for(let W=0;W>>=0,y=Math.imul(2747636419^y,2654435769)>>>0,y=Math.imul(y^y>>>16,2654435769)>>>0,(y=Math.imul(y^y>>>16,2654435769)>>>0)/4294967296},c.ee=z0,c.ef=$L,c.eg=tb,c.eh=$f,c.ei=zh,c.ej=J1t,c.ek=Wr,c.el=Ia,c.em=Zm,c.en=function(y,u){var p=Math.sin(u),_=Math.cos(u);return y[0]=_,y[1]=0,y[2]=-p,y[3]=0,y[4]=0,y[5]=1,y[6]=0,y[7]=0,y[8]=p,y[9]=0,y[10]=_,y[11]=0,y[12]=0,y[13]=0,y[14]=0,y[15]=1,y},c.eo=function(y,u){var p=Math.sin(u),_=Math.cos(u);return y[0]=1,y[1]=0,y[2]=0,y[3]=0,y[4]=0,y[5]=_,y[6]=p,y[7]=0,y[8]=0,y[9]=-p,y[10]=_,y[11]=0,y[12]=0,y[13]=0,y[14]=0,y[15]=1,y},c.ep=function(y,u){return y[0]=u[0],y[1]=u[1],y[2]=u[2],y[3]=u[4],y[4]=u[5],y[5]=u[6],y[6]=u[8],y[7]=u[9],y[8]=u[10],y},c.eq=Z1,c.er=w6,c.es=function(y,u,p,_,C){return Mt((y-u)/(p-u)*(C-_)+_,_,C)},c.et=Jt,c.eu=function(y,u){var p=u[0],_=u[1],C=u[2],M=u[3],L=u[4],O=u[5],U=u[6],W=u[7],J=u[8],se=J*L-O*W,re=-J*M+O*U,fe=W*M-L*U,xe=p*se+_*re+C*fe;return xe?(y[0]=se*(xe=1/xe),y[1]=(-J*_+C*W)*xe,y[2]=(O*_-C*L)*xe,y[3]=re*xe,y[4]=(J*p-C*U)*xe,y[5]=(-O*p+C*M)*xe,y[6]=fe*xe,y[7]=(-W*p+_*U)*xe,y[8]=(L*p-_*M)*xe,y):null},c.ev=2,c.ew=ze,c.ex=Ie,c.ey=K,c.ez=function(y,u){var p=new h(3);K(p,u);var _=1/p[0],C=1/p[1],M=1/p[2],L=u[0]*_,O=u[1]*C,U=u[2]*M,W=u[4]*_,J=u[5]*C,se=u[6]*M,re=u[8]*_,fe=u[9]*C,xe=u[10]*M,we=L+J+xe,je=0;return we>0?(je=2*Math.sqrt(we+1),y[3]=.25*je,y[0]=(se-fe)/je,y[1]=(re-U)/je,y[2]=(O-W)/je):L>J&&L>xe?(je=2*Math.sqrt(1+L-J-xe),y[3]=(se-fe)/je,y[0]=.25*je,y[1]=(O+W)/je,y[2]=(re+U)/je):J>xe?(je=2*Math.sqrt(1+J-L-xe),y[3]=(re-U)/je,y[0]=(O+W)/je,y[1]=.25*je,y[2]=(se+fe)/je):(je=2*Math.sqrt(1+xe-L-J),y[3]=(O-W)/je,y[0]=(re+U)/je,y[1]=(se+fe)/je,y[2]=.25*je),y},c.f=Gx,c.f0=function(y){const u=y.navigator?y.navigator.userAgent:null;return!!function(p){if(Pi==null){const _=p.navigator?p.navigator.userAgent:null;Pi=!!p.safari||!(!_||!(Je.test(_)||_.match("Safari")&&!_.match("Chrome")))}return Pi}(y)&&!(!u||!(u.match("Version/15.4")||u.match("Version/15.5")||u.match(Fe)))},c.f1=function(y,u){oy=y,ly=u},c.f2=ai,c.f3=zi,c.f4=function(y){const u=[0,0,0],p=N(new Float64Array(16));return T(p,y.pixelMatrix,y.globeMatrix),rt(u,u,p),new us(u[0],u[1])},c.f5=function(y,u){if(!y||!u)throw new Error("TileProvider name and URL are required");Va.TILE_PROVIDER_URLS[y]=bd.resolveURL(u)},c.f6=o6,c.f7=function(y,u,p=!1){if(oh===gm.deferred||oh===gm.loading||oh===gm.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Ip=bd.resolveURL(y),oh=gm.deferred,R0=u,ow(),p||F7()},c.f8=Lf,c.f9=Wm,c.fA=H9,c.fB=L6,c.fC=function(y){return y<=1?1:Math.pow(2,Math.floor(Math.log2(y)))},c.fD=f$,c.fE=V0,c.fF=function(y){let u=0;if(new Uint32Array(y,0,1)[0]!==tPe){const p=new Uint32Array(y,0,7),[,,_,C,M,L]=p;u=p.byteLength+C+M+L+M,(_!==y.byteLength||u>=y.byteLength)&&ra("Invalid b3dm header information.")}return aPe(y,u)},c.fG=function(y,u){const p=y.json.extensionsUsed&&y.json.extensionsUsed.includes("mbx_bvh"),_=k0e(y);for(const C of _){if(!p)for(const M of C.meshes)wvt(M);C.lights&&(C.lightMeshIndex=C.meshes.length,C.meshes.push(jvt(C.lights,u)))}return _},c.fH=h$,c.fI=ci,c.fJ=Pp,c.fK=gm,c.fL=function(y){Rf(),Np!=null&&Np.then(u=>{u.keys().then(p=>{for(let _=0;_ra(C.message))}).catch(p=>ra(p.message))}).catch(u=>ra(u.message))},c.fa=Dl,c.fb=function(y){const u=mm();if(!u)return;const p=u.delete(A1);y&&p.then(()=>y()).catch(y)},c.fc=Mr,c.fd=pu,c.fe=2,c.ff=gT,c.fg=ek,c.fh=Q1,c.fi=ZLe,c.fj=XLe,c.fk=NPe,c.fl=rb,c.fm="hd_road_elevation",c.fn=E,c.fo=$s,c.fp=w9,c.fq=ab,c.fr=z0e,c.fs=1,c.ft=lg,c.fu=function(y,u,p,_,C,M,L,O=1,U,W,J,se){y.createArrays(),y.tilePixelRatio=mr/(512*y.overscaling),y.compareText={},y.iconsNeedLinear=!1;const re=y.layers[0].layout,fe=y.layers[0]._unevaluatedLayout._values,xe={};xe.scaleFactor=O,xe.textSizeScaleRange=re.get("text-size-scale-range"),xe.iconSizeScaleRange=re.get("icon-size-scale-range");const[we,je]=xe.textSizeScaleRange,[Be,Ye]=xe.iconSizeScaleRange;xe.textScaleFactor=Mt(xe.scaleFactor,we,je),xe.iconScaleFactor=Mt(xe.scaleFactor,Be,Ye);const Ue=fe["text-size"],tt=fe["icon-size"];if(y.textSizeData.kind==="composite"){const{minZoom:jt,maxZoom:At}=y.textSizeData;xe.compositeTextSizes=[Ue.possiblyEvaluate(new fi(jt,{worldview:J}),M),Ue.possiblyEvaluate(new fi(At,{worldview:J}),M)]}if(y.iconSizeData.kind==="composite"){const{minZoom:jt,maxZoom:At}=y.iconSizeData;xe.compositeIconSizes=[tt.possiblyEvaluate(new fi(jt,{worldview:J}),M,se),tt.possiblyEvaluate(new fi(At,{worldview:J}),M,se)]}xe.layoutTextSize=Ue.possiblyEvaluate(new fi(L+1,{worldview:J}),M),xe.layoutIconSize=tt.possiblyEvaluate(new fi(L+1,{worldview:J}),M,se),xe.textMaxSize=Ue.possiblyEvaluate(new fi(18,{worldview:J}),M);const ot=re.get("symbol-placement"),pt=re.get("text-rotation-alignment")==="map"&&ot!=="point",Rt=re.get("text-size");let _t=!1;const Et=[];for(const jt of y.features){const At=re.get("text-font").evaluate(jt,{},M).join(","),ns=Rt.evaluate(jt,{},M)*xe.textScaleFactor,is=xe.layoutTextSize.evaluate(jt,{},M)*xe.textScaleFactor,xs=xe.layoutIconSize.evaluate(jt,{},M,se)*xe.iconScaleFactor,ks={horizontal:{},vertical:void 0},ws=jt.text;let Ks,ds=[0,0];if(ws){const ca=ws.toString(),dl=re.get("text-letter-spacing").evaluate(jt,{},M)*Oc,xi=re.get("text-line-height").evaluate(jt,{},M)*Oc,ei=P7(ca)?dl:0,Vi=re.get("text-anchor").evaluate(jt,{},M),Ro=re.get("text-variable-anchor");if(!Ro){const Fl=re.get("text-radial-offset").evaluate(jt,{},M);if(Fl)ds=cLe(Vi,[Fl*Oc,H0e]);else{const ic=re.get("text-offset").evaluate(jt,{},M);ds=[ic[0]*Oc,ic[1]*Oc]}}let Fc=pt?"center":re.get("text-justify").evaluate(jt,{},M);const eo=ot==="point",ul=eo?re.get("text-max-width").evaluate(jt,{},M)*Oc:1/0,ac=Fl=>{y.allowVerticalPlacement&&n6(ca)&&(ks.vertical=P0e(ws,u,p,C,At,ul,xi,Vi,Fl,ei,ds,rf.vertical,!0,is,ns,U,xe.textScaleFactor))};if(!pt&&Ro){const Fl=Fc==="auto"?Ro.map(pa=>G0e(pa)):[Fc];let ic=!1;for(let pa=0;paString.fromCharCode(+("0x"+p))))},c.k=du,c.l=function(y){return decodeURIComponent(atob(y).split("").map(u=>"%"+("00"+u.charCodeAt(0).toString(16)).slice(-2)).join(""))},c.m=P1,c.n=dN,c.o=bd,c.p=function(y,u){return S0(Object.assign(y,{method:"POST"}),u)},c.q=ii,c.r=Df,c.s=function(y){try{const u=self[y];return u.setItem("_mapbox_test_",1),u.removeItem("_mapbox_test_"),!0}catch{return!1}},c.t=u6,c.u=function(){return function y(u){return u?(u^Math.random()*(16>>u/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,y)}()},c.v=function(y){return!!y&&Na.test(y)},c.w=ra,c.x=class{constructor(y){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(y&&y.maxTextureMemoryMB?y.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(u=>{this.cache.delete(u),this.clearExpiredTextures()})}calculateTextureMemory(y){return y.image?Math.ceil(y.image.width*y.image.height*4*(y.patternPositions.size>0?1.33:1)):0}evictTexture(y){const u=this.textures.get(y);if(u){const p=this.calculateTextureMemory(y);u.destroy(),this.textures.delete(y),this.textureAccessTimes.delete(y),this.textureMemoryUsed-=p,y.uploaded=!1}}evictTexturesIfNeeded(y){for(;this.textureMemoryUsed+y>this.maxTextureMemory&&this.textures.size>0;){let u=null,p=1/0;for(const[_]of this.textures.entries()){const C=this.textureAccessTimes.get(_)||0;Cthis._layers[gr.id]),Gt=kt[0];if(Gt.visibility==="none")continue;const Mt=Gt.source||"";let Kt=this.familiesBySource[Mt];Kt||(Kt=this.familiesBySource[Mt]=Object.create(null));const Es=Gt.sourceLayer||"_geojsonTileLayer";let Ls=Kt[Es];Ls||(Ls=Kt[Es]=[]),Ls.push(kt)}}}const v=1*c.fe;class j{constructor(Fe){const We={},He=[];for(const Gt in Fe){const Mt=Fe[Gt],Kt=We[Gt]={};for(const Es in Mt.glyphs){const Ls=Mt.glyphs[+Es];if(!Ls||Ls.bitmap.width===0||Ls.bitmap.height===0)continue;const gr=Ls.metrics.localGlyph?v:1,qr={x:0,y:0,w:Ls.bitmap.width+2*gr,h:Ls.bitmap.height+2*gr};He.push(qr),Kt[Es]=qr}}const{w:bt,h:ut}=c.F(He),kt=new c.fd({width:bt||1,height:ut||1});for(const Gt in Fe){const Mt=Fe[Gt];for(const Kt in Mt.glyphs){const Es=Mt.glyphs[+Kt];if(!Es||Es.bitmap.width===0||Es.bitmap.height===0)continue;const Ls=We[Gt][Kt],gr=Es.metrics.localGlyph?v:1;c.fd.copy(Es.bitmap,kt,{x:0,y:0},{x:Ls.x+gr,y:Ls.y+gr},Es.bitmap)}}this.image=kt,this.positions=We}}function b(Je,Fe,We){Je[Fe]?We&&(Je[Fe].center=We):Je[Fe]={floorIds:new Set,center:We||[0,0],floors:{}}}function N(Je,Fe,We,He){for(const bt of Fe)b(Je,bt),Je[bt].floors[We]=He,Je[bt].floorIds.add(We)}function S(Je){return{id:Je.properties.id.toString(),center:[Je.properties.center_lon||0,Je.properties.center_lat||0]}}function T(Je,Fe){const We=Je.properties.id.toString(),He=!!Je.properties.is_default&&Je.properties.is_default,bt=Je.properties.connected_floor_ids?new Set(Je.properties.connected_floor_ids.toString().split(";")):new Set,ut=Je.properties.conflicted_floor_ids?new Set(Je.properties.conflicted_floor_ids.toString().split(";")):new Set,kt=Je.properties.structure_ids?new Set(Je.properties.structure_ids.toString().split(";")):new Set,Gt=Je.properties.name.toString(),Mt=Je.properties.z_index,Kt=function(Es,Ls){const gr=Es.loadGeometry();if(!gr||gr.length===0)return;const qr=gr.map(Xr=>Xr.map(Yn=>c.ff(Yn,Ls,Es.extent)));return qr.length===0?void 0:{type:"Polygon",coordinates:[qr[0]]}}(Je,Fe);return{id:We,isDefault:He,connections:bt,conflicts:ut,buildings:kt,name:Gt,zIndex:Mt,geometry:Kt}}function A(Je,Fe){return Fe.every(We=>Je.properties&&Je.properties[We]!=null)}function P(Je){return A(Je,["type","id","name"])&&Je.properties.type==="structure"}function D(Je){return A(Je,["type","id","name","z_index"])&&Je.properties.type==="floor"}c.fc(j,"GlyphAtlas");class B{constructor(Fe){this.tileID=new c.aU(Fe.tileID.overscaledZ,Fe.tileID.wrap,Fe.tileID.canonical.z,Fe.tileID.canonical.x,Fe.tileID.canonical.y),this.tileZoom=Fe.tileZoom,this.uid=Fe.uid,this.zoom=Fe.zoom,this.lut=Fe.lut,this.canonical=Fe.tileID.canonical,this.pixelRatio=Fe.pixelRatio,this.tileSize=Fe.tileSize,this.source=Fe.source,this.scope=Fe.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Fe.showCollisionBoxes,this.showElevationIdDebug=Fe.showElevationIdDebug,this.collectResourceTiming=!!Fe.request&&Fe.request.collectResourceTiming,this.promoteId=Fe.promoteId,this.renderSourceType=Fe.renderSourceType,this.tileTransform=c.fg(Fe.tileID.canonical,Fe.projection),this.projection=Fe.projection,this.worldview=Fe.worldview,this.localizableLayerIds=Fe.localizableLayerIds,this.brightness=Fe.brightness,this.extraShadowCaster=!!Fe.extraShadowCaster,this.tessellationStep=Fe.tessellationStep,this.scaleFactor=Fe.scaleFactor,this.worldview=Fe.worldview,this.indoor=Fe.indoor}parse(Fe,We,He,bt,ut,kt){this.status="parsing",this.data=Fe,this.collisionBoxArray=new c.fh;const Gt=new c.fi(Object.keys(Fe.layers).sort()),Mt=new c.fj(this.tileID,this.promoteId);Mt.bucketLayerIDs=[];const Kt={},Es=new c.fk(256,256),Ls={featureIndex:Mt,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Es,availableImages:He,brightness:this.brightness,scaleFactor:this.scaleFactor,showElevationIdDebug:this.showElevationIdDebug,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Ls.activeFloors=function(Yn,Qr,$s,Kr){const In=Qr.indoorState.activeFloorsVisible;if(!Qr.sourceLayers)return In?Qr.indoorState.activeFloors:void 0;const Ja=function(ki,Qi){if(!ki)return c.w("No source layers defined in indoor specification"),Qi;if(ki.size===0)return Qi;const Po=ki.difference(Qi);for(const ci of Po)c.w(`Missing source layer required in indoor specification: ${ci}`);return Qi.intersection(Qi)}(Qr.sourceLayers,new Set(Object.keys(Yn.layers))),yo=Qr.indoorState,ra=function(ki,Qi,Po,ci,za){const jo={};for(const Pi of Qi){const Lo=ki.layers[Pi];if(Lo)for(let rc=0;rc=ci.maxzoom||ci.visibility==="none")continue;z(Po,this.zoom,Ls.brightness,He,this.worldview,Ls.activeFloors);const za=()=>{const jo=Kt[ci.id]=ci.createBucket({index:Mt.bucketLayerIDs.length,layers:Po,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:yo,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:bt,worldview:this.worldview,localizable:ki,availableImages:He,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});Mt.bucketLayerIDs.push(Po.map(Pi=>c.t(Pi.id,Pi.scope))),jo.populate(ra,Ls,this.tileID.canonical,this.tileTransform)};if("prepare"in ci){const jo=ci.prepare().then(()=>za());gr.push(jo)}else za()}}const Xr=()=>{Es.trim();const Yn=!(!Ls.elevationFeatures||!Ls.elevationFeatures.some(ci=>ci.heightRange.min<0));let Qr,$s,Kr,In,Ja,yo,ra;const ki={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Qi=()=>{if(Qr)return this.status="done",kt(Qr);if(this.extraShadowCaster)this.status="done",kt(null,{buckets:Object.values(Kt).filter(ci=>!ci.isEmpty()),featureIndex:Mt,collisionBoxArray:null,hasTunnelGeometry:Yn,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Ls.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if($s&&Kr&&In&&ra){const za=new j($s),jo=new Map;for(const[Lo,rc]of Kr.entries()){const{imagePosition:dr}=c.fr(Lo,rc,c.fs);jo.set(Lo,dr)}const Pi={};for(const Lo in Kt){const rc=Kt[Lo];rc instanceof c.ft&&(z(rc.layers,this.zoom,Ls.brightness,He,this.worldview,Ls.activeFloors),Pi[Lo]=c.fu(rc,$s,za.positions,Kr,jo,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ja,this.worldview,He))}Ja.size||yo.size?this.rasterizeTask=ut.send("rasterizeImages",{scope:this.scope,iconTasks:Ja,patternTasks:yo},(Lo,rc)=>{if(!Lo)for(const[dr,Jn]of rc.entries())Kr.has(dr)&&Kr.set(dr,Object.assign(Kr.get(dr),{data:Jn})),In.has(dr)&&In.set(dr,Object.assign(In.get(dr),{data:Jn}));Po(Pi,za,void 0,ra)}):Po(Pi,za,void 0,ra)}},Po=(ci,za,jo,Pi)=>{const Lo=Kr.size>0||In.size>0,rc=Object.keys(ci).length>0;if(!Lo&&!rc)return this.status="done",void kt(null,{buckets:Object.values(Kt).filter(Jn=>!Jn.isEmpty()),featureIndex:Mt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Yn,glyphAtlasImage:za.image,lineAtlas:Es,imageAtlas:null,brightness:Ls.brightness});const dr=(Jn,uo)=>{for(const ll in Kt){const Va=Kt[ll];if(ll in ci)c.fz(Va,ci[ll],this.showCollisionBoxes,He,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Kr,uo);else if(Va.hasPattern&&(Va instanceof c.fA||Va instanceof c.fp||Va instanceof c.e3)){z(Va.layers,this.zoom,Ls.brightness,He,this.worldview,Ls.activeFloors);const Dl=Object.fromEntries(uo.patternPositions);Va.addFeatures(Ls,this.tileID.canonical,Dl,He,this.tileTransform,this.brightness)}}this.status="done",kt(null,{buckets:Object.values(Kt).filter(ll=>!ll.isEmpty()),featureIndex:Mt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Yn,glyphAtlasImage:za.image,lineAtlas:Es,imageAtlas:Jn,brightness:Ls.brightness})};if(Lo){const Jn=new Map,uo=c.fv(Kr,Jn),ll=c.fv(In,Jn),Va=new c.fw(uo,ll,Pi,this.lut,Jn);ut.send("checkAtlasCache",{descriptor:Va,scope:this.scope},(Dl,Wm)=>{let Lf,Gx;if(Dl&&c.w(`[Worker] Error checking atlas cache: ${Dl.message}`),Wm)Lf=new c.fx(Wm.sourceHash),Gx=Wm;else{const j0=new c.fy(Kr,In,this.lut,Pi);Lf=j0,Gx=j0}dr(Lf,Gx)})}else dr(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const ci=c.fo(Ls.glyphDependencies,Pi=>Object.keys(Pi).map(Number));Object.keys(ci).length?ut.send("getGlyphs",{uid:this.uid,stacks:ci},(Pi,Lo)=>{Qr||(Qr=Pi,$s=Lo,Qi())},void 0,!1,ki):$s={},ra=new Map;const za=Array.from(Ls.iconDependencies.keys()).map(Pi=>c.I.parse(Pi)),jo=Array.from(Ls.patternDependencies.keys()).map(Pi=>c.I.parse(Pi));za.length||jo.length?ut.send("getImages",{icons:za,patterns:jo,source:this.source,scope:this.scope,tileID:this.tileID},(Pi,Lo)=>{if(!Qr){Qr=Pi,Kr=new Map,In=new Map,Ja=this.updateImageMapAndGetImageTaskQueue(Kr,Lo.images,Ls.iconDependencies),yo=this.updateImageMapAndGetImageTaskQueue(In,Lo.images,Ls.patternDependencies);for(const[rc,dr]of Lo.versions.entries())ra.set(rc,dr);Qi()}},void 0,!1,ki):(Kr=new Map,In=new Map,Ja=new Map,yo=new Map)}if(Ls.elevationFeatures&&Ls.elevationFeatures.length>0){const ci=[];for(const jo of Object.values(Kt))if(jo instanceof c.fp){const Pi=jo.getUnevaluatedPortalGraph();Pi&&ci.push(Pi)}const za=c.fq.evaluate(ci);for(const jo of Object.values(Kt))if(jo instanceof c.fp){const Pi=Fe.layers[Gt.decode(jo.sourceLayerIndex)];jo.setEvaluatedPortalGraph(za,Pi,this.tileID.canonical,Ls.availableImages,Ls.brightness)}}Qi()};gr.length>0?Promise.allSettled(gr).then(Xr).catch(kt):Xr()}updateParameters(Fe){this.scaleFactor=Fe.scaleFactor,this.showCollisionBoxes=Fe.showCollisionBoxes,this.showElevationIdDebug=Fe.showElevationIdDebug,this.projection=Fe.projection,this.brightness=Fe.brightness,this.tileTransform=c.fg(Fe.tileID.canonical,Fe.projection),this.extraShadowCaster=Fe.extraShadowCaster,this.lut=Fe.lut,this.worldview=Fe.worldview,this.indoor=Fe.indoor}updateImageMapAndGetImageTaskQueue(Fe,We,He){const bt=new Map;for(const ut of We.keys()){const kt=He.get(ut)||[];for(const Gt of kt){const Mt=Gt.toString(),Kt=We.get(Gt.id.toString());Kt.usvg?bt.has(Mt)||(bt.set(Mt,Gt),Fe.set(Mt,Object.assign({},Kt))):Fe.set(Mt,Kt)}}return bt}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function z(Je,Fe,We,He,bt,ut){const kt=new c.ab(Fe,{brightness:We,worldview:bt,activeFloors:ut});for(const Gt of Je)Gt.recalculate(kt,He)}class F extends c.E{constructor({actor:Fe,layerIndex:We,availableImages:He,availableModels:bt,isSpriteLoaded:ut,tileProvider:kt,brightness:Gt,maxUniformBufferBindings:Mt,maxUniformBlockSizeDwords:Kt,disableSymbolUBO:Es}){super(),this.actor=Fe,this.layerIndex=We,this.availableImages=He,this.availableModels=bt,this.loadVectorData=c.aQ,this.tileProvider=kt,this.loading={},this.loaded={},this.deduped=new c.aL(Fe.scheduler),this.isSpriteLoaded=ut,this.scheduler=Fe.scheduler,this.brightness=Gt,this.maxUniformBufferBindings=Mt,this.maxUniformBlockSizeDwords=Kt,this.disableSymbolUBO=Es}loadTileData(Fe,We){if(!this.tileProvider)return this.loadVectorData(Fe,We);const He=new AbortController;return this.loadTileWithProvider(this.tileProvider,Fe,He,We),()=>He.abort()}async loadTileWithProvider(Fe,We,He,bt){const{z:ut,x:kt,y:Gt}=We.tileID.canonical;try{const Mt=await Fe.loadTile({z:ut,x:kt,y:Gt},{request:We.request,signal:He.signal});if(He.signal.aborted)return;if(Mt==null){const Es=new Error("Tile not found");return Es.status=404,bt(Es)}if(Mt.data==null)return bt(null,null);const Kt=new Map;Mt.expires&&Kt.set("expires",Mt.expires),Mt.cacheControl&&Kt.set("cache-control",Mt.cacheControl),bt(null,{rawData:Mt.data,responseHeaders:Kt})}catch(Mt){if(He.signal.aborted)return;bt(Mt instanceof Error?Mt:new Error(String(Mt)))}}loadTile(Fe,We){const He=Fe.uid,bt=Fe&&Fe.request,ut=bt&&bt.collectResourceTiming,kt=this.loading[He]=new B(Fe);kt.maxUniformBufferBindings=this.maxUniformBufferBindings,kt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,kt.disableSymbolUBO=this.disableSymbolUBO,kt.abort=this.loadTileData(Fe,(Gt,Mt)=>{const Kt=!this.loading[He];if(delete this.loading[He],kt.cancelRasterize(),Kt||Gt||!Mt)return kt.status="done",Kt||(this.loaded[He]=kt),We(Gt);const Es=Mt.rawData,Ls={},gr=c.aR(Mt.responseHeaders);gr&&gr.expires&&(Ls.expires=gr.expires),gr&&gr.cacheControl&&(Ls.cacheControl=gr.cacheControl),kt.vectorTile=Mt.vectorTile||new c.fB(new c.b2(Es));const qr=()=>{kt.parse(kt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Xr,Yn)=>{if(Xr||!Yn)return We(Xr);const Qr={};if(ut){const $s=d(bt);$s.length>0&&(Qr.resourceTiming=JSON.parse(JSON.stringify($s)))}We(null,Object.assign({rawTileData:Es.slice(0),responseHeaders:Mt.responseHeaders},Yn,Ls,Qr))})};this.isSpriteLoaded?qr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(qr,{type:"parseTile",renderSourceType:Fe.renderSourceType,zoom:Fe.tileZoom}):qr()}),this.loaded=this.loaded||{},this.loaded[He]=kt})}reloadTile(Fe,We){const He=this.loaded,bt=Fe.uid;if(He&&He[bt]){const ut=He[bt];ut.updateParameters(Fe);const kt=(Gt,Mt)=>{const Kt=ut.reloadCallback;Kt&&(delete ut.reloadCallback,ut.parse(ut.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Kt)),We(Gt,Mt)};ut.status==="parsing"?ut.reloadCallback=kt:ut.status==="done"&&(ut.vectorTile?ut.parse(ut.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,kt):kt())}else We(null,void 0)}abortTile(Fe,We){const He=Fe.uid,bt=this.loading[He];bt&&(bt.abort&&bt.abort(),delete this.loading[He]),We()}removeTile(Fe,We){const He=this.loaded,bt=Fe.uid;He&&He[bt]&&delete He[bt],We()}}class ${constructor(Fe){this.tileProvider=Fe.tileProvider,this.loading={}}loadTile(Fe,We){const He=Fe.uid;if(this.tileProvider){const ut=new AbortController;return this.loading[He]={cancel:()=>ut.abort()},void this.loadTileWithProvider(this.tileProvider,He,Fe,ut,We)}const{cancel:bt}=c.b4(Fe.request,(ut,kt,Gt)=>{const Mt=!this.loading[He];if(delete this.loading[He],Mt||ut||!kt)return We(ut);this.decodeTile(He,kt,Fe.encoding).then(Kt=>{const{expires:Es,cacheControl:Ls}=c.aR(Gt);We(null,Object.assign(Kt,{expires:Es,cacheControl:Ls}))}).catch(Kt=>We(Kt))});this.loading[He]={cancel:bt}}async decodeTile(Fe,We,He){const bt=await createImageBitmap(new Blob([new Uint8Array(We)],{type:"image/png"})),ut=1-(bt.width-c.fC(bt.width))/2,kt=ut<1,Gt=this.getImageData(bt,ut);return bt.close(),{dem:new c.fD(Fe,Gt,He,kt),borderReady:kt}}async loadTileWithProvider(Fe,We,He,bt,ut){const{z:kt,x:Gt,y:Mt}=He.tileID.canonical;try{const Kt=await Fe.loadTile({z:kt,x:Gt,y:Mt},{request:He.request,signal:bt.signal});if(bt.signal.aborted)return ut(null,null);if(Kt==null){const Ls=new Error("Tile not found");return Ls.status=404,ut(Ls)}if(Kt.data==null)return ut(null,null);const Es=await this.decodeTile(We,Kt.data,He.encoding);if(bt.signal.aborted)return ut(null,null);ut(null,Object.assign(Es,{expires:Kt.expires,cacheControl:Kt.cacheControl}))}catch(Kt){if(bt.signal.aborted||Kt instanceof DOMException&&Kt.name==="AbortError")return ut(null,null);ut(Kt instanceof Error?Kt:new Error(String(Kt)))}finally{delete this.loading[We]}}reloadTile(Fe,We){We(null,null)}abortTile(Fe,We){const He=Fe.uid,bt=this.loading[He];bt&&(bt.cancel(),delete this.loading[He]),We()}removeTile(Fe,We){We()}getImageData(Fe,We){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Fe.width,Fe.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Fe.width,this.offscreenCanvas.height=Fe.height,this.offscreenCanvasContext.drawImage(Fe,0,0,Fe.width,Fe.height);const He=this.offscreenCanvasContext.getImageData(-We,-We,Fe.width+2*We,Fe.height+2*We);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),He}}c.b1.setPbf(c.b2);class X{constructor(Fe){this._mrt=new c.b1(Fe.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Fe.uid,this.tileID=Fe.tileID,this.source=Fe.source}parse(Fe,We){const He=this._mrt;this.status="parsing",this._entireBuffer=Fe;try{He.parseHeader(Fe),this._isHeaderLoaded=!0;const bt=[];for(const ut in He.layers){const kt=He.getLayer(ut),Gt=kt.getDataRange(kt.getBandList()),Mt=He.createDecodingTask(Gt),Kt=Fe.slice(Gt.firstByte,Gt.lastByte+1),Es=c.b1.performDecoding(Kt,Mt).then(Ls=>Mt.complete(null,Ls)).catch(Ls=>Mt.complete(Ls,null));bt.push(Es)}Promise.allSettled(bt).then(()=>We(null,He)).catch(ut=>We(ut))}catch(bt){We(bt)}}}class K{constructor({actor:Fe}){this.actor=Fe,this.loading={},this.loaded={}}loadTile(Fe,We){const He=Fe.uid,bt=Fe.request,ut=this.loading[He]=new X(Fe),{cancel:kt}=c.b4(bt,(Gt,Mt,Kt)=>{const Es=!this.loading[He];if(delete this.loading[He],Es||Gt||!Mt)return ut.status="done",Es||(this.loaded[He]=ut),We(Gt);ut.parse(Mt,(Ls,gr)=>{if(Ls||!gr)return We(Ls);We(null,gr,Kt)}),this.loaded[He]=ut});ut.abort=kt}reloadTile(Fe,We){We(null,void 0)}abortTile(Fe,We){const He=Fe.uid,bt=this.loading[He];bt&&(bt.abort&&bt.abort(),delete this.loading[He]),We()}removeTile(Fe,We){const He=Fe.uid;this.loaded[He]&&delete this.loaded[He],We()}decodeRasterArray(Fe,We){c.b1.performDecoding(Fe.buffer,Fe.task).then(He=>We(null,He)).catch(He=>We(He))}}const Q=c.fE.prototype.toGeoJSON;class Y{constructor(Fe){this._feature=Fe,this.extent=c.ak,this.type=Fe.type,this.properties=Fe.tags,"id"in Fe&&!isNaN(Fe.id)&&(this.id=parseInt(Fe.id,10))}loadGeometry(){if(this._feature.type===1){const Fe=[];for(const We of this._feature.geometry)Fe.push([new c.P(We[0],We[1])]);return Fe}{const Fe=[];for(const We of this._feature.geometry){const He=[];for(const bt of We)He.push(new c.P(bt[0],bt[1]));Fe.push(He)}return Fe}}toGeoJSON(Fe,We,He){return Q.call(this,Fe,We,He)}}class ne{constructor(Fe,We){this.name=Fe,this.extent=c.ak,this.length=We.length,this._jsonFeatures=We}feature(Fe){return new Y(this._jsonFeatures[Fe])}}class de{constructor(Fe){this.layers={},this.extent=c.ak;for(const We of Object.keys(Fe))this.layers[We]=new ne(We,Fe[We])}}const ce=64/4096;class ae{constructor(){this.features=new Map}clear(){this.features.clear()}load(Fe=[],We){for(const He of Fe){const bt=He.id;if(bt==null)continue;let ut=this.features.get(bt);ut&&this.updateCache(ut,We),He.geometry?(ut=me(He),this.updateCache(ut,We),this.features.set(bt,ut)):this.features.delete(bt),this.updateCache(ut,We)}}updateCache(Fe,We){for(const{canonical:He,uid:bt}of Object.values(We)){const{z:ut,x:kt,y:Gt}=He;ie(Fe,Math.pow(2,ut),kt,Gt)&&delete We[bt]}}getTile(Fe,We,He){const bt=Math.pow(2,Fe),ut=[];for(const kt of this.features.values())ie(kt,bt,We,He)&&ut.push(Oe(kt,bt,We,He));return{features:ut}}getFeatures(){return[...this.features.values()]}}function ie({minX:Je,minY:Fe,maxX:We,maxY:He},bt,ut,kt){return Je<(ut+1+ce)/bt&&Fe<(kt+1+ce)/bt&&We>(ut-ce)/bt&&He>(kt-ce)/bt}function me(Je){const{id:Fe,geometry:We,properties:He}=Je;if(!We)return;if(We.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:bt,coordinates:ut}=We,kt={id:Fe,type:1,geometry:[],tags:He,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Gt=kt.geometry;if(bt==="Point")oe(ut,Gt,kt);else if(bt==="MultiPoint")for(const Mt of ut)oe(Mt,Gt,kt);else if(bt==="LineString")kt.type=2,ge(ut,Gt,kt);else if(bt==="MultiLineString")kt.type=2,be(ut,Gt,kt);else if(bt==="Polygon")kt.type=3,be(ut,Gt,kt,!0);else{if(bt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");kt.type=3;for(const Mt of ut)be(Mt,Gt,kt,!0)}return kt}function oe([Je,Fe],We,He){const bt=c.aG(Je);let ut=c.aJ(Fe);ut=ut<0?0:ut>1?1:ut,We.push(bt,ut),He.minX=Math.min(He.minX,bt),He.minY=Math.min(He.minY,ut),He.maxX=Math.max(He.maxX,bt),He.maxY=Math.max(He.maxY,ut)}function ge(Je,Fe,We,He=!1,bt=!1){const ut=[];for(const kt of Je)oe(kt,ut,We);Fe.push(ut),He&&function(kt,Gt){let Mt=0;for(let Kt=0,Es=kt.length,Ls=Es-2;Kt0===Gt)for(let Kt=0,Es=kt.length;Kt=kt&&Ls>=kt||(Kt>=kt?(Es+=Math.round(Xr*((kt-Kt)/qr)),Kt=kt):Ls>=kt&&(gr=Es+Math.round(Xr*((kt-Kt)/qr)),Ls=kt),Es>=kt&&gr>=kt||(Es>=kt?(Kt+=Math.round(qr*((kt-Es)/Xr)),Es=kt):gr>=kt&&(Ls=Kt+Math.round(qr*((kt-Es)/Xr)),gr=kt),Gt&&Kt===Gt.at(-1)[0]&&Es===Gt.at(-1)[1]||(Gt=[[Kt,Es]],bt.push(Gt)),Gt.push([Ls,gr])))))}}function Pe(Je,Fe,We,He,bt){const ut=(We-ce)/Fe,kt=(He-ce)/Fe,Gt=(We+1+ce)/Fe,Mt=(He+1+ce)/Fe;function Kt(gr,qr){let Xr=0;return grGt&&(Xr|=2),qrMt&&(Xr|=8),Xr}let Es=[];for(let gr=1;gr<=8;gr*=2){let qr=Je[Je.length-2],Xr=Je.at(-1),Yn=!(Kt(qr,Xr)&gr);for(let Qr=0;Qr>31}function ye(Je,Fe){const{geometry:We,type:He}=Je;let bt=0,ut=0;if(He===1){Fe.writeVarint(ze(1,We.length));for(const kt of We){const Gt=kt[0]-bt,Mt=kt[1]-ut;Fe.writeVarint(Te(Gt)),Fe.writeVarint(Te(Mt)),bt+=Gt,ut+=Mt}}else for(const kt of We){if(kt.length===0)continue;Fe.writeVarint(ze(1,1));const Gt=kt.length-(He===3?1:0);for(let Mt=0;MtJe},rt=Math.fround||(Re=new Float32Array(1),Je=>(Re[0]=+Je,Re[0]));var Re;class Qe{constructor(Fe){this.options=Object.assign(Object.create(ve),Fe),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Fe){const{log:We,minZoom:He,maxZoom:bt}=this.options;We&&console.time("total time");const ut=`prepare ${Fe.length} points`;We&&console.time(ut),this.points=Fe;const kt=[];for(let Mt=0;Mt=He;Mt--){const Kt=+Date.now();Gt=this.trees[Mt]=this._createTree(this._cluster(Gt,Mt)),We&&console.log("z%d: %d clusters in %dms",Mt,Gt.numItems,+Date.now()-Kt)}return We&&console.timeEnd("total time"),this}getClusters(Fe,We){let He=((Fe[0]+180)%360+360)%360-180;const bt=Math.max(-90,Math.min(90,Fe[1]));let ut=Fe[2]===180?180:((Fe[2]+180)%360+360)%360-180;const kt=Math.max(-90,Math.min(90,Fe[3]));if(Fe[2]-Fe[0]>=360)He=-180,ut=180;else if(He>ut){const Ls=this.getClusters([He,bt,180,kt],We),gr=this.getClusters([-180,bt,ut,kt],We);return Ls.concat(gr)}const Gt=this.trees[this._limitZoom(We)],Mt=Gt.range(nt(He),$t(kt),nt(ut),$t(bt)),Kt=Gt.data,Es=[];for(const Ls of Mt){const gr=this.stride*Ls;Es.push(Kt[gr+5]>1?Ke(Kt,gr,this.clusterProps):this.points[Kt[gr+3]])}return Es}getChildren(Fe){const We=this._getOriginId(Fe),He=this._getOriginZoom(Fe),bt="No cluster with the specified id.",ut=this.trees[He];if(!ut)throw new Error(bt);const kt=ut.data;if(We*this.stride>=kt.length)throw new Error(bt);const Gt=this.options.radius/(this.options.extent*Math.pow(2,He-1)),Mt=ut.within(kt[We*this.stride],kt[We*this.stride+1],Gt),Kt=[];for(const Es of Mt){const Ls=Es*this.stride;kt[Ls+4]===Fe&&Kt.push(kt[Ls+5]>1?Ke(kt,Ls,this.clusterProps):this.points[kt[Ls+3]])}if(Kt.length===0)throw new Error(bt);return Kt}getLeaves(Fe,We,He){const bt=[];return this._appendLeaves(bt,Fe,We=We||10,He=He||0,0),bt}getTile(Fe,We,He){const bt=this.trees[this._limitZoom(Fe)],ut=Math.pow(2,Fe),{extent:kt,radius:Gt}=this.options,Mt=Gt/kt,Kt=(He-Mt)/ut,Es=(He+1+Mt)/ut,Ls={features:[]};return this._addTileFeatures(bt.range((We-Mt)/ut,Kt,(We+1+Mt)/ut,Es),bt.data,We,He,ut,Ls),We===0&&this._addTileFeatures(bt.range(1-Mt/ut,Kt,1,Es),bt.data,ut,He,ut,Ls),We===ut-1&&this._addTileFeatures(bt.range(0,Kt,Mt/ut,Es),bt.data,-1,He,ut,Ls),Ls.features.length?Ls:null}getClusterExpansionZoom(Fe){let We=this._getOriginZoom(Fe)-1;for(;We<=this.options.maxZoom;){const He=this.getChildren(Fe);if(We++,He.length!==1)break;Fe=He[0].properties.cluster_id}return We}_appendLeaves(Fe,We,He,bt,ut){const kt=this.getChildren(We);for(const Gt of kt){const Mt=Gt.properties;if(Mt&&Mt.cluster?ut+Mt.point_count<=bt?ut+=Mt.point_count:ut=this._appendLeaves(Fe,Mt.cluster_id,He,bt,ut):ut1;let Es,Ls,gr;if(Kt)Es=Ce(We,Mt,this.clusterProps),Ls=We[Mt],gr=We[Mt+1];else{const Yn=this.points[We[Mt+3]];Es=Yn.properties;const[Qr,$s]=Yn.geometry.coordinates;Ls=nt(Qr),gr=$t($s)}const qr={type:1,geometry:[[Math.round(this.options.extent*(Ls*ut-He)),Math.round(this.options.extent*(gr*ut-bt))]],tags:Es};let Xr;Xr=Kt||this.options.generateId?We[Mt+3]:this.points[We[Mt+3]].id,Xr!==void 0&&(qr.id=Xr),kt.features.push(qr)}}_limitZoom(Fe){return Math.max(this.options.minZoom,Math.min(Math.floor(+Fe),this.options.maxZoom+1))}_cluster(Fe,We){const{radius:He,extent:bt,reduce:ut,minPoints:kt}=this.options,Gt=He/(bt*Math.pow(2,We)),Mt=Fe.data,Kt=[],Es=this.stride;for(let Ls=0;LsWe&&(Qr+=Mt[Kr+5])}if(Qr>Yn&&Qr>=kt){let $s,Kr=gr*Yn,In=qr*Yn,Ja=-1;const yo=(Ls/Es<<5)+(We+1)+this.points.length;for(const ra of Xr){const ki=ra*Es;if(Mt[ki+2]<=We)continue;Mt[ki+2]=We;const Qi=Mt[ki+5];Kr+=Mt[ki]*Qi,In+=Mt[ki+1]*Qi,Mt[ki+4]=yo,ut&&($s||($s=this._map(Mt,Ls,!0),Ja=this.clusterProps.length,this.clusterProps.push($s)),ut($s,this._map(Mt,ki)))}Mt[Ls+4]=yo,Kt.push(Kr/Qr,In/Qr,1/0,yo,-1,Qr),ut&&Kt.push(Ja)}else{for(let $s=0;$s1)for(const $s of Xr){const Kr=$s*Es;if(!(Mt[Kr+2]<=We)){Mt[Kr+2]=We;for(let In=0;In>5}_getOriginZoom(Fe){return(Fe-this.points.length)%32}_map(Fe,We,He){if(Fe[We+5]>1){const kt=this.clusterProps[Fe[We+6]];return He?Object.assign({},kt):kt}const bt=this.points[Fe[We+3]].properties,ut=this.options.map(bt);return He&&ut===bt?Object.assign({},ut):ut}}function Ke(Je,Fe,We){return{type:"Feature",id:Je[Fe+3],properties:Ce(Je,Fe,We),geometry:{type:"Point",coordinates:[(He=Je[Fe],360*(He-.5)),lt(Je[Fe+1])]}};var He}function Ce(Je,Fe,We){const He=Je[Fe+5],bt=He>=1e4?`${Math.round(He/1e3)}k`:He>=1e3?Math.round(He/100)/10+"k":He,ut=Je[Fe+6],kt=ut===-1?{}:Object.assign({},We[ut]);return Object.assign(kt,{cluster:!0,cluster_id:Je[Fe+3],point_count:He,point_count_abbreviated:bt})}function nt(Je){return Je/360+.5}function $t(Je){const Fe=Math.sin(Je*Math.PI/180),We=.5-.25*Math.log((1+Fe)/(1-Fe))/Math.PI;return We<0?0:We>1?1:We}function lt(Je){const Fe=(180-360*Je)*Math.PI/180;return 360*Math.atan(Math.exp(Fe))/Math.PI-90}function it(Je,Fe,We,He){let bt=He;const ut=Fe+(We-Fe>>1);let kt,Gt=We-Fe;const Mt=Je[Fe],Kt=Je[Fe+1],Es=Je[We],Ls=Je[We+1];for(let gr=Fe+3;grbt)kt=gr,bt=qr;else if(qr===bt){const Xr=Math.abs(gr-ut);XrHe&&(kt-Fe>3&&it(Je,Fe,kt,He),Je[kt+2]=bt,We-kt>3&&it(Je,kt,We,He))}function Nt(Je,Fe,We,He,bt,ut){let kt=bt-We,Gt=ut-He;if(kt!==0||Gt!==0){const Mt=((Je-We)*kt+(Fe-He)*Gt)/(kt*kt+Gt*Gt);Mt>1?(We=bt,He=ut):Mt>0&&(We+=kt*Mt,He+=Gt*Mt)}return kt=Je-We,Gt=Fe-He,kt*kt+Gt*Gt}function Ft(Je,Fe,We,He){const bt={id:Je??null,type:Fe,geometry:We,tags:He,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Fe==="Point"||Fe==="MultiPoint"||Fe==="LineString")at(bt,We);else if(Fe==="Polygon")at(bt,We[0]);else if(Fe==="MultiLineString")for(const ut of We)at(bt,ut);else if(Fe==="MultiPolygon")for(const ut of We)at(bt,ut[0]);return bt}function at(Je,Fe){for(let We=0;We0&&(kt+=He?(bt*Es-Kt*ut)/2:Math.sqrt(Math.pow(Kt-bt,2)+Math.pow(Es-ut,2))),bt=Kt,ut=Es}const Gt=Fe.length-3;Fe[2]=1,it(Fe,0,Gt,We),Fe[Gt+2]=1,Fe.size=Math.abs(kt),Fe.start=0,Fe.end=Fe.size}function Jt(Je,Fe,We,He){for(let bt=0;bt1?1:We}function dt(Je,Fe,We,He,bt,ut,kt,Gt){if(He/=Fe,ut>=(We/=Fe)&&kt=He)return null;const Mt=[];for(const Kt of Je){const Es=Kt.geometry;let Ls=Kt.type;const gr=bt===0?Kt.minX:Kt.minY,qr=bt===0?Kt.maxX:Kt.maxY;if(gr>=We&&qr=He)continue;let Xr=[];if(Ls==="Point"||Ls==="MultiPoint")Qt(Es,Xr,We,He,bt);else if(Ls==="LineString")yt(Es,Xr,We,He,bt,!1,Gt.lineMetrics);else if(Ls==="MultiLineString")Is(Es,Xr,We,He,bt,!1);else if(Ls==="Polygon")Is(Es,Xr,We,He,bt,!0);else if(Ls==="MultiPolygon")for(const Yn of Es){const Qr=[];Is(Yn,Qr,We,He,bt,!0),Qr.length&&Xr.push(Qr)}if(Xr.length){if(Gt.lineMetrics&&Ls==="LineString"){for(const Yn of Xr)Mt.push(Ft(Kt.id,Ls,Yn,Kt.tags));continue}Ls!=="LineString"&&Ls!=="MultiLineString"||(Xr.length===1?(Ls="LineString",Xr=Xr[0]):Ls="MultiLineString"),Ls!=="Point"&&Ls!=="MultiPoint"||(Ls=Xr.length===3?"Point":"MultiPoint"),Mt.push(Ft(Kt.id,Ls,Xr,Kt.tags))}}return Mt.length?Mt:null}function Qt(Je,Fe,We,He,bt){for(let ut=0;ut=We&&kt<=He&&fs(Fe,Je[ut],Je[ut+1],Je[ut+2])}}function yt(Je,Fe,We,He,bt,ut,kt){let Gt=ss(Je);const Mt=bt===0?ar:Er;let Kt,Es,Ls=Je.start;for(let Qr=0;QrWe&&(Es=Mt(Gt,$s,Kr,Ja,yo,We),kt&&(Gt.start=Ls+Kt*Es)):ra>He?ki=We&&(Es=Mt(Gt,$s,Kr,Ja,yo,We),Qi=!0),ki>He&&ra<=He&&(Es=Mt(Gt,$s,Kr,Ja,yo,He),Qi=!0),!ut&&Qi&&(kt&&(Gt.end=Ls+Kt*Es),Fe.push(Gt),Gt=ss(Je)),kt&&(Ls+=Kt)}let gr=Je.length-3;const qr=Je[gr],Xr=Je[gr+1],Yn=bt===0?qr:Xr;Yn>=We&&Yn<=He&&fs(Gt,qr,Xr,Je[gr+2]),gr=Gt.length-3,ut&&gr>=3&&(Gt[gr]!==Gt[0]||Gt[gr+1]!==Gt[1])&&fs(Gt,Gt[0],Gt[1],Gt[2]),Gt.length&&Fe.push(Gt)}function ss(Je){const Fe=[];return Fe.size=Je.size,Fe.start=Je.start,Fe.end=Je.end,Fe}function Is(Je,Fe,We,He,bt,ut){for(const kt of Je)yt(kt,Fe,We,He,bt,ut,!1)}function fs(Je,Fe,We,He){Je.push(Fe,We,He)}function ar(Je,Fe,We,He,bt,ut){const kt=(ut-Fe)/(He-Fe);return fs(Je,ut,We+(bt-We)*kt,1),kt}function Er(Je,Fe,We,He,bt,ut){const kt=(ut-We)/(bt-We);return fs(Je,Fe+(He-Fe)*kt,ut,1),kt}function Tr(Je,Fe){const We=[];for(let He=0;He0&&Fe.size<(bt?kt:He))return void(We.numPoints+=Fe.length/3);const Gt=[];for(let Mt=0;Mtkt)&&(We.numSimplified++,Gt.push(Fe[Mt],Fe[Mt+1])),We.numPoints++;bt&&function(Mt,Kt){let Es=0;for(let Ls=0,gr=Mt.length,qr=gr-2;Ls0===Kt)for(let Ls=0,gr=Mt.length;Ls24)throw new Error("maxZoom should be in the 0-24 range");if(We.promoteId&&We.generateId)throw new Error("promoteId and generateId cannot be used together.");let bt=function(ut,kt){const Gt=[];if(ut.type==="FeatureCollection")for(let Mt=0;Mt1&&console.time("creation"),qr=this.tiles[gr]=Sr(Fe,We,He,bt,Kt),this.tileCoords.push({z:We,x:He,y:bt}),Es)){Es>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",We,He,bt,qr.numFeatures,qr.numPoints,qr.numSimplified),console.timeEnd("creation"));const Qi=`z${We}`;this.stats[Qi]=(this.stats[Qi]||0)+1,this.total++}if(qr.source=Fe,ut==null){if(We===Kt.indexMaxZoom||qr.numPoints<=Kt.indexMaxPoints)continue}else{if(We===Kt.maxZoom||We===ut)continue;if(ut!=null){const Qi=ut-We;if(He!==kt>>Qi||bt!==Gt>>Qi)continue}}if(qr.source=null,Fe.length===0)continue;Es>1&&console.time("clipping");const Xr=.5*Kt.buffer/Kt.extent,Yn=.5-Xr,Qr=.5+Xr,$s=1+Xr;let Kr=null,In=null,Ja=null,yo=null,ra=dt(Fe,Ls,He-Xr,He+Qr,0,qr.minX,qr.maxX,Kt),ki=dt(Fe,Ls,He+Yn,He+$s,0,qr.minX,qr.maxX,Kt);Fe=null,ra&&(Kr=dt(ra,Ls,bt-Xr,bt+Qr,1,qr.minY,qr.maxY,Kt),In=dt(ra,Ls,bt+Yn,bt+$s,1,qr.minY,qr.maxY,Kt),ra=null),ki&&(Ja=dt(ki,Ls,bt-Xr,bt+Qr,1,qr.minY,qr.maxY,Kt),yo=dt(ki,Ls,bt+Yn,bt+$s,1,qr.minY,qr.maxY,Kt),ki=null),Es>1&&console.timeEnd("clipping"),Mt.push(Kr||[],We+1,2*He,2*bt),Mt.push(In||[],We+1,2*He,2*bt+1),Mt.push(Ja||[],We+1,2*He+1,2*bt),Mt.push(yo||[],We+1,2*He+1,2*bt+1)}}getTile(Fe,We,He){Fe=+Fe,We=+We,He=+He;const bt=this.options,{extent:ut,debug:kt}=bt;if(Fe<0||Fe>24)return null;const Gt=1<1&&console.log("drilling down to z%d-%d-%d",Fe,We,He);let Kt,Es=Fe,Ls=We,gr=He;for(;!Kt&&Es>0;)Es--,Ls>>=1,gr>>=1,Kt=this.tiles[xn(Es,Ls,gr)];return Kt&&Kt.source?(kt>1&&(console.log("found parent tile z%d-%d-%d",Es,Ls,gr),console.time("drilling down")),this.splitTile(Kt.source,Es,Ls,gr,Fe,We,He),kt>1&&console.timeEnd("drilling down"),this.tiles[Mt]?$r(this.tiles[Mt],ut):null):null}}function xn(Je,Fe,We){return 32*((1<Kt.tags&&"3d_elevation_id"in Kt.tags&&"source"in Kt.tags&&Kt.tags.source==="elevation",ut=He.features.filter(Kt=>bt(Kt));let kt={_geojsonTileLayer:He.features};ut.length>0&&(kt={_geojsonTileLayer:He.features.filter(Kt=>!bt(Kt)),hd_road_elevation:ut});const Gt=new de(kt),Mt=function(Kt){const Es=new c.b2;for(const Ls of Object.keys(Kt))Es.writeMessage(3,Ee,{name:Ls,features:Kt[Ls]});return Es.finish()}(kt).buffer;Fe(null,{vectorTile:Gt,rawData:Mt})}class pr extends F{constructor(Fe){super(Fe),this.loadVectorData=us,this._dynamicIndex=new ae}loadData(Fe,We){const He=Fe&&Fe.request,bt=He&&He.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Fe,(ut,kt)=>{if(ut||!kt)return We(ut);if(typeof kt!="object")return We(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`));{try{if(Fe.filter){const Mt=c.U(Fe.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Mt.result==="error")throw new Error(Mt.value.map(Kt=>`${Kt.key}: ${Kt.message}`).join(", "));kt.features=kt.features.filter(Kt=>Mt.value.evaluate({zoom:0},Kt))}Fe.dynamic?(kt.type==="Feature"&&(kt={type:"FeatureCollection",features:[kt]}),Fe.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(kt.features,this.loaded),Fe.cluster&&(kt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Fe.cluster?new Qe(function({superclusterOptions:Mt,clusterProperties:Kt}){if(!Kt||!Mt)return Mt;const Es={},Ls={},gr={accumulated:null,zoom:0},qr={properties:null},Xr=Object.keys(Kt);for(const Yn of Xr){const[Qr,$s]=Kt[Yn],Kr=c.U($s),In=c.U(typeof Qr=="string"?[Qr,["accumulated"],["get",Yn]]:Qr);Es[Yn]=Kr.value,Ls[Yn]=In.value}return Mt.map=Yn=>{qr.properties=Yn;const Qr={};for(const $s of Xr)Qr[$s]=Es[$s].evaluate(gr,qr);return Qr},Mt.reduce=(Yn,Qr)=>{qr.properties=Qr;for(const $s of Xr)gr.accumulated=Yn[$s],Yn[$s]=Ls[$s].evaluate(gr,qr)},Mt}(Fe)).load(kt.features):Fe.dynamic?this._dynamicIndex:function(Mt,Kt){return new Ur(Mt,Kt)}(kt,Fe.geojsonVtOptions)}catch(Mt){return We(Mt)}const Gt={};if(bt){const Mt=d(He);Mt&&(Gt.resourceTiming={},Gt.resourceTiming[Fe.source]=JSON.parse(JSON.stringify(Mt)))}We(null,Gt)}})}reloadTile(Fe,We){const He=this.loaded;return He&&He[Fe.uid]?Fe.partial?We(null,void 0):super.reloadTile(Fe,We):this.loadTile(Fe,We)}loadGeoJSON(Fe,We){if(Fe.request)c.m(Fe.request,We);else{if(typeof Fe.data!="string")return We(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return We(null,JSON.parse(Fe.data))}catch{return We(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Fe,We){try{We(null,this._geoJSONIndex.getClusterExpansionZoom(Fe.clusterId))}catch(He){We(He)}}getClusterChildren(Fe,We){try{We(null,this._geoJSONIndex.getChildren(Fe.clusterId))}catch(He){We(He)}}getClusterLeaves(Fe,We){try{We(null,this._geoJSONIndex.getLeaves(Fe.clusterId,Fe.limit,Fe.offset))}catch(He){We(He)}}}class Hr{constructor(Fe,We,He){this.tileID=new c.aU(Fe.tileID.overscaledZ,Fe.tileID.wrap,Fe.tileID.canonical.z,Fe.tileID.canonical.x,Fe.tileID.canonical.y),this.tileZoom=Fe.tileZoom,this.uid=Fe.uid,this.zoom=Fe.zoom,this.canonical=Fe.tileID.canonical,this.pixelRatio=Fe.pixelRatio,this.tileSize=Fe.tileSize,this.source=Fe.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Fe.projection,this.brightness=We,this.worldview=He}parse(Fe,We,He,bt){this.status="parsing";const ut=new c.aU(He.tileID.overscaledZ,He.tileID.wrap,He.tileID.canonical.z,He.tileID.canonical.x,He.tileID.canonical.y),kt=[],Gt=We.familiesBySource[He.source],Mt=new c.fj(ut,He.promoteId);Mt.bucketLayerIDs=[],Mt.is3DTile=!0,c.fF(Fe).then(Kt=>{const Es=Kt.json.extensionsUsed&&Kt.json.extensionsUsed.includes("MAPBOX_mesh_features")||Kt.json.asset.extras&&Kt.json.asset.extras.MAPBOX_mesh_features,Ls=Kt.json.extensionsUsed&&Kt.json.extensionsUsed.includes("EXT_meshopt_compression"),gr=new c.ab(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const qr in Gt)for(const Xr of Gt[qr]){const Yn=Xr[0];Mt.bucketLayerIDs.push(Xr.map(Kr=>c.t(Kr.id,Kr.scope))),Yn.recalculate(gr,[]);const Qr=c.fG(Kt,1/c.cW(He.tileID.canonical)),$s=new c.fH(Xr,Qr,ut,Es,Ls,this.brightness,Mt,this.worldview);Es||($s.needsUpload=!0),kt.push($s),$s.evaluate(Yn)}this.status="done",bt(null,{buckets:kt,featureIndex:Mt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Kt=>bt(new Error(Kt.message)))}}class aa{constructor({actor:Fe,layerIndex:We,availableImages:He,availableModels:bt,brightness:ut,worldview:kt}){this.actor=Fe,this.layerIndex=We,this.availableImages=He,this.availableModels=bt,this.brightness=ut,this.loading={},this.loaded={},this.worldview=kt}loadTile(Fe,We){const He=Fe.uid,bt=this.loading[He]=new Hr(Fe,this.brightness,this.worldview);c.b4(Fe.request,(ut,kt)=>{const Gt=!this.loading[He];return delete this.loading[He],Gt||ut?(bt.status="done",Gt||(this.loaded[He]=bt),We(ut)):kt&&kt.byteLength!==0?void bt.parse(kt,this.layerIndex,Fe,(Mt,Kt)=>{bt.status="done",this.loaded=this.loaded||{},this.loaded[He]=bt,Mt||!Kt?We(Mt):We(null,Kt)}):(bt.status="done",this.loaded[He]=bt,We())})}reloadTile(Fe,We){const He=this.loaded,bt=Fe.uid;if(He&&He[bt]){const ut=He[bt];ut.projection=Fe.projection,ut.brightness=Fe.brightness;const kt=(Gt,Mt)=>{ut.reloadCallback&&(delete ut.reloadCallback,this.loadTile(Fe,We)),We(Gt,Mt)};ut.status==="parsing"?ut.reloadCallback=kt:ut.status==="done"&&this.loadTile(Fe,We)}}abortTile(Fe,We){const He=Fe.uid;this.loading[He]&&delete this.loading[He],We()}removeTile(Fe,We){const He=this.loaded,bt=Fe.uid;He&&He[bt]&&delete He[bt],We()}}class Na{constructor(Fe){this.self=Fe,this.actor=new c.ap(Fe,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.c4({name:"mercator"}),this.workerSourceTypes={vector:F,geojson:pr,"raster-dem":$,"raster-array":K,"batched-model":aa},this.workerSources={},this.self.registerWorkerSource=(We,He)=>{if(this.workerSourceTypes[We])throw new Error(`Worker source with name "${We}" already registered.`);this.workerSourceTypes[We]=He},this.self.registerRTLTextPlugin=We=>{if(c.fJ.isParsed())throw new Error("RTL text plugin already registered.");c.fJ.setState({pluginStatus:c.fK.parsed,pluginURL:c.fJ.getPluginURL()}),c.fJ.applyArabicShaping=We.applyArabicShaping,c.fJ.processBidirectionalText=We.processBidirectionalText,c.fJ.processStyledBidirectionalText=We.processStyledBidirectionalText;for(const He of this.rtlPluginParsingListeners)He(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Fe,We,He){delete this.layerIndexes[Fe],delete this.availableImages[Fe],delete this.availableModels[Fe],delete this.workerSources[Fe],He()}checkIfReady(Fe,We,He){He()}setReferrer(Fe,We){this.referrer=We}spriteLoaded(Fe,We){this.isSpriteLoaded[Fe]||(this.isSpriteLoaded[Fe]={});const{scope:He,isLoaded:bt}=We;if(this.isSpriteLoaded[Fe][He]=bt,this.workerSources[Fe]&&this.workerSources[Fe][He])for(const ut in this.workerSources[Fe][He]){const kt=this.workerSources[Fe][He][ut];for(const Gt in kt){const Mt=kt[Gt];Mt instanceof F&&(Mt.isSpriteLoaded=bt,Mt.fire(new c.z("isSpriteLoaded")))}}}setImages(Fe,We,He){this.availableImages[Fe]||(this.availableImages[Fe]={});const{scope:bt,images:ut}=We;if(this.availableImages[Fe][bt]=ut,this.workerSources[Fe]&&this.workerSources[Fe][bt]){for(const kt in this.workerSources[Fe][bt]){const Gt=this.workerSources[Fe][bt][kt];for(const Mt in Gt)Gt[Mt].availableImages=ut}He()}else He()}setModels(Fe,{scope:We,models:He},bt){if(this.availableModels[Fe]||(this.availableModels[Fe]={}),this.availableModels[Fe][We]=He,this.workerSources[Fe]&&this.workerSources[Fe][We]){for(const ut in this.workerSources[Fe][We]){const kt=this.workerSources[Fe][We][ut];for(const Gt in kt)kt[Gt].availableModels=He}bt()}else bt()}setProjection(Fe,We){this.projections[Fe]=c.c4(We)}setBrightness(Fe,We,He){this.brightness=We,He()}setContextParams(Fe,We,He){this.maxUniformBufferBindings=We.maxBindingPoints,this.maxUniformBlockSizeDwords=We.maxUniformBlockSizeDwords,this.disableSymbolUBO=We.disableSymbolUBO,He()}setWorldview(Fe,We,He){this.worldview=We,He()}setLayers(Fe,We,He){this.getLayerIndex(Fe,We.scope).replace(We.layers,We.options),He()}updateLayers(Fe,We,He){this.getLayerIndex(Fe,We.scope).update(We.layers,We.removedIds,We.options),He()}loadTile(Fe,We,He){We.projection=this.projections[Fe]||this.defaultProjection,this.getWorkerSource(Fe,We).loadTile(We,He)}decodeRasterArray(Fe,We,He){this.getWorkerSource(Fe,We).decodeRasterArray(We,He)}reloadTile(Fe,We,He){We.projection=this.projections[Fe]||this.defaultProjection,this.getWorkerSource(Fe,We).reloadTile(We,He)}abortTile(Fe,We,He){this.getWorkerSource(Fe,We).abortTile(We,He)}removeTile(Fe,We,He){this.getWorkerSource(Fe,We).removeTile(We,He)}removeSource(Fe,We,He){if(!(this.workerSources[Fe]&&this.workerSources[Fe][We.scope]&&this.workerSources[Fe][We.scope][We.type]&&this.workerSources[Fe][We.scope][We.type][We.source]))return;const bt=this.workerSources[Fe][We.scope][We.type][We.source];delete this.workerSources[Fe][We.scope][We.type][We.source],bt.removeSource!==void 0?bt.removeSource(We,He):He()}loadTileProvider(Fe,We,He){c.aT(We.name,We.url).then(bt=>{const ut=new bt(We.options);return this.getWorkerSource(Fe,{type:We.type,source:We.source,scope:We.scope},ut),ut.load&&We.request?ut.load({request:We.request}):null}).then(bt=>He(null,bt)).catch(bt=>He(bt instanceof Error?bt:new Error(String(bt))))}async syncRTLPluginState(Fe,We,He){if(c.fJ.isParsed())return void He(null,!0);if(c.fJ.isParsing())return void this.rtlPluginParsingListeners.push(He);c.fJ.setState(We);const bt=c.fJ.getPluginURL();if(!c.fJ.isLoaded()||c.fJ.isParsed()||c.fJ.isParsing())He(null,!1);else{c.fJ.setState({pluginStatus:c.fK.parsing,pluginURL:bt});try{await import(bt),c.fJ.isParsed()?He(null,!0):this.rtlPluginParsingListeners.push(He)}catch(ut){c.fJ.setState({pluginStatus:c.fK.error,pluginURL:bt}),He(ut);for(const kt of this.rtlPluginParsingListeners)kt(ut);this.rtlPluginParsingListeners=[]}}}setConfig(Fe,We){Object.assign(c.g,We)}getAvailableImages(Fe,We){this.availableImages[Fe]||(this.availableImages[Fe]={});let He=this.availableImages[Fe][We];return He||(He=[]),He}getAvailableModels(Fe,We){this.availableModels[Fe]||(this.availableModels[Fe]={});let He=this.availableModels[Fe][We];return He||(He={}),He}getLayerIndex(Fe,We){this.layerIndexes[Fe]||(this.layerIndexes[Fe]={});let He=this.layerIndexes[Fe][We];return He||(He=this.layerIndexes[Fe][We]=new g,He.scope=We),He}getWorkerSource(Fe,We,He){const{type:bt,source:ut,scope:kt}=We,Gt=this.workerSources;if(Gt[Fe]||(Gt[Fe]={}),Gt[Fe][kt]||(Gt[Fe][kt]={}),Gt[Fe][kt][bt]||(Gt[Fe][kt][bt]={}),this.isSpriteLoaded[Fe]||(this.isSpriteLoaded[Fe]={}),Gt[Fe][kt][bt][ut])He&&(Gt[Fe][kt][bt][ut].tileProvider=He);else{const Mt={send:(Es,Ls,gr,qr,Xr,Yn)=>this.actor.send(Es,Ls,gr,Fe,Xr,Yn),scheduler:this.actor.scheduler},Kt=this.workerSourceTypes[bt];if(!Kt)throw new Error(`Unknown worker source type "${bt}".`);Gt[Fe][kt][bt][ut]=new Kt({actor:Mt,layerIndex:this.getLayerIndex(Fe,kt),availableImages:this.getAvailableImages(Fe,kt),availableModels:this.getAvailableModels(Fe,kt),isSpriteLoaded:this.isSpriteLoaded[Fe][kt],tileProvider:He,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Gt[Fe][kt][bt][ut]}enforceCacheSizeLimit(Fe,We){c.fL(We)}getWorkerPerformanceMetrics(Fe,We,He){He(void 0,void 0)}}return c.fI(self)&&(self.worker=new Na(self)),Na}),i(["./shared"],function(o){var c="3.24.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},h={mark(E){performance.mark(E)},measure(E,f,w){performance.measure(E,f,w)}};function m(E){const f=E.name.split("?")[0];return o.a(f)&&f.includes("mapbox-gl.js")?"javascript":o.a(f)&&f.includes("mapbox-gl.css")?"css":o.b(f)?"fontRange":o.c(f)?"sprite":o.i(f)?"style":o.d(f)?"tilejson":"other"}var x,g={},v=function(){if(x)return g;function E(I){return!f(I)}function f(I){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var q,V,Z=new Blob([""],{type:"text/javascript"}),te=URL.createObjectURL(Z);try{V=new Worker(te),q=!0}catch{q=!1}return V&&V.terminate(),URL.revokeObjectURL(te),q}()?function(){var q=document.createElement("canvas");q.width=q.height=1;var V=q.getContext("2d");if(!V)return!1;var Z=V.getImageData(0,0,1,1);return Z&&Z.width===q.width}()?(w[R=I&&I.failIfMajorPerformanceCaveat]===void 0&&(w[R]=function(q){var V,Z=function(te){var le=document.createElement("canvas"),pe=Object.create(E.webGLContextAttributes);return pe.failIfMajorPerformanceCaveat=te,le.getContext("webgl2",pe)}(q);if(!Z)return!1;try{V=Z.createShader(Z.VERTEX_SHADER)}catch{return!1}return!(!V||Z.isContextLost())&&(Z.shaderSource(V,"void main() {}"),Z.compileShader(V),Z.getShaderParameter(V,Z.COMPILE_STATUS)===!0)}(R)),w[R]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var R}x=1,g.supported=E,g.notSupportedReason=f;var w={};return E.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},g}();const j=/firefox/i,b=/macintosh/i;function N(E,f,w){const I=document.createElement(E);return f!=null&&(I.className=f),w&&w.appendChild(I),I}function S(E,f,w){const I=document.createElementNS("http://www.w3.org/2000/svg",E);for(const R of Object.keys(f))I.setAttributeNS(null,R,String(f[R]));return w&&w.appendChild(I),I}const T=typeof document<"u"?document.documentElement&&document.documentElement.style:null,A=T&&T.userSelect!==void 0?"userSelect":"WebkitUserSelect";let P;function D(){T&&A&&(P=T[A],T[A]="none")}function B(){T&&A&&(T[A]=P)}function z(E){E.preventDefault(),E.stopPropagation(),window.removeEventListener("click",z,!0)}function F(){window.addEventListener("click",z,!0),window.setTimeout(()=>{window.removeEventListener("click",z,!0)},0)}function $(E,f){const w=E.getBoundingClientRect();return Q(E,w,f)}function X(E,f){const w=E.getBoundingClientRect(),I=[];for(let R=0;Rthis._skuTokenExpiresAt}transformRequest(f,w){return this._transformRequestFn&&this._transformRequestFn(f,w)||{url:f}}normalizeStyleURL(f,w){if(!o.e(f))return f;const I=be(f);return I.params.push(`sdk=js-${c}`),I.path=`/styles/v1${I.path}`,this._makeAPIURL(I,this._customAccessToken||w)}normalizeGlyphsURL(f,w){if(!o.e(f))return f;const I=be(f);return I.path=`/fonts/v1${I.path}`,this._makeAPIURL(I,this._customAccessToken||w)}normalizeModelURL(f,w){if(!o.e(f))return f;const I=be(f);return I.path=`/models/v1${I.path}`,this._makeAPIURL(I,this._customAccessToken||w)}normalizeSourceURL(f,w,I,R){if(!o.e(f))return f;const q=be(f);return q.path=`/v4/${q.authority}.json`,q.params.push("secure"),I&&q.params.push(`language=${I}`),R&&q.params.push(`worldview=${R}`),this._makeAPIURL(q,this._customAccessToken||w)}normalizeIconsetURL(f,w){const I=be(f);return o.e(f)?(I.path=`/styles/v1${I.path}/iconset.pbf`,this._makeAPIURL(I,this._customAccessToken||w)):Oe(I)}normalizeSpriteURL(f,w,I,R){const q=be(f);return o.e(f)?(q.path=`/styles/v1${q.path}/sprite${w}${I}`,this._makeAPIURL(q,this._customAccessToken||R)):(q.path+=`${w}${I}`,Oe(q))}normalizeTileURL(f,w,I){if(this._isSkuTokenExpired()&&this._createSkuToken(),f&&!o.e(f))return f;const R=be(f);R.path=R.path.replace(ne,`${w||I&&R.authority!=="raster"&&I===512?"@2x":""}${o.k.supported?".webp":"$1"}`),R.authority==="raster"?R.path=`/${o.g.RASTER_URL_PREFIX}${R.path}`:R.authority==="rasterarrays"?R.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${R.path}`:R.authority==="3dtiles"?R.path=`/${o.g.TILES3D_URL_PREFIX}${R.path}`:(R.path=R.path.replace(de,"/"),R.path=`/${o.g.TILE_URL_VERSION}${R.path}`);const q=this._customAccessToken||function(V){for(const Z of V){const te=Z.match(ie);if(te)return te[1]}return null}(R.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&q&&this._skuToken&&R.params.push(`sku=${this._skuToken}`),this._makeAPIURL(R,q)}canonicalizeTileURL(f,w){const I=be(f);if(!ae.test(I.path)||!ce.test(I.path))return f;let R="mapbox://";I.path.startsWith("/raster/v1/")?R+=`raster/${I.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:I.path.startsWith("/rasterarrays/v1/")?R+=`rasterarrays/${I.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:R+=`tiles/${I.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let q=I.params;return w&&(q=q.filter(V=>!V.match(ie))),q.length&&(R+=`?${q.join("&")}`),R}canonicalizeTileset(f,w){const I=!!w&&o.e(w),R=[];for(const q of f.tiles||[])o.f(q)?R.push(this.canonicalizeTileURL(q,I)):R.push(q);return R}_makeAPIURL(f,w){const I="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",R=be(o.g.API_URL);if(f.protocol=R.protocol,f.authority=R.authority,f.protocol==="http"){const q=f.params.indexOf("secure");q>=0&&f.params.splice(q,1)}if(R.path!=="/"&&(f.path=`${R.path}${f.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return Oe(f);if(w=w||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!w)throw new Error(`An API access token is required to use Mapbox GL. ${I}`);if(w[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${I}`)}return f.params=f.params.filter(q=>!q.includes("access_token")),f.params.push(`access_token=${w||""}`),Oe(f)}}const ge=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function be(E){const f=E.match(ge);if(!f)throw new Error("Unable to parse URL object");return{protocol:f[1],authority:f[2],path:f[3]||"/",params:f[4]?f[4].split("&"):[]}}function Oe(E){const f=E.params.length?`?${E.params.join("&")}`:"";return`${E.protocol}://${E.authority}${E.path}${f}`}const Me="mapbox.eventData";function Pe(E){if(!E)return null;const f=E.split(".");if(!f||f.length!==3)return null;try{return JSON.parse(o.l(f[1]))}catch{return null}}function Ee(E){return!(!o.g.EVENTS_URL||!E&&!o.g.ACCESS_TOKEN)}class $e{constructor(f){this.type=f,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(f){const w=Pe(o.g.ACCESS_TOKEN);let I="";return I=w&&w.u?o.j(w.u):o.g.ACCESS_TOKEN||"",f?`${Me}.${f}:${I}`:`${Me}:${I}`}fetchEventData(){const f=o.s("localStorage"),w=this.getStorageKey(),I=this.getStorageKey("uuid"),R=this.getStorageKey("uuidTimestamp");if(f)try{const q=localStorage.getItem(w);q&&(this.eventData=JSON.parse(q));const V=localStorage.getItem(I);V&&(this.anonId=V);const Z=localStorage.getItem(R);Z&&(this.anonIdTimestamp=Number(Z));const te=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(w,JSON.stringify(this.eventData)),V&&localStorage.setItem(R,V.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(f){}postEvent(f,w,I,R){if(!o.g.EVENTS_URL)return;const q=be(o.g.EVENTS_URL);q.params.push(`access_token=${R||o.g.ACCESS_TOKEN||""}`);const V={event:this.type,created:new Date(f).toISOString()},Z=w?Object.assign(V,w):V,te={url:Oe(q),headers:{"Content-Type":"text/plain"},body:JSON.stringify([Z])};this.pendingRequest=o.p(te,le=>{this.pendingRequest=null,I(le),this.saveEventData(),this.processRequests(R)})}queueRequest(f,w){this.queue.push(f),this.processRequests(w)}}class Se extends $e{constructor(f){super("metrics"),f&&(this.data=f)}postMetricsEvent(f){if(!Ee(f))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const w=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:w},f)}processRequests(f){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:I}=this.queue.shift();this.postEvent(w,I,()=>{},f)}}const ze=new class extends $e{constructor(E){super("appUserTurnstile"),this._customAccessToken=E}postTurnstileEvent(E,f){Ee(f)&&Array.isArray(E)&&E.some(w=>o.e(w)||o.f(w))&&this.queueRequest(Date.now(),f)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const f=Pe(o.g.ACCESS_TOKEN),w=f?f.u:o.g.ACCESS_TOKEN;let I=w!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),I=!0);const R=this.queue.shift();if(this.eventData.lastSuccess){const q=new Date(this.eventData.lastSuccess),V=new Date(R),Z=(R-this.eventData.lastSuccess)/864e5;I=I||Z>=1||Z<-1||q.getDate()!==V.getDate()}else I=!0;I?this.postEvent(R,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Y,"enabled.telemetry":!1,userId:this.anonId},q=>{q||(this.eventData.lastSuccess=R,this.eventData.tokenU=w)},E):this.processRequests()}},Te=ze.postTurnstileEvent.bind(ze),ye=new class extends $e{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(E,f,w,I){this.skuToken=f,this.errorCb=I,o.g.EVENTS_URL&&(w||o.g.ACCESS_TOKEN?this.queueRequest({id:E,timestamp:Date.now()},w):this.errorCb(new Error(me)))}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{id:f,timestamp:w}=this.queue.shift();f&&this.success[f]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(w,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Y,skuToken:this.skuToken,userId:this.anonId},I=>{I?this.errorCb(I):f&&(this.success[f]=!0)},E))}remove(){this.errorCb=null}},ct=ye.postMapLoadEvent.bind(ye),ve=new class extends $e{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(E){let f=this.mapInstanceIdMap.get(E);return f||(f=o.u(),this.mapInstanceIdMap.set(E,f)),f}getEventId(E){const f=this.eventIdPerMapInstanceMap.get(E)||0;return this.eventIdPerMapInstanceMap.set(E,f+1),f}postStyleLoadEvent(E,f){const{map:w,style:I,importedStyles:R}=f;if(!Ee(E))return;const q=this.getMapInstanceId(w),V={mapInstanceId:q,eventId:this.getEventId(q),style:I};R.length&&(V.importedStyles=R),this.queueRequest({timestamp:Date.now(),payload:V},E)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:f,payload:w}=this.queue.shift();this.postEvent(f,w,()=>{},E)}},rt=ve.postStyleLoadEvent.bind(ve),Re=new Se({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Qe=Re.postMetricsEvent.bind(Re),Ke=new Se({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Ce=Ke.postMetricsEvent.bind(Ke),nt=new class extends $e{constructor(){super("gljs.performance")}postPerformanceEvent(E,f){Ee(E)&&this.queueRequest({timestamp:Date.now(),performanceData:f},E)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:f,performanceData:w}=this.queue.shift(),I=function(R){const q=performance.getEntriesByType("resource"),V=performance.getEntriesByType("mark"),Z=function(Le){const Ve={};if(Le){for(const qe in Le)if(qe!=="other")for(const Ze of Le[qe]){const Xe=`${qe}ResolveRangeMin`,ht=`${qe}ResolveRangeMax`,vt=`${qe}RequestCount`,st=`${qe}RequestCachedCount`;Ve[Xe]=Math.min(Ve[Xe]||1/0,Ze.startTime),Ve[ht]=Math.max(Ve[ht]||-1/0,Ze.responseEnd);const Ut=Pt=>{Ve[Pt]===void 0&&(Ve[Pt]=0),++Ve[Pt]};Ze.transferSize!==void 0&&Ze.transferSize===0&&Ut(st),Ut(vt)}}return Ve}(function(Le,Ve){const qe={};if(Le)for(const Ze of Le){const Xe=Ve(Ze);qe[Xe]===void 0&&(qe[Xe]=[]),qe[Xe].push(Ze)}return qe}(q,m)),te=window.devicePixelRatio,le=navigator.connection||navigator.mozConnection||navigator.webkitConnection,pe=le?le.effectiveType:void 0,Ae={counters:[],metadata:[],attributes:[]},_e=(Le,Ve,qe)=>{qe!=null&&Le.push({name:Ve,value:qe.toString()})};for(const Le in Z)_e(Ae.counters,Le,Z[Le]);if(R.interactionRange[0]!==1/0&&R.interactionRange[1]!==-1/0&&(_e(Ae.counters,"interactionRangeMin",R.interactionRange[0]),_e(Ae.counters,"interactionRangeMax",R.interactionRange[1])),V)for(const Le of Object.values(d)){const Ve=V.find(qe=>qe.name===Le);Ve&&_e(Ae.counters,Le,Ve.startTime)}return _e(Ae.counters,"visibilityHidden",R.visibilityHidden),_e(Ae.attributes,"style",function(Le){if(Le)for(const Ve of Le){const qe=Ve.name.split("?")[0];if(o.i(qe)){const Ze=qe.split("/").slice(-2);if(Ze.length===2)return`mapbox://styles/${Ze[0]}/${Ze[1]}`}}}(q)),_e(Ae.attributes,"terrainEnabled",R.terrainEnabled?"true":"false"),_e(Ae.attributes,"fogEnabled",R.fogEnabled?"true":"false"),_e(Ae.attributes,"projection",R.projection),_e(Ae.attributes,"zoom",R.zoom),_e(Ae.metadata,"devicePixelRatio",te),_e(Ae.metadata,"connectionEffectiveType",pe),_e(Ae.metadata,"navigatorUserAgent",navigator.userAgent),_e(Ae.metadata,"screenWidth",window.screen.width),_e(Ae.metadata,"screenHeight",window.screen.height),_e(Ae.metadata,"windowWidth",window.innerWidth),_e(Ae.metadata,"windowHeight",window.innerHeight),_e(Ae.metadata,"mapWidth",R.width/te),_e(Ae.metadata,"mapHeight",R.height/te),_e(Ae.metadata,"webglRenderer",R.renderer),_e(Ae.metadata,"webglVendor",R.vendor),_e(Ae.metadata,"sdkVersion",c),_e(Ae.metadata,"sdkIdentifier","mapbox-gl-js"),Ae}(w);for(const R of I.metadata);for(const R of I.counters);for(const R of I.attributes);this.postEvent(f,I,()=>{},E)}},$t=nt.postPerformanceEvent.bind(nt),lt=new class extends $e{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(E,f,w,I){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const R=be(o.g.API_URL+o.g.SESSION_PATH);R.params.push(`sku=${f||""}`),R.params.push(`access_token=${I||o.g.ACCESS_TOKEN||""}`);const q={url:Oe(R),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(q,V=>{this.pendingRequest=null,w(V),this.saveEventData(),this.processRequests(I)})}getSessionAPI(E,f,w,I){this.skuToken=f,this.errorCb=I,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(w||o.g.ACCESS_TOKEN?this.queueRequest({id:E,timestamp:Date.now()},w):this.errorCb(new Error(me)))}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{id:f,timestamp:w}=this.queue.shift();f&&this.success[f]||this.getSession(w,this.skuToken,I=>{I?this.errorCb(I):f&&(this.success[f]=!0)},E)}remove(){this.errorCb=null}},it=lt.getSessionAPI.bind(lt),Nt=new Set;function Ft(E,f){f?Nt.add(E):Nt.delete(E)}class at{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(f,w){this._updatedSourceCaches[f]=w,this.setDirty()}discardSourceCacheUpdate(f){delete this._updatedSourceCaches[f]}updateLayer(f){const w=f.scope;this._updatedLayers[w]=this._updatedLayers[w]||new Set,this._updatedLayers[w].add(f.id),this.setDirty()}removeLayer(f){const w=f.scope;this._removedLayers[w]=this._removedLayers[w]||{},this._updatedLayers[w]=this._updatedLayers[w]||new Set,this._removedLayers[w][f.id]=f,this._updatedLayers[w].delete(f.id),this._updatedPaintProps.delete(f.fqid),this.setDirty()}getRemovedLayer(f){return this._removedLayers[f.scope]?this._removedLayers[f.scope][f.id]:null}discardLayerRemoval(f){this._removedLayers[f.scope]&&delete this._removedLayers[f.scope][f.id]}getLayerUpdatesByScope(){const f={};for(const w in this._updatedLayers)f[w]=f[w]||{},f[w].updatedIds=Array.from(this._updatedLayers[w].values());for(const w in this._removedLayers)f[w]=f[w]||{},f[w].removedIds=Object.keys(this._removedLayers[w]);return f}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(f){this._updatedPaintProps.add(f.fqid),this.setDirty()}getUpdatedImages(f){return this._updatedImages[f]?Array.from(this._updatedImages[f].values()):[]}updateImage(f,w){this._updatedImages[w]=this._updatedImages[w]||new Set,this._updatedImages[w].add(o.I.toString(f)),this.setDirty()}resetUpdatedImages(f){this._updatedImages[f]&&this._updatedImages[f].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ie(E){const{userImage:f}=E;return!!(f&&f.render&&f.render())&&(E.data.replace(new Uint8Array(f.data.buffer)),!0)}const et=new o.C(0,0,0);function Dt(E,f,w){E===1&&f.icons.push(function(I,R){return function(q){if(q.usvg_tree.height||(q.usvg_tree.height=q.usvg_tree.width),!q.metadata)return q;const{metadata:V}=q;if(V.content_area){const{content_area:Z}=V;Z.left==null&&(Z.left=0),Z.top==null&&(Z.top=Z.left),Z.width==null&&(Z.width=q.usvg_tree.width),Z.height==null&&(Z.height=Z.width)}if(V.text_placeholder){const{text_placeholder:Z}=V;Z.top==null&&(Z.top=Z.left),Z.height==null&&(Z.height=Z.width)}return V.stretch_x&&V.stretch_x.length&&Jt(V,"x"),V.stretch_y&&V.stretch_y.length&&Jt(V,"y"),q}(I.readFields(cs,{name:void 0},R))}(w,w.readVarint()+w.pos))}function Jt(E,f){const w=[],I=E[`stretch_${f}`];let R=null;for(let q=0;q>16&255)/255,(E>>8&255)/255,(255&E)/255,1)}function Sr(E,f,w){E===1?(f.rgb_color=kr(w.readVarint()),f.paint="rgb_color"):E===2?(f.linear_gradient_idx=w.readVarint(),f.paint="linear_gradient_idx"):E===3?(f.radial_gradient_idx=w.readVarint(),f.paint="radial_gradient_idx"):E===5?w.readPackedFloat(f.dasharray):E===6?f.dashoffset=w.readFloat():E===7?f.miterlimit=w.readFloat():E===8?f.opacity=w.readVarint():E===9?f.width=w.readFloat():E===10?f.linecap=w.readVarint():E===11&&(f.linejoin=w.readVarint())}function hn(E,f,w){E===1?f.transform=Er(w,w.readVarint()+w.pos):E===2?f.spread_method=w.readVarint():E===3?f.stops.push(zn(w,w.readVarint()+w.pos)):E===4?f.x1=w.readFloat():E===5?f.y1=w.readFloat():E===6?f.x2=w.readFloat():E===7&&(f.y2=w.readFloat())}function zn(E,f){return E.readFields(Xs,{offset:0,opacity:255,rgb_color:et},f)}function Xs(E,f,w){E===1?f.offset=w.readFloat():E===2?f.opacity=w.readVarint():E===3&&(f.rgb_color=kr(w.readVarint()))}function Ur(E,f,w){E===1?f.transform=Er(w,w.readVarint()+w.pos):E===2?f.spread_method=w.readVarint():E===3?f.stops.push(zn(w,w.readVarint()+w.pos)):E===4?f.cx=w.readFloat():E===5?f.cy=w.readFloat():E===6?f.r=w.readFloat():E===7?f.fx=w.readFloat():E===8?f.fy=w.readFloat():E===9&&(f.fr=w.readFloat())}function xn(E,f,w){E===1?f.transform=Er(w,w.readVarint()+w.pos):E===2?f.clip_path_idx=w.readVarint():E===3&&f.children.push(Is(w,w.readVarint()+w.pos))}function us(E,f,w){E===1?f.left=f.top=w.readFloat():E===2?f.width=f.height=w.readFloat():E===3?f.top=w.readFloat():E===4?f.height=w.readFloat():E===5?f.mask_type=w.readVarint():E===6?f.mask_idx=w.readVarint():E===7&&f.children.push(Is(w,w.readVarint()+w.pos))}class pr{static calculate(f={},w=[]){const I=new Map,R=new Map;if(Object.keys(f).length===0)return I;w.forEach(q=>{R.set(q.name,q.rgb_color||new o.C(0,0,0))});for(const[q,V]of Object.entries(f))R.has(q)?I.set(R.get(q).toString(),V):console.warn(`Ignoring unknown image variable "${q}"`);return I}}function Hr(E,f=255,w){const I=w.get(E.toString())||E;if(f===255)return I.toString();const R=I.clone();return R.a*=f/255,R.toString()}const aa=[];let Na=0;function Je(E,f){if(Na>=aa.length){const I=o.r()?new OffscreenCanvas(E,f):document.createElement("canvas");aa.push(I.getContext("2d",{willReadFrequently:!0}))}const w=aa[Na++];return w.canvas.width=E,w.canvas.height=f,w}function Fe(){Na--}function We(E,f,w,I,R){for(const q of I.children)He(E,f,w,q,R)}function He(E,f,w,I,R){I.group?(E.save(),function(q,V,Z,te,le){const pe=te.mask_idx!=null?Z.masks[te.mask_idx]:null,Ae=te.clip_path_idx!=null?Z.clip_paths[te.clip_path_idx]:null;if(te.transform&&(V=gr(te.transform).preMultiplySelf(V)),!function(Le,Ve,qe){return Le.opacity!==255||Ve||qe}(te,Ae!=null,pe!=null))return void We(q,V,Z,te,le);const _e=Je(q.canvas.width,q.canvas.height);We(_e,V,Z,te,le),Ae&&Es(_e,V,Z,Ae),pe&&Ls(_e,V,Z,pe,le),q.globalAlpha=te.opacity/255,q.drawImage(_e.canvas,0,0),Fe()}(E,f,w,I.group,R),E.restore()):I.path&&(E.save(),function(q,V,Z,te,le){q.setTransform(V),te.paint_order===1?(bt(q,Z,te,le),kt(q,Z,te,le)):(kt(q,Z,te,le),bt(q,Z,te,le))}(E,f,w,I.path,R),E.restore())}function bt(E,f,w,I){const R=w.fill;if(!R)return;const q=R.opacity/255;switch(E.save(),E.beginPath(),qr(w,E),R.paint){case"rgb_color":E.fillStyle=Hr(R.rgb_color,R.opacity,I);break;case"linear_gradient_idx":{const V=f.linear_gradients[R.linear_gradient_idx];V.transform&&E.setTransform(gr(V.transform).preMultiplySelf(E.getTransform())),E.fillStyle=Gt(E,V,q,I);break}case"radial_gradient_idx":{const V=f.radial_gradients[R.radial_gradient_idx];V.transform&&E.setTransform(gr(V.transform).preMultiplySelf(E.getTransform())),E.fillStyle=Mt(E,V,q,I)}}E.fill(ut(w)),E.restore()}function ut(E){return E.rule===1?"nonzero":E.rule===2?"evenodd":void 0}function kt(E,f,w,I){const R=w.stroke;if(!R)return;const q=Xr(w);E.lineWidth=R.width,E.miterLimit=R.miterlimit,E.setLineDash(R.dasharray),E.lineDashOffset=R.dashoffset;const V=R.opacity/255;switch(R.paint){case"rgb_color":E.strokeStyle=Hr(R.rgb_color,R.opacity,I);break;case"linear_gradient_idx":E.strokeStyle=Gt(E,f.linear_gradients[R.linear_gradient_idx],V,I,!0);break;case"radial_gradient_idx":E.strokeStyle=Mt(E,f.radial_gradients[R.radial_gradient_idx],V,I,!0)}switch(R.linejoin){case 2:case 1:E.lineJoin="miter";break;case 3:E.lineJoin="round";break;case 4:E.lineJoin="bevel"}switch(R.linecap){case 1:E.lineCap="butt";break;case 2:E.lineCap="round";break;case 3:E.lineCap="square"}E.stroke(q)}function Gt(E,f,w,I,R=!1){if(f.stops.length===1){const _e=f.stops[0];return Hr(_e.rgb_color,_e.opacity*w,I)}const{x1:q,y1:V,x2:Z,y2:te}=f;let le=new DOMPoint(q,V),pe=new DOMPoint(Z,te);if(R){const _e=gr(f.transform);le=_e.transformPoint(le),pe=_e.transformPoint(pe)}const Ae=E.createLinearGradient(le.x,le.y,pe.x,pe.y);for(const _e of f.stops)Ae.addColorStop(_e.offset,Hr(_e.rgb_color,_e.opacity*w,I));return Ae}function Mt(E,f,w,I,R=!1){if(f.stops.length===1){const Xe=f.stops[0];return Hr(Xe.rgb_color,Xe.opacity*w,I)}const q=gr(f.transform),{fx:V,fy:Z,fr:te,cx:le,cy:pe,r:Ae}=f;let _e=new DOMPoint(V,Z),Le=new DOMPoint(le,pe),Ve=te,qe=Ae;if(R){_e=q.transformPoint(_e),Le=q.transformPoint(Le);const Xe=(q.a+q.d)/2;Ve=te*Xe,qe=f.r*Xe}const Ze=E.createRadialGradient(_e.x,_e.y,Ve,Le.x,Le.y,qe);for(const Xe of f.stops)Ze.addColorStop(Xe.offset,Hr(Xe.rgb_color,Xe.opacity*w,I));return Ze}function Kt(E,f,w,I){const R=I.transform?gr(I.transform).preMultiplySelf(f):f,q=Je(E.canvas.width,E.canvas.height);for(const Z of I.children)if(Z.group)Kt(q,R,w,Z.group);else if(Z.path){const te=Z.path,le=new Path2D;le.addPath(Xr(te),R),q.fill(le,ut(te))}const V=I.clip_path_idx!=null?w.clip_paths[I.clip_path_idx]:null;V&&Es(q,R,w,V),E.globalCompositeOperation="source-over",E.drawImage(q.canvas,0,0),Fe()}function Es(E,f,w,I){const R=Je(E.canvas.width,E.canvas.height);Kt(R,f,w,I),E.globalCompositeOperation="destination-in",E.drawImage(R.canvas,0,0),Fe()}function Ls(E,f,w,I,R){if(I.children.length===0)return;const q=I.mask_idx!=null?w.masks[I.mask_idx]:null;q&&Ls(E,f,w,q,R);const V=E.canvas.width,Z=E.canvas.height,te=Je(V,Z),le=I.width,pe=I.height,Ae=I.left,_e=I.top,Le=new Path2D,Ve=new Path2D;Ve.rect(Ae,_e,le,pe),Le.addPath(Ve,f),te.clip(Le);for(const Xe of I.children)He(te,f,w,Xe,R);const qe=te.getImageData(0,0,V,Z),Ze=qe.data;if(I.mask_type===1)for(let Xe=0;Xeo.I.from(w))}getImageVersions(f){const w=this.imageVersions.get(f);if(w)return w}getImages(f,w,I){const R=[],q=[],V=this.imageProviders.get(w);for(const pe of f){if(!pe.iconsetId){R.push(pe);continue}const Ae=V.get(pe.iconsetId);Ae&&(this.getImage(pe,w)?q.push(pe):Ae.addPendingRequest(pe))}if(R.length===0)return void this._notify(q,w,I);let Z=!0;const te=!!this.loaded.get(w),le=this.images.get(w);if(!te)for(const pe of R)le.has(pe.toString())||(Z=!1);te||Z?this._notify(R,w,I):this.requestors.push({ids:R,scope:w,callback:I})}rasterizeImages(f,w){const I=new Map,{iconTasks:R,patternTasks:q,scope:V}=f;for(const Z of[R,q])for(const[te,le]of Z.entries()){const pe=this.getImage(le.id,V);pe&&I.set(te,{image:pe,imageVariant:le})}w(null,this._rasterizeImages(V,I))}_rasterizeImages(f,w){const I=new Map;for(const[R,{image:q,imageVariant:V}]of w.entries())I.set(R,this.imageRasterizer.rasterize(V,q,f,0));return I}getUpdatedImages(f){return this.updatedImages.get(f)||new Set}_notify(f,w,I){const R=this.images.get(w),q=new Map;for(const V of f){if(!R.get(V.toString())){if(V.iconsetId)continue;this.fire(new o.z("styleimagemissing",{id:V.name}))}const Z=R.get(V.toString());if(!Z){o.w(`Image "${V.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const te={data:Z.usvg?null:Z.data.clone(),pixelRatio:Z.pixelRatio,sdf:Z.sdf,usvg:Z.usvg,stretchX:Z.stretchX,stretchY:Z.stretchY,content:Z.content,hasRenderCallback:!!(Z.userImage&&Z.userImage.render)};Z.usvg&&Object.assign(te,{width:Z.icon.usvg_tree.width,height:Z.icon.usvg_tree.height}),q.set(o.I.toString(V),te)}I(null,{images:q,versions:this.getImageVersions(w)})}getPixelSize(f){const{width:w,height:I}=this.atlasImage.get(f);return{width:w,height:I}}getPattern(f,w,I){const R=f.toString(),q=this.patterns.get(w),V=q.get(R),Z=this.getImage(f,w);if(!Z)return null;if(V){if(V.position.version===Z.version)return V.position;V.position.version=Z.version}else{if(Z.usvg&&!Z.data){const te=this.getPatternInFlightId(R,w);if(this.patternsInFlight.has(te))return null;this.patternsInFlight.add(te);const le=new o.A(f).scaleSelf(o.o.devicePixelRatio),pe=new Map([[le.toString(),{image:Z,imageVariant:le}]]),Ae=this._rasterizeImages(w,pe);return this.storePatternImage(le,w,Z,I,Ae),null}this.storePattern(f,w,Z)}return this._updatePatternAtlas(w,I),q.get(R).position}getPatternInFlightId(f,w){return o.t(f,w)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(f,w,I,R,q){const V=f.toString(),Z=q?q.get(V):void 0;Z&&(I.data=Z,this.storePattern(f.id,w,I),this._updatePatternAtlas(w,R),this.patternsInFlight.delete(this.getPatternInFlightId(f.id.toString(),w)))}storePattern(f,w,I){const R={w:I.data.width+2*o.B,h:I.data.height+2*o.B,x:0,y:0},q=new o.D(R,I,o.B);this.patterns.get(w).set(f.toString(),{bin:R,position:q})}destroyAtlasTextures(){for(const f of this.atlasTexture.values())f&&f.destroy();this.atlasTexture.clear()}bind(f,w){const I=f.gl;let R=this.atlasTexture.get(w);R?this.dirty&&(R.update(this.atlasImage.get(w)),this.dirty=!1):(R=new o.T(f,this.atlasImage.get(w),I.RGBA8),this.atlasTexture.set(w,R)),R.bind(I.LINEAR,I.CLAMP_TO_EDGE)}_updatePatternAtlas(f,w){const I=this.patterns.get(f),R=Array.from(I.values()).map(({bin:le})=>le),{w:q,h:V}=o.F(R),Z=this.atlasImage.get(f);Z.resize({width:q||1,height:V||1});const te=this.images.get(f);for(const[le,{bin:pe,position:Ae}]of I.entries()){let _e=Ae.padding;const Le=pe.x+_e,Ve=pe.y+_e,qe=te.get(le).data,Ze=qe.width,Xe=qe.height;_e=_e>1?_e-1:_e,o.q.copy(qe,Z,{x:0,y:0},{x:Le,y:Ve},{width:Ze,height:Xe},w),o.q.copy(qe,Z,{x:0,y:Xe-_e},{x:Le,y:Ve-_e},{width:Ze,height:_e},w),o.q.copy(qe,Z,{x:0,y:0},{x:Le,y:Ve+Xe},{width:Ze,height:_e},w),o.q.copy(qe,Z,{x:Ze-_e,y:0},{x:Le-_e,y:Ve},{width:_e,height:Xe},w),o.q.copy(qe,Z,{x:0,y:0},{x:Le+Ze,y:Ve},{width:_e,height:Xe},w),o.q.copy(qe,Z,{x:Ze-_e,y:Xe-_e},{x:Le-_e,y:Ve-_e},{width:_e,height:_e},w),o.q.copy(qe,Z,{x:0,y:Xe-_e},{x:Le+Ze,y:Ve-_e},{width:_e,height:_e},w),o.q.copy(qe,Z,{x:0,y:0},{x:Le+Ze,y:Ve+Xe},{width:_e,height:_e},w),o.q.copy(qe,Z,{x:Ze-_e,y:0},{x:Le-_e,y:Ve+Xe},{width:_e,height:_e},w)}this.dirty=!0}beginFrame(){for(const f of this.images.keys())this.callbackDispatchedThisFrame.set(f,new Set)}dispatchRenderCallbacks(f,w){const I=this.images.get(w);for(const R of f){if(this.callbackDispatchedThisFrame.get(w).has(R.toString()))continue;this.callbackDispatchedThisFrame.get(w).add(R.toString());const q=I.get(R.toString());Ie(q)&&this.updateImage(R,w,q)}}}class $s{constructor(f,w,I,R){this.message=(f?`${f}: `:"")+I,R&&(this.identifier=R),w!=null&&w.__line__&&(this.line=w.__line__)}}class Kr extends $s{}function In(E){const f=E.value,w=E.valueSpec,I=E.style,R=E.styleSpec,q=E.key,V=E.arrayElementValidator||Do;if(!Array.isArray(f))return[new $s(q,f,`array expected, ${o.J(f)} found`)];if(w.length&&f.length!==w.length)return[new $s(q,f,`array length ${w.length} expected, length ${f.length} found`)];if(w["min-length"]&&f.lengthR)return[new $s(f,w,`${w} is greater than the maximum value ${R}`)]}return[]}function yo(E){const f=E.key,w=E.value;if(!o.G(w))return[new $s(f,w,`object expected, ${o.J(w)} found`)];const I=E.valueSpec,R=o.H(w.type);let q,V,Z,te={};const le=R!=="categorical"&&w.property===void 0,pe=!le,Ae=function(qe){const Ze=qe.stops;return Array.isArray(Ze)&&Array.isArray(Ze[0])&&o.G(Ze[0][0])}(w),_e=vd({key:E.key,value:E.value,valueSpec:E.styleSpec.function,style:E.style,styleSpec:E.styleSpec,objectElementValidators:{stops:function(qe){if(R==="identity")return[new $s(qe.key,qe.value,'identity function may not have a "stops" property')];let Ze=[];const Xe=qe.value;return Ze=Ze.concat(In({key:qe.key,value:Xe,valueSpec:qe.valueSpec,style:qe.style,styleSpec:qe.styleSpec,arrayElementValidator:Le})),Array.isArray(Xe)&&Xe.length===0&&Ze.push(new $s(qe.key,Xe,"array must have at least one stop")),Ze},default:function(qe){return Do({key:qe.key,value:qe.value,valueSpec:I,style:qe.style,styleSpec:qe.styleSpec})}}});return R==="identity"&&le&&_e.push(new $s(E.key,E.value,'missing required property "property"')),R==="identity"||w.stops||_e.push(new $s(E.key,E.value,'missing required property "stops"')),R==="exponential"&&I.expression&&!o.M(I)&&_e.push(new $s(E.key,E.value,"exponential functions not supported")),E.styleSpec.$version>=8&&(pe&&!o.N(I)?_e.push(new $s(E.key,E.value,"property functions not supported")):le&&!o.O(I)&&_e.push(new $s(E.key,E.value,"zoom functions not supported"))),R!=="categorical"&&!Ae||w.property!==void 0||_e.push(new $s(E.key,E.value,'"property" property is required')),_e;function Le(qe){let Ze=[];const Xe=qe.value,ht=qe.key;if(!Array.isArray(Xe))return[new $s(ht,Xe,`array expected, ${o.J(Xe)} found`)];if(Xe.length!==2)return[new $s(ht,Xe,`array length 2 expected, length ${Xe.length} found`)];if(Ae){if(!o.G(Xe[0]))return[new $s(ht,Xe,`object expected, ${o.J(Xe[0])} found`)];const vt=Xe[0];if(vt.zoom===void 0)return[new $s(ht,Xe,"object stop key must have zoom")];if(vt.value===void 0)return[new $s(ht,Xe,"object stop key must have value")];const st=o.H(vt.zoom);if(typeof st!="number")return[new $s(ht,vt.zoom,"stop zoom values must be numbers")];if(Z&&Z>st)return[new $s(ht,vt.zoom,"stop zoom values must appear in ascending order")];st!==Z&&(Z=st,V=void 0,te={}),Ze=Ze.concat(vd({key:`${ht}[0]`,value:Xe[0],valueSpec:{zoom:{}},style:qe.style,styleSpec:qe.styleSpec,objectElementValidators:{zoom:Ja,value:Ve}}))}else Ze=Ze.concat(Ve({key:`${ht}[0]`,value:Xe[0],style:qe.style,styleSpec:qe.styleSpec},Xe));return o.Q(o.S(Xe[1]))?Ze.concat([new $s(`${ht}[1]`,Xe[1],"expressions are not allowed in function stops.")]):Ze.concat(Do({key:`${ht}[1]`,value:Xe[1],valueSpec:I,style:qe.style,styleSpec:qe.styleSpec}))}function Ve(qe,Ze){const Xe=o.J(qe.value),ht=o.H(qe.value),vt=qe.value!==null?qe.value:Ze;if(q){if(Xe!==q)return[new $s(qe.key,vt,`${Xe} stop domain type must match previous stop domain type ${q}`)]}else q=Xe;if(Xe!=="number"&&Xe!=="string"&&Xe!=="boolean"&&typeof ht!="number"&&typeof ht!="string"&&typeof ht!="boolean")return[new $s(qe.key,vt,"stop domain value must be a number, string, or boolean")];if(Xe!=="number"&&R!=="categorical"){let st=`number expected, ${Xe} found`;return o.N(I)&&R===void 0&&(st+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new $s(qe.key,vt,st)]}return R!=="categorical"||Xe!=="number"||typeof ht=="number"&&isFinite(ht)&&Math.floor(ht)===ht?R!=="categorical"&&Xe==="number"&&typeof ht=="number"&&typeof V=="number"&&V!==void 0&&htnew $s(`${E.key}${I.key}`,E.value,I.message));const w=f.value.expression||f.value._styleExpression.expression;if(E.expressionContext==="property"&&E.propertyKey==="text-font"&&!w.outputDefined())return[new $s(E.key,E.value,`Invalid data expression for "${E.propertyKey}". Output values must be contained as literals within the expression.`)];if(E.expressionContext==="property"&&E.propertyType==="layout"&&!o.Y(w))return[new $s(E.key,E.value,'"feature-state" data expressions are not supported with layout properties.')];if(E.expressionContext==="filter")return ki(w,E);if(E.expressionContext==="appearance")return Qi(w,E);if(E.expressionContext&&E.expressionContext.indexOf("cluster")===0){if(!o.W(w,["zoom","feature-state"]))return[new $s(E.key,E.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(E.expressionContext==="cluster-initial"&&!o.X(w))return[new $s(E.key,E.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function ki(E,f){const w=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(f.valueSpec&&f.valueSpec.expression)for(const R of f.valueSpec.expression.parameters)w.delete(R);if(w.size===0)return[];const I=[];return E instanceof o.Z&&w.has(E.name)?[new $s(f.key,f.value,`["${E.name}"] expression is not supported in a filter for a ${f.object.type} layer with id: ${f.object.id}`)]:(E.eachChild(R=>{I.push(...ki(R,f))}),I)}function Qi(E,f){const w=new Set;if(f.valueSpec&&f.valueSpec.expression)for(const R of f.valueSpec.expression.parameters)w.add(R);if(w.size===0)return[];const I=[];return E instanceof o.Z&&!w.has(E.name)?[new $s(f.key,f.value,`["${E.name}"] is not an allowed parameter`)]:(E.eachChild(R=>{I.push(...Qi(R,f))}),I)}function Po(E){const f=E.key,w=E.value,I=E.valueSpec,R=[];return Array.isArray(I.values)?I.values.includes(o.H(w))||R.push(new $s(f,w,`expected one of [${I.values.join(", ")}], ${JSON.stringify(w)} found`)):Object.keys(I.values).includes(o.H(w))||R.push(new $s(f,w,`expected one of [${Object.keys(I.values).join(", ")}], ${JSON.stringify(w)} found`)),R}function ci(E){return o.a1(o.S(E.value))?ra(Object.assign({},E,{expressionContext:"filter",valueSpec:E.styleSpec[`filter_${E.layerType||"fill"}`]})):za(E)}function za(E){const f=E.value,w=E.key;if(!Array.isArray(f))return[new $s(w,f,`array expected, ${o.J(f)} found`)];if(f.length<1)return[new $s(w,f,"filter array must have at least 1 element")];const I=E.styleSpec;let R=Po({key:`${w}[0]`,value:f[0],valueSpec:I.filter_operator});const q=()=>{f.length>=2&&(o.$(f[1])||R.push(new $s(`${w}[1]`,f[1],`string expected, ${o.J(f[1])} found`)));for(let V=2;V":case">=":f.length>=2&&o.H(f[1])==="$type"&&R.push(new $s(w,f,`"$type" cannot be use with operator "${f[0]}"`)),f.length!==3&&R.push(new $s(w,f,`filter array for operator "${f[0]}" must have 3 elements`)),q();break;case"==":case"!=":f.length!==3&&R.push(new $s(w,f,`filter array for operator "${f[0]}" must have 3 elements`)),q();break;case"in":case"!in":q();break;case"any":case"all":case"none":for(let V=1;V{le in w&&f.push(new $s(I,w[le],`"${le}" is prohibited for ref layers`))}),R.layers.forEach(le=>{o.H(le.id)===Z&&(te=le)}),te?te.ref?f.push(new $s(I,w.ref,"ref cannot reference another ref layer")):V=o.H(te.type):typeof Z=="string"&&f.push(new $s(I,w.ref,`ref layer "${Z}" not found`))}else if(V!=="background"&&V!=="sky"&&V!=="slot")if(w.source)if(o.$(w.source)){const te=R.sources&&R.sources[w.source],le=te&&o.H(te.type);te?le==="vector"&&V==="raster"?f.push(new $s(I,w.source,`layer "${w.id}" requires a raster source`)):le==="raster"&&V!=="raster"?f.push(new $s(I,w.source,`layer "${w.id}" requires a vector source`)):le!=="vector"||w["source-layer"]?le==="raster-dem"&&V!=="hillshade"?f.push(new $s(I,w.source,"raster-dem source can only be used with layer type 'hillshade'.")):le!=="raster-array"||["raster","raster-particle"].includes(V)?V==="line"&&w.paint&&w.paint["line-gradient"]&&le==="geojson"&&!te.lineMetrics?f.push(new $s(I,w,`layer "${w.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):V==="line"&&w.paint&&w.paint["line-trim-offset"]&&le==="geojson"&&!te.lineMetrics?f.push(new $s(I,w,`layer "${w.id}" specifies a line-trim-offset, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):V==="raster-particle"&&le!=="raster-array"&&f.push(new $s(I,w.source,`layer "${w.id}" requires a 'raster-array' source.`)):f.push(new $s(I,w.source,"raster-array source can only be used with layer type 'raster'.")):f.push(new $s(I,w,`layer "${w.id}" must specify a "source-layer"`)):f.push(new $s(I,w.source,`source "${w.source}" not found`))}else f.push(new $s(`${I}.source`,w.source,'"source" must be a string'));else f.push(new $s(I,w,'missing required property "source"'));return f=f.concat(vd({key:I,value:w,valueSpec:q.layer,style:E.style,styleSpec:E.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Do({key:`${I}.type`,value:w.type,valueSpec:q.layer.type,style:E.style,styleSpec:E.styleSpec,object:w,objectKey:"type"}),filter:te=>ci(Object.assign({layerType:V},te)),layout:te=>vd({layer:w,key:te.key,value:te.value,valueSpec:{},style:te.style,styleSpec:te.styleSpec,objectElementValidators:{"*":le=>rc(Object.assign({layerType:V},le))}}),paint:te=>vd({layer:w,key:te.key,value:te.value,valueSpec:{},style:te.style,styleSpec:te.styleSpec,objectElementValidators:{"*":le=>Lo(Object.assign({layerType:V,layer:w},le))}}),appearances(te){const le=In({key:te.key,value:te.value,valueSpec:te.valueSpec,style:te.style,styleSpec:te.styleSpec,arrayElementValidator:_e=>function(Le){const{key:Ve,layer:qe,layerType:Ze}=Le,Xe=o.H(Le.value),ht=o.H(Xe.name),vt=o.H(Xe.condition),st=vd({key:Ve,value:Xe,valueSpec:Le.styleSpec.appearance,style:Le.style,styleSpec:Le.styleSpec,objectElementValidators:{condition:Ut=>function(Pt){const Vt=[];return Vt.push(...ra({key:Pt.key,value:Pt.object.condition,valueSpec:o.a6.appearance.condition,expressionContext:"appearance"})),Vt}(Object.assign({layer:qe,layerType:Ze},Ut)),properties:Ut=>function(Pt){const Vt=[],{styleSpec:St,layer:Ct,layerType:qt}=Pt,Zt=St[`paint_${qt}`],Wt=St[`layout_${qt}`],hs=Pt.object[Pt.objectKey];for(const ms in hs){const Zs=ms in Zt?"paint":ms in Wt?"layout":void 0;if(!Zs){Vt.push(new $s(Pt.key,ms,`unknown property "${ms}" for layer type "${qt}"`));continue}const ts=Object.assign({},Pt,{key:`${Pt.key}.${ms}`,object:hs,objectKey:ms,layer:Ct,layerType:qt,value:hs[ms],valueSpec:Zs==="paint"?Zt[ms]:Wt[ms]});Vt.push(...Pi(ts,Zs))}return Vt}(Object.assign({layer:qe,layerType:Ze},Ut))}});return ht!=="hidden"&&vt===void 0&&st.push(new $s(Le.key,"name",'Appearance with name different than "hidden" must have a condition')),st}(Object.assign({layerType:V,layer:w},_e))}),pe=Array.isArray(te.value)?te.value:[],Ae=new Set;return pe.forEach((_e,Le)=>{const Ve=o.H(_e.name);if(Ve)if(Ae.has(Ve)){const qe=o.H(w.id);le.push(new $s(te.key,Ve,`Duplicated appearance name "${Ve}" for layer "${qe}"`))}else Ae.add(Ve)}),le}}})),f}function Jn({key:E,value:f}){return o.$(f)?[]:[new $s(E,f,`string expected, ${o.J(f)} found`)]}const uo={promoteId:function E({key:f,value:w}){if(o.$(w))return Jn({key:f,value:w});if(Array.isArray(w)){const R=[],q=o.S(w),V=o.U(q);return V.result==="error"?(V.value.forEach(Z=>{R.push(new $s(`${f}${Z.key}`,null,`${Z.message}`))}),R):(o.W(V.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"])||R.push(new $s(`${f}`,null,"promoteId expression should be only feature dependent")),R)}if(!o.G(w))return[new $s(f,w,`string, expression or object expected, "${o.J(w)}" found`)];const I=[];for(const R in w)I.push(...E({key:`${f}.${R}`,value:w[R]}));return I}};function ll(E){const f=E.value,w=E.key,I=E.styleSpec,R=E.style;if(!o.G(f))return[new $s(w,f,`object expected, ${o.J(f)} found`)];if(!("type"in f))return[new $s(w,f,'"type" is required')];const q=o.H(f.type);let V=[];switch(["vector","raster","raster-dem","raster-array"].includes(q)&&("url"in f||"tiles"in f||V.push(new Kr(w,f,'Either "url" or "tiles" is required.'))),q){case"vector":case"raster":case"raster-dem":case"raster-array":return V=V.concat(vd({key:w,value:f,valueSpec:I[`source_${q.replace("-","_")}`],style:E.style,styleSpec:I,objectElementValidators:uo})),V;case"geojson":if(V=vd({key:w,value:f,valueSpec:I.source_geojson,style:R,styleSpec:I,objectElementValidators:uo}),"cluster"in f&&"clusterProperties"in f){if(!o.G(f.clusterProperties))return[new $s(`${w}.clusterProperties`,f,`object expected, ${o.J(f)} found`)];for(const Z in f.clusterProperties){const te=f.clusterProperties[Z];if(!Array.isArray(te))return[new $s(`${w}.clusterProperties.${Z}`,te,"array expected")];const[le,pe]=te,Ae=typeof le=="string"?[le,["accumulated"],["get",Z]]:le;V.push(...ra({key:`${w}.${Z}.map`,value:pe,expressionContext:"cluster-map"})),V.push(...ra({key:`${w}.${Z}.reduce`,value:Ae,expressionContext:"cluster-reduce"}))}}return V;case"video":return vd({key:w,value:f,valueSpec:I.source_video,style:R,styleSpec:I});case"image":return vd({key:w,value:f,valueSpec:I.source_image,style:R,styleSpec:I});case"canvas":return[new $s(w,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Po({key:`${w}.type`,value:f.type,valueSpec:{values:Va(I)}})}}function Va(E){return E.source.reduce((f,w)=>{const I=E[w];return I.type.type==="enum"&&(f=f.concat(Object.keys(I.type.values||{}))),f},[])}function Dl(E,f){const w=!E.includes("://");try{return new URL(E,w&&f?"http://example.com":void 0),!0}catch{return!1}}function Wm(E){const f=E.value;return f?o.$(f)?Dl(f,!0)?[]:[new $s(E.key,f,`invalid url "${f}"`)]:[new $s(E.key,f,`string expected, "${o.J(f)}" found`)]:[]}function Lf(E){const f=E.value,w=E.styleSpec,I=w.light,R=E.style;if(f===void 0)return[];if(!o.G(f))return[new $s("light",f,`object expected, ${o.J(f)} found`)];let q=[];for(const V in f){const Z=V.match(o.a3),te=V.match(o.a2);q=q.concat(te&&I[te[1]]?Do({key:V,value:f[V],valueSpec:{type:"string"},style:R,styleSpec:w}):Z&&I[Z[1]]&&I[Z[1]].transition?Do({key:V,value:f[V],valueSpec:w.transition,style:R,styleSpec:w}):I[V]?Do({key:V,value:f[V],valueSpec:I[V],style:R,styleSpec:w}):[new $s(V,f[V],`unknown property "${V}"`)])}return q}function Gx(E){const f=E.value;if(!f)return[];const w=E.key;if(!o.G(f))return[new $s(w,f,`object expected, ${o.J(f)} found`)];let I=[];const R=E.styleSpec,q=R["light-3d"],V=E.style,Z=E.style.lights;for(const pe of["type","id"])if(!(pe in f))return I=I.concat([new $s(w,f,`missing property "${pe}"`)]),I;if(!o.$(f.type))return I=I.concat([new $s(`${w}.type`,f.type,"string expected")]),I;if(Z)for(let pe=0;pe[],array:In,boolean:function(E){const f=E.value,w=E.key;return o._(f)?[]:[new $s(w,f,`boolean expected, ${o.J(f)} found`)]},number:Ja,color:function({key:E,value:f}){return o.$(f)?o.a0.parseCSSColor(f)===null?[new $s(E,f,`color expected, "${f}" found`)]:[]:[new $s(E,f,`color expected, ${o.J(f)} found`)]},enum:Po,filter:ci,function:yo,layer:dr,object:vd,source:ll,model:Wm,light:Lf,"light-3d":Gx,terrain:j0,fog:F_,string:Jn,formatted:function(E){return Jn(E).length===0?[]:ra(E)},resolvedImage:function(E){return Jn(E).length===0?[]:ra(E)},projection:function(E){const f=E.value,w=E.styleSpec,I=w.projection,R=E.style;if(o.G(f)){let q=[];for(const V in f)q=q.concat(Do({key:V,value:f[V],valueSpec:I[V],style:R,styleSpec:w}));return q}return o.$(f)?[]:[new $s("projection",f,`object or string expected, ${o.J(f)} found`)]},import:function(E){const f=E.key,{value:w,styleSpec:I}=E;if(!o.G(w))return[new $s(f,w,"import must be an object")];const{data:R,...q}=w;Object.defineProperty(q,"__line__",{value:w.__line__,enumerable:!1});let V=vd(Object.assign({},E,{value:q,valueSpec:I.import}));return o.H(q.id)===""&&V.push(new $s(`${E.key}.id`,q,"import id can't be an empty string")),R&&(V=V.concat(N0(R,I,{key:`${E.key}.data`}))),V},iconset:function(E){const f=E.value,w=E.key,I=E.styleSpec,R=E.style;if(!o.G(f))return[new $s(w,f,"object expected")];if(!f.type)return[new $s(w,f,'"type" is required')];const q=o.H(f.type);let V=[];if(V=V.concat(vd({key:w,value:f,valueSpec:I[`iconset_${q}`],style:R,styleSpec:I})),function(Z,te){return!(Z!=="source"||!te.source)}(q,f)){const Z=R.sources&&R.sources[f.source],te=Z&&o.H(Z.type);Z?te!=="raster-array"&&V.push(new $s(w,f.source,`iconset cannot be used with a source of type ${String(te)}, it only be used with a "raster-array" source type`)):V.push(new $s(w,f.source,`source "${f.source}" not found`))}return V}};function Do(E,f=!1){const w=E.value,I=E.valueSpec,R=E.styleSpec;if(I.expression){if(o.a4(o.H(w)))return yo(E);if(o.Q(o.S(w)))return ra(E)}if(I.type&&E1[I.type]){const q=E1[I.type](E);return f===!0&&q.length>0&&Array.isArray(E.value)?ra(E):q}return vd(Object.assign({},E,{valueSpec:I.type?R[I.type]:I}))}function vd(E){const f=E.key,w=E.value,I=E.valueSpec||{},R=E.objectElementValidators||{},q=E.style,V=E.styleSpec;if(!o.G(w))return[new $s(f,w,`object expected, ${o.J(w)} found`)];let Z=[];for(const te in w){const le=te.split(".")[0];let pe;R[le]?pe=R[le]:I[le]?pe=Do:R["*"]?pe=R["*"]:I["*"]&&(pe=Do),pe?Z=Z.concat(pe({key:(f&&`${f}.`)+te,value:w[te],valueSpec:I[le]||I["*"],style:q,styleSpec:V,object:w,objectKey:te},w)):Z.push(new Kr(f,w[te],`unknown property "${te}"`))}for(const te in I){if(R[te])continue;const le=I[te];le.required&&le.default===void 0&&w[te]===void 0&&Z.push(new $s(f,w,`missing required property "${te}"`))}return Z}function iy({key:E,value:f}){const w=Jn({key:E,value:f});if(w.length)return w;const I=f;return I.includes("{fontstack}")||w.push(new $s(E,f,'"glyphs" url must include a "{fontstack}" token')),I.includes("{range}")||w.push(new $s(E,f,'"glyphs" url must include a "{range}" token')),w}function N0(E,f=o.a6,w={}){return vd({key:w.key||"",value:E,valueSpec:Object.assign({},f.$root,{"*":{type:"*"}}),styleSpec:f,style:E,objectElementValidators:{glyphs:iy}})}function Df(E,f=o.a6){return Dc(N0(E,f))}const bd=E=>Dc(ll(E)),iN=E=>Dc(Lf(E)),oN=E=>Dc(Gx(E)),A1=E=>Dc(j0(E)),oy=E=>Dc(F_(E)),ly=E=>Dc(function(f){const w=f.value,I=f.style,R=f.styleSpec,q=R.snow;if(w===void 0)return[];if(!o.G(w))return[new $s("snow",w,`object expected, ${o.J(w)} found`)];let V=[];for(const Z in w){const te=Z.match(o.a3);V=V.concat(te&&q[te[1]]&&q[te[1]].transition?Do({key:Z,value:w[Z],valueSpec:R.transition,style:I,styleSpec:R}):q[Z]?Do({key:Z,value:w[Z],valueSpec:q[Z],style:I,styleSpec:R}):[new Kr(Z,w[Z],`unknown property "${Z}"`)])}return V}(E)),cy=E=>Dc(function(f){const w=f.value,I=f.style,R=f.styleSpec,q=R.rain;if(w===void 0)return[];if(!o.G(w))return[new $s("rain",w,`object expected, ${o.J(w)} found`)];let V=[];for(const Z in w){const te=Z.match(o.a3);V=V.concat(te&&q[te[1]]&&q[te[1]].transition?Do({key:Z,value:w[Z],valueSpec:R.transition,style:I,styleSpec:R}):q[Z]?Do({key:Z,value:w[Z],valueSpec:q[Z],style:I,styleSpec:R}):[new Kr(Z,w[Z],`unknown property "${Z}"`)])}return V}(E)),Np=E=>Dc(dr(E)),mm=E=>Dc(ci(E)),Rf=E=>Dc(Lo(E)),k0=E=>Dc(rc(E)),du=E=>Dc(Wm(E));function Dc(E){return E.slice().sort((f,w)=>f.line&&w.line?f.line-w.line:0)}function fm(E,f){let w=!1;if(f&&f.length)for(const I of f)I instanceof Kr?o.w(I.message):(E.fire(new o.y(new Error(I.message))),w=!0);return w}const Hd=o.a6.light;let lN;class cN extends o.E{constructor(f,w="flat"){super(),this._transitionable=new o.a7(lN||(lN=new o.a8({anchor:new o.a9(Hd.anchor),position:new o.aa(Hd.position),color:new o.a9(Hd.color),intensity:new o.a9(Hd.intensity)}))),this.setLight(f,w),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(f,w,I={}){this._validate(iN,f,I)||(this._transitionable.setTransitionOrValue(f),this.id=w)}updateTransitions(f){this._transitioning=this._transitionable.transitioned(f,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(f){this.properties=this._transitioning.possiblyEvaluate(f)}_validate(f,w,I){return(!I||I.validate!==!1)&&fm(this,f.call(Df,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a6})))}}const dy=o.a6.terrain;let kp=class extends o.E{constructor(E,f,w,I,R){super(),this.scope=w,this._transitionable=new o.a7(new o.a8({source:new o.a9(dy.source),exaggeration:new o.a9(dy.exaggeration)}),w,I),this._transitionable.setTransitionOrValue(E,I),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=f,this.worldview=R}get(){return this._transitionable.serialize()}set(E,f){this._transitionable.setTransitionOrValue(E,f)}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}getExaggeration(E){return this._transitioning.possiblyEvaluate(new o.ab(E,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const E=this._transitionable._values.exaggeration;if(!E)return null;const f=E.value.expression;if(!f)return null;let w=-1,I=-1,R=1;for(const q of f.zoomStops)R=f.evaluate(new o.ab(q,{worldview:this.worldview})),R>.01?(w=q,I=-1):I=q;return R<.01&&w>0&&I>w?[w,I]:null}isZoomDependent(){const E=this._transitionable._values.exaggeration;return E!=null&&E.value!=null&&E.value.expression!=null&&E.value.expression instanceof o.ac}};const Sp=.05;function M1(E,f,w){const I=o.ag(45,65,w),[R,q]=E.range;let V=1-Math.min(1,Math.exp((f-R)/(q-R)*-6));return V*=V*V,V=Math.min(1,1.00747*V),V*I*E.alpha}function I1(E,f,w,I,R){const q=o.ae([],[f,w,I],R.mercatorFogMatrix);return M1(E,o.af(q),R.pitch)}function oT(E,f,w,I,R,q,V){const Z=[[w,I,0],[R,I,0],[R,q,0],[w,q,0]];let te=Number.MAX_VALUE,le=-Number.MAX_VALUE;for(const pe of Z){const Ae=o.ae([],pe,f),_e=o.af(Ae);te=Math.min(te,_e),le=Math.max(le,_e)}return[M1(E,te,V.pitch),M1(E,le,V.pitch)]}const Cp=o.a6.fog;class S0 extends o.E{constructor(f,w,I,R){super();const q=new o.a8({range:new o.a9(Cp.range),color:new o.a9(Cp.color),"color-use-theme":new o.a9({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.a9(Cp["high-color"]),"high-color-use-theme":new o.a9({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.a9(Cp["space-color"]),"space-color-use-theme":new o.a9({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.a9(Cp["horizon-blend"]),"star-intensity":new o.a9(Cp["star-intensity"]),"vertical-range":new o.a9(Cp["vertical-range"])});this._transitionable=new o.a7(q,I,R),this.set(f,R),this._transitioning=this._transitionable.untransitioned(),this._transform=w,this.properties=new o.ah(q),this.scope=I}get state(){const f=this._transform,w=f.projection.name==="globe",I=o.ai(f.zoom),R=this.properties.get("range"),q=[2,4.5],V=.5/Math.tan(.5*f._fov),Z=[R[0]+V,R[1]+V];return{range:w?[o.aj(q[0],Z[0],I),o.aj(q[1],Z[1],I)]:Z,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(f,w,I={}){if(this._validate(oy,f,I))return;const R=Object.assign({},f);for(const q of Object.keys(Cp))R[q]===void 0&&(R[q]=Cp[q].default);this._options=R,this._transitionable.setTransitionOrValue(this._options,w)}getOpacity(f){if(!this._transform.projection.supportsFog)return 0;const w=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.ag(45,65,f))*w.a}getOpacityAtLatLng(f,w){return this._transform.projection.supportsFog?function(I,R,q){const V=o.ad.fromLngLat(R),Z=q.elevation?q.elevation.getAtPointOrZero(V):0;return I1(I,V.x,V.y,Z,q)}(this.state,f,w):0}getOpacityForTile(f){if(!this._transform.projection.supportsFog)return[1,1];const w=this._transform.calculateFogTileMatrix(f.toUnwrapped());return oT(this.state,w,0,0,o.ak,o.ak,this._transform)}getOpacityForBounds(f,w,I,R,q){return this._transform.projection.supportsFog?oT(this.state,f,w,I,R,q,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(f){if(!this._transform.projection.supportsFog)return!1;const w=[4,5,6,7];for(const I of w){const R=f.points[I];let q;if(R[2]>=0)q=R;else{const V=f.points[I-4];q=o.al(V,R,V[2]/(V[2]-R[2]))}if(I1(this.state,q[0],q[1],0,this._transform)>=Sp)return!0}return!1}updateConfig(f){this._transitionable.setTransitionOrValue(this._options,f)}updateTransitions(f){this._transitioning=this._transitionable.transitioned(f,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(f){this.properties=this._transitioning.possiblyEvaluate(f)}_validate(f,w,I){return(!I||I.validate!==!1)&&fm(this,f.call(Df,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a6})))}}let P1,C0,yL=class extends o.E{constructor(E,f,w,I){super();const R=P1||(P1=new o.a8({density:new o.a9(o.a6.snow.density),intensity:new o.a9(o.a6.snow.intensity),color:new o.a9(o.a6.snow.color),opacity:new o.a9(o.a6.snow.opacity),vignette:new o.a9(o.a6.snow.vignette),"vignette-color":new o.a9(o.a6.snow["vignette-color"]),"center-thinning":new o.a9(o.a6.snow["center-thinning"]),direction:new o.a9(o.a6.snow.direction),"flake-size":new o.a9(o.a6.snow["flake-size"])}));this._transitionable=new o.a7(R,w,I),this.set(E,I),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ah(R),this.scope=w}get state(){const E=this.properties.get("opacity"),f=this.properties.get("color"),w=this.properties.get("direction"),I=o.am(w[0]),R=-Math.max(o.am(w[1]),.01),q=[Math.cos(I)*Math.cos(R),Math.sin(I)*Math.cos(R),Math.sin(R)],V=this.properties.get("vignette"),Z=this.properties.get("vignette-color");return Z.a=V,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(f.r,f.g,f.b,f.a*E),direction:q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:Z}}get(){return this._transitionable.serialize()}set(E,f,w={}){if(this._validate(ly,E,w))return;const I=Object.assign({},E),R=o.a6.snow;for(const q of Object.keys(R))I[q]===void 0&&(I[q]=R[q].default);this._options=I,this._transitionable.setTransitionOrValue(this._options,f)}updateConfig(E){this._transitionable.setTransitionOrValue(this._options,E)}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}_validate(E,f,w){return(!w||w.validate!==!1)&&fm(this,E.call(Df,Object.assign({value:f,style:{glyphs:!0,sprite:!0},styleSpec:o.a6})))}},B_=class extends o.E{constructor(E,f,w,I){super();const R=C0||(C0=new o.a8({density:new o.a9(o.a6.rain.density),intensity:new o.a9(o.a6.rain.intensity),color:new o.a9(o.a6.rain.color),opacity:new o.a9(o.a6.rain.opacity),vignette:new o.a9(o.a6.rain.vignette),"vignette-color":new o.a9(o.a6.rain["vignette-color"]),"center-thinning":new o.a9(o.a6.rain["center-thinning"]),direction:new o.a9(o.a6.rain.direction),"droplet-size":new o.a9(o.a6.rain["droplet-size"]),"distortion-strength":new o.a9(o.a6.rain["distortion-strength"])}));this._transitionable=new o.a7(R,w,I),this.set(E,I),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ah(R),this.scope=w}get state(){const E=this.properties.get("opacity"),f=this.properties.get("color"),w=this.properties.get("direction"),I=o.am(w[0]),R=-Math.max(o.am(w[1]),.01),q=[Math.cos(I)*Math.cos(R),Math.sin(I)*Math.cos(R),Math.sin(R)],V=this.properties.get("vignette-color");return V.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(f.r,f.g,f.b,f.a*E),direction:q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:V}}get(){return this._transitionable.serialize()}set(E,f,w={}){if(this._validate(cy,E,w))return;const I=Object.assign({},E),R=o.a6.rain;for(const q of Object.keys(R))I[q]===void 0&&(I[q]=R[q].default);this._options=I,this._transitionable.setTransitionOrValue(this._options,f)}updateConfig(E){this._transitionable.setTransitionOrValue(this._options,E)}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}_validate(E,f,w){return(!w||w.validate!==!1)&&fm(this,E.call(Df,Object.assign({value:f,style:{glyphs:!0,sprite:!0},styleSpec:o.a6})))}};const Gd={workerUrl:"",workerClass:null,workerParams:void 0};function dN(E){return Gd.workerClass!=null?new Gd.workerClass:new self.Worker(Gd.workerUrl,Object.assign({name:E},Gd.workerParams))}const z_="mapboxgl_preloaded_worker_pool";class Wx{constructor(f){this.active={},this.name=f}acquire(f,w=Wx.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{w.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[z_]}numActive(){return Object.keys(this.active).length}}Wx.workerCount=2;class L1{constructor(f,w,I="Worker",R=Wx.workerCount){this.workerPool=f,this.actors=[],this.currentActor=0,this.id=o.an();const q=this.workerPool.acquire(this.id,R);for(let V=0;V{this.ready=!0})}broadcast(f,w,I){o.ao(this.actors,(R,q)=>{R.send(f,w,q)},I=I||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(f=>{f.remove()}),this.actors=[],this.workerPool.release(this.id)}}L1.Actor=o.ap;class T0 extends o.E{constructor(f,w,I,R){super(),this.scope=I,this._options=f,this.properties=new o.ah(w),this._transitionable=new o.a7(w,I,R),this._transitionable.setTransitionOrValue(f.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(f){this._transitionable.setTransitionOrValue(this._options.properties,f)}updateTransitions(f){this._transitioning=this._transitionable.transitioned(f,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(f){this.properties=this._transitioning.possiblyEvaluate(f)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(f,w){this._options=f,this._transitionable.setTransitionOrValue(f.properties,w)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}let $_;const lT=()=>$_||($_=new o.a8({color:new o.a9(o.a6.properties_light_ambient.color),"color-use-theme":new o.a9({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.a9(o.a6.properties_light_ambient.intensity)}));let cT;const It=()=>cT||(cT=new o.a8({direction:new o.aq(o.a6.properties_light_directional.direction),color:new o.a9(o.a6.properties_light_directional.color),"color-use-theme":new o.a9({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.a9(o.a6.properties_light_directional.intensity),"cast-shadows":new o.a9(o.a6.properties_light_directional["cast-shadows"]),"shadow-quality":new o.a9(o.a6.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.a9(o.a6.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.a9(o.a6.properties_light_directional["shadow-draw-before-layer"])}));class Gs{constructor(f,w,I){this.screenBounds=f,this.cameraPoint=I.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=w,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,I)}static createFromScreenPoints(f,w){let I,R;if(f instanceof o.P||typeof f[0]=="number"){const q=o.P.convert(f);I=[q],R=w.isPointAboveHorizon(q)}else{const q=o.P.convert(f[0]),V=o.P.convert(f[1]),Z=q.add(V)._div(2);I=[q,V],R=o.ar(q,V).every(te=>w.isPointAboveHorizon(te))&&w.isPointAboveHorizon(Z)}return new Gs(I,R,w)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(f){return o.ar(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],f)}bufferedCameraGeometry(f){const w=this.screenBounds[0],I=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],R=o.ar(w,I,0,!1);return this.cameraPoint.y>I.y&&(this.cameraPoint.x>w.x&&this.cameraPoint.x=I.x?R[2]=this.cameraPoint:this.cameraPoint.x<=w.x&&(R[3]=this.cameraPoint)),o.as(R,f)}bufferedCameraGeometryGlobe(f){const w=this.screenBounds[0],I=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],R=o.ar(w,I,f),q=this.cameraPoint.clone(),V=+(q.x>w.x)+ +(q.x>I.x);switch(3*(+(q.y>w.y)+ +(q.y>I.y))+V){case 0:R[0]=q,R[4]=q.clone();break;case 1:R.splice(1,0,q);break;case 2:R[1]=q;break;case 3:R.splice(4,0,q);break;case 5:R.splice(2,0,q);break;case 6:R[3]=q;break;case 7:R.splice(3,0,q);break;case 8:R[2]=q}return R}containsTile(f,w,I,R=0){const q=Math.max(f.queryPadding,f.evaluateQueryRenderedFeaturePadding())/w._pixelsPerMercatorPixel+1,V=I?this._bufferedCameraMercator(q,w):this._bufferedScreenMercator(q,w);let Z=f.tileID.wrap+(V.unwrapped?R:0);const te=V.polygon.map(Ze=>o.at(f.tileTransform,Ze,Z));if(!o.au(te,0,0,o.ak,o.ak))return;Z=f.tileID.wrap+(this.screenGeometryMercator.unwrapped?R:0);const le=this.screenGeometryMercator.polygon.map(Ze=>o.av(f.tileTransform,Ze,Z)),pe=le.map(Ze=>new o.P(Ze[0],Ze[1])),Ae=w.getFreeCameraOptions().position||new o.ad(0,0,0),_e=o.av(f.tileTransform,Ae,Z),Le=le.map(Ze=>{const Xe=o.aw(Ze,Ze,_e);return o.ax(Xe,Xe),new o.ay(_e,Xe)}),Ve=o.az(f,1,w.zoom)*w._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:pe,tilespaceRays:Le,bufferedTilespaceGeometry:te,bufferedTilespaceBounds:(qe=o.aA(te),qe.min.x=o.aB(qe.min.x,0,o.ak),qe.min.y=o.aB(qe.min.y,0,o.ak),qe.max.x=o.aB(qe.max.x,0,o.ak),qe.max.y=o.aB(qe.max.y,0,o.ak),qe),tile:f,tileID:f.tileID,pixelToTileUnitsFactor:Ve};var qe}_bufferedScreenMercator(f,w){const I=_n(f);if(this._screenRaycastCache[I])return this._screenRaycastCache[I];{let R;return R=w.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(f),w):{polygon:this.bufferedScreenGeometry(f).map(q=>w.pointCoordinate3D(q)),unwrapped:!0},this._screenRaycastCache[I]=R,R}}_bufferedCameraMercator(f,w){const I=_n(f);if(this._cameraRaycastCache[I])return this._cameraRaycastCache[I];{let R;return R=w.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(f),w):{polygon:this.bufferedCameraGeometry(f).map(q=>w.pointCoordinate3D(q)),unwrapped:!0},this._cameraRaycastCache[I]=R,R}}_projectAndResample(f,w){const I=function(q,V){const Z=o.aC([],V.pixelMatrix,V.globeMatrix),te=[0,-o.aE,0,1],le=[0,o.aE,0,1],pe=[0,0,0,1];o.aD(te,te,Z),o.aD(le,le,Z),o.aD(pe,pe,Z);const Ae=new o.P(te[0]/te[3],te[1]/te[3]),_e=new o.P(le[0]/le[3],le[1]/le[3]),Le=o.aF(q,Ae)&&te[3]1?hr(q.slice(0,Ze),V):[],vt=Zenew o.P(gn(St.x),St.y)),vt=vt.map(St=>new o.P(gn(St.x),St.y));const st=[...ht];st.length===0&&st.push(vt.at(-1));const Ut=st.at(-1),Pt=o.aj(Ut.y,(vt.length===0?ht[0]:vt[0]).y,Xe);let Vt;return Vt=Le?[new o.P(0,Pt),new o.P(0,0),new o.P(1,0),new o.P(1,Pt)]:[new o.P(1,Pt),new o.P(1,1),new o.P(0,1),new o.P(0,Pt)],st.push(...Vt),vt.length===0?st.push(ht[0]):st.push(...vt),{polygon:st.map(St=>new o.ad(St.x,St.y)),unwrapped:!1}}(f,w);if(I)return I;const R=function(q,V){let Z=!1,te=-1/0,le=0;for(let Ae=0;Aete&&(te=q[Ae].x,le=Ae);for(let Ae=0;Ae.5&&(Le.x{Ae.x-=1}),{polygon:q,unwrapped:Z}}(hr(f,w).map(q=>new o.P(gn(q.x),q.y)),w);return{polygon:R.polygon.map(q=>new o.ad(q.x,q.y)),unwrapped:R.unwrapped}}}function hr(E,f){return o.aH(E,w=>{const I=f.pointCoordinate3D(w);w.x=I.x,w.y=I.y},1/256)}function gn(E){return E<0?1+E%1:E%1}function _n(E){return 100*E|0}function Aa(E,f){const w=Math.pow(2,f.z),I=Math.floor(o.aG(E.getWest())*w),R=Math.floor(o.aJ(E.getNorth())*w),q=Math.ceil(o.aG(E.getEast())*w),V=Math.ceil(o.aJ(E.getSouth())*w);return f.x>=I&&f.x=R&&f.ythis.maxzoom||f.z{this._tileJSONRequest=null,this._loaded=!0,V?(w&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${w}`),I&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${I}`),this.fire(new o.y(V))):Z&&(this._setTileJSON(Z),Te(Z.tiles,this.map._requestManager._customAccessToken),this.fire(new o.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.z("data",{dataType:"source",sourceDataType:"content"}))),f&&f(V)};this.provider=this._options.provider;const q=o.aM(this._options);return q instanceof Error?(this._loaded=!0,this.fire(new o.y(q)),void(f&&f())):this.provider&&!q?(this._loaded=!0,this.fire(new o.y(new Error(`TileProvider "${this.provider}" is not registered`))),void(f&&f())):void(this._tileJSONRequest=q?this.loadTileJSONWithProvider(q,R):o.aN(this._options,this.map._requestManager,w,I,R))}loadTileJSONWithProvider(f,w){this.provider=f.name;const{request:I,options:R}=o.aO(this._options,this.map._requestManager),q=new AbortController;return this.dispatcher.broadcast("loadTileProvider",{name:f.name,url:f.url,source:this.id,scope:this.scope,type:this.type,options:R,request:I},(V,Z)=>{if(q.signal.aborted)return;if(V)return void w(V);const te=Z?Z.find(pe=>pe!=null):null,le=o.aP(this._options,te,this.map._requestManager);le instanceof Error?w(le):w(null,le)}),{cancel:()=>q.abort()}}_setTileJSON(f){if(Object.assign(this,f),this.hasWorldviews=!!f.worldview_options,f.worldview_default&&(this.worldviewDefault=f.worldview_default),f.vector_layers){this.vectorLayers=f.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const w of f.vector_layers)this.vectorLayerIds.push(w.id),f.worldview&&f.worldview[w.source]&&this.localizableLayerIds.add(w.id)}this.tileBounds=Gn.fromTileJSON(f)}loaded(){return this._loaded}hasTile(f){return!this.tileBounds||this.tileBounds.contains(f.canonical)}onAdd(f){this.map=f,this.load()}reload(){this.cancelTileJSONRequest();const f=o.t(this.id,this.scope);this.load(()=>this.map.style.clearSource(f))}setTiles(f){return this._options.tiles=f,this.reload(),this}setUrl(f){return this.url=f,this._options.url=f,this.reload(),this}onRemove(f){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(f,w){const I=f.tileID.canonical.url(this.tiles,this.scheme),R=this.map._requestManager.normalizeTileURL(I),q=this.map._requestManager.transformRequest(R,o.R.Tile),V=this.map.style?this.map.style.getLut(this.scope):null,Z=V?{image:V.image.clone()}:null,te={request:q,data:void 0,uid:f.uid,tileID:f.tileID,tileZoom:f.tileZoom,zoom:f.tileID.overscaledZ,maxZoom:this.maxzoom,lut:Z,tileSize:this.tileSize*f.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,renderSourceType:f.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:f.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(I)&&(te.localizableLayerIds=this.localizableLayerIds),te.request.collectResourceTiming=this._collectResourceTiming,f.actor&&f.state!=="expired")f.state==="loading"?f.reloadCallback=w:f.request=f.actor.send("reloadTile",te,le.bind(this));else if(f.actor=this._tileWorkers[R]=this._tileWorkers[R]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)f.request=f.actor.send("loadTile",te,le.bind(this),void 0,!0);else{const pe=o.aQ.call({deduped:this._deduped},te,(Ae,_e)=>{if(Ae||!_e)le.call(this,Ae);else{const Le=o.aR(_e.responseHeaders);te.data={rawData:_e.rawData.slice(0),expires:Le.expires,cacheControl:Le.cacheControl},f.actor&&f.actor.send("loadTile",te,le.bind(this),void 0,!0)}},!0);f.request={cancel:pe}}function le(pe,Ae){return delete f.request,f.aborted?w(null):pe?w(pe):(Ae&&Ae.resourceTiming&&(f.resourceTiming=Ae.resourceTiming),this.map._refreshExpiredTiles&&Ae&&f.setExpiryData(Ae),f.loadVectorData(Ae,this.map.painter),o.aS(this.dispatcher),w(null,Ae),void(f.reloadCallback&&(this.loadTile(f,f.reloadCallback),f.reloadCallback=null)))}}abortTile(f){f.request&&(f.request.cancel(),delete f.request),f.actor&&f.actor.send("abortTile",{uid:f.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(f,w){f.actor&&f.actor.send("removeTile",{uid:f.uid,type:this.type,source:this.id,scope:this.scope}),f.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class Fh extends o.E{constructor(f,w,I,R){super(),this.id=f,this.dispatcher=I,this.setEventedParent(R),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"},w),Object.assign(this,o.aK(w,["url","scheme","tileSize"]))}load(f){this._loaded=!1,this.fire(new o.z("dataloading",{dataType:"source"}));const w=this.map.getWorldview(),I=(q,V)=>{this._tileJSONRequest=null,this._loaded=!0,q?this.fire(new o.y(q)):V&&(Object.assign(this,V),V.raster_layers&&(this.rasterLayers=V.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Z=>Z.id)),this.tileBounds=Gn.fromTileJSON(V),Te(V.tiles),this.fire(new o.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.z("data",{dataType:"source",sourceDataType:"content"}))),f&&f(q)};this.provider=typeof this._options.provider=="string"?this._options.provider:void 0,this._tileProvider=void 0;const R=o.aM(this._options);return R instanceof Error?(this._loaded=!0,this.fire(new o.y(R)),void(f&&f())):this.provider&&!R?(this._loaded=!0,this.fire(new o.y(new Error(`TileProvider "${this.provider}" is not registered`))),void(f&&f())):void(this._tileJSONRequest=R?this.loadTileJSONWithProvider(R,I):o.aN(this._options,this.map._requestManager,null,w,I))}loadTileJSONWithProvider(f,w){this.provider=f.name;const{request:I,options:R}=o.aO(this._options,this.map._requestManager),q=new AbortController;return o.aT(f.name,f.url).then(V=>{if(q.signal.aborted)return;const Z=new V(R);return Z.load&&I?Z.load({request:I}).then(te=>(this._tileProvider=Z,te)):(this._tileProvider=Z,null)}).then(V=>{if(q.signal.aborted)return;const Z=o.aP(this._options,V,this.map._requestManager);Z instanceof Error?w(Z):w(null,Z)}).catch(V=>{q.signal.aborted||w(V instanceof Error?V:new Error(String(V)))}),{cancel:()=>q.abort()}}loaded(){return this._loaded}onAdd(f){this.map=f,this.load()}reload(){this.cancelTileJSONRequest();const f=o.t(this.id,this.scope);this.load(()=>this.map.style.clearSource(f))}setTiles(f){return this._options.tiles=f,this.reload(),this}setUrl(f){return this.url=f,this._options.url=f,this.reload(),this}onRemove(f){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(f){return!this.tileBounds||this.tileBounds.contains(f.canonical)}loadTile(f,w){const I=o.o.devicePixelRatio>=2,R=this.map._requestManager.normalizeTileURL(f.tileID.canonical.url(this.tiles,this.scheme),I,this.tileSize),q=this.map._requestManager.transformRequest(R,o.R.Tile);if(this._tileProvider){const V=new AbortController;f.request={cancel:()=>V.abort()},this.loadTileWithProvider(f,this._tileProvider,q,V,w)}else f.request=o.n(q,(V,Z,te)=>{if(delete f.request,f.aborted)return f.state="unloaded",w(null);if(V)return f.state="errored",w(V);if(!Z)return w(null);const le=o.aR(te);this.map._refreshExpiredTiles&&f.setExpiryData(le),f.setTexture(Z,this.map.painter),f.state="loaded",o.aS(this.dispatcher),w(null)})}async loadTileWithProvider(f,w,I,R,q){const{z:V,x:Z,y:te}=f.tileID.canonical;try{const le=await w.loadTile({z:V,x:Z,y:te},{request:I,signal:R.signal});if(R.signal.aborted)return f.state="unloaded",q(null);if(le==null){const Ae=new Error("Tile not found");return Ae.status=404,f.state="errored",q(Ae)}if(le.data==null)return f.state="loaded",q(null);const pe=await createImageBitmap(new Blob([le.data]));if(R.signal.aborted)return f.state="unloaded",q(null);f.setTexture(pe,this.map.painter),f.state="loaded",this.map._refreshExpiredTiles&&f.setExpiryData({cacheControl:le.cacheControl,expires:le.expires}),q(null)}catch(le){if(R.signal.aborted||le instanceof DOMException&&le.name==="AbortError")return f.state="unloaded",q(null);f.state="errored",q(le instanceof Error?le:new Error(String(le)))}finally{delete f.request}}abortTile(f,w){f.request&&(f.request.cancel(),delete f.request),w&&w()}unloadTile(f,w){f.texture&&f.texture instanceof o.T?(f.destroy(!1),f.texture&&f.texture instanceof o.T&&this.map.painter.saveTileTexture(f.texture)):f.destroy(),w&&w()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Tp([E,f],w,I,{scaled:R=!0}={}){const{tileSize:q,buffer:V}=I,{x:Z,y:te,z:le}=w;if(!isFinite(Z)||!isFinite(te)||!isFinite(le))throw new Error("Invalid MRT header");const pe=2**le,Ae=pe*o.aG(E),_e=pe*o.aJ(f);return function([Le,Ve],qe,{scaled:Ze=!0}={}){if(!qe)throw new Error("bandView is undefined");const{data:Xe,tileSize:ht,buffer:vt,offset:st,scale:Ut,dimension:Pt}=qe;if(Le<-vt||Le>ht+vt||Ve<-vt||Ve>ht+vt)throw new Error(`Point (${Le}, ${Ve}) out of bounds for tileSize=${ht}, buffer=${vt}`);const Vt=(Ve+vt)*(ht+2*vt)+(Le+vt);if(new Uint32Array(Xe.buffer)[Vt]===4294967295)return null;let St=[];St=Ze?[]:new qe.data.constructor(Pt);for(let Ct=0;Ct{if(delete f.request,f.aborted)return f.state="unloaded",w(null);if(Z)return Z.name==="AbortError"?void 0:(f.state="errored",w(Z));if(this.map._refreshExpiredTiles&&te){const pe=o.aR(le);f.setExpiryData(pe)}if(this.partial&&f.state!=="expired")f.state="empty";else if(!this.partial){if(!te)return w(null);f.state="loaded",f._isHeaderLoaded=!0,f._mrt=te}w(null)};f.request=this.partial?f.fetchHeader(void 0,V.bind(this)):f.actor.send("loadTile",q,V.bind(this),void 0,!0)}abortTile(f){f.request&&(f.request.cancel(),delete f.request),f.actor&&f.actor.send("abortTile",{uid:f.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(f,w){const I=f.texturePerLayer;if(f.flushAllQueues(),I.size){f.destroy(!1);for(const R of I.values())this.map.painter.saveTileTexture(R)}else f.destroy()}prepareTile(f,w,I,R){f._isHeaderLoaded&&(f.state!=="empty"&&(f.state="reloading"),f.fetchBandForRender(w,I,R,(q,V)=>{q?(f.state="errored",this.fire(new o.y(q))):V&&(f._isHeaderLoaded=!0,f.setTexturePerLayer(I,V,this.map.painter),f.state="loaded"),this.triggerRepaint(f)}))}getInitialBand(f){if(!this.rasterLayers)return 0;const w=this.rasterLayers.find(({id:q})=>q===f),I=w&&w.fields,R=I&&I.bands&&I.bands;return R?R[0]:0}getTextureDescriptor(f,w,I){if(!f)return;const R=w.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!R)return;let q=null;w instanceof o.aV?q=w.paint.get("raster-array-band"):w instanceof o.aW&&(q=w.paint.get("raster-particle-array-band"));const V=q||this.getInitialBand(R);if(V==null)return;if(!f.textureDescriptorPerLayer.get(w.id))return void this.prepareTile(f,R,w.id,V);if(f.updateNeeded(w.id,V)&&!I)return;const Z=f.textureDescriptorPerLayer.get(w.id);return Object.assign({},Z,{texture:f.texturePerLayer.get(w.id)})}getImages(f,w){const I=new Map;for(const R of f)for(const q of w){const[V,Z]=q.split("/"),te=R.getLayer(V);if(!te||!te.hasBand(Z)||!te.hasDataForBand(Z))continue;const{bytes:le,tileSize:pe,buffer:Ae}=te.getBandView(Z),_e=pe+2*Ae,Le={data:new o.q({width:_e,height:_e},le),pixelRatio:2,sdf:!1,usvg:!1,version:0};I.set(q,Le)}return I}queryRasterArrayValueByBandId(f,w,I){const R=w._mrt;return new Promise(q=>{const V={},Z=new Set;for(const[te,le]of Object.entries(R.layers)){if(I.layerName&&te!==I.layerName)continue;const pe={};V[te]=pe;for(const{bands:Ae}of le.dataIndex)for(const _e of Ae)I.bands&&!I.bands.includes(_e)||(Z.add(o.t(te,_e)),w.fetchBand(te,null,_e,Le=>{o.o.frame(()=>{pe[_e]=Le?null:Tp([f.lng,f.lat],R,le.getBandView(_e)),Z.delete(o.t(te,_e)),Z.size===0&&q(V)})},!1))}Z.size===0&&q(V)})}_loadTileForQuery(f,w){if(this._loadTileLoaded[f.uid])return void w(null,f._mrt);if(this._loadTilePending[f.uid])return void this._loadTilePending[f.uid].push(w);this._loadTilePending[f.uid]=[w];const I=this.map._requestManager.normalizeTileURL(f.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),R=this.map._requestManager.transformRequest(I,o.R.Tile);f.actor.send("loadTile",{request:R,uid:f.uid,tileID:f.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(q,V,Z)=>{if(q)return this._loadTilePending[f.uid].forEach(te=>te(q,null)),void delete this._loadTilePending[f.uid];if(!V)return this._loadTilePending[f.uid].forEach(te=>te(null,null)),void delete this._loadTilePending[f.uid];if(this.map._refreshExpiredTiles&&V){const te=o.aR(Z);f.setExpiryData(te)}f._mrt=V,f._isHeaderLoaded=!0,f.state="loaded",this._loadTilePending[f.uid].forEach(te=>te(null,V)),this._loadTileLoaded[f.uid]=!0,delete this._loadTilePending[f.uid]},void 0,!0)}queryRasterArrayValueByAllBands(f,w,I){return new Promise((R,q)=>{this._loadTileForQuery(w,(V,Z)=>{V?q(V):R(Z?this.queryRasterArrayValueByBandId(f,w,I):null)})})}queryRasterArrayValue(f,w){const I=o.aX.convert(f),R=this.findLoadedParent(I);return R&&R._mrt?w.bands||!this.partial?this.queryRasterArrayValueByBandId(I,R,w):this.queryRasterArrayValueByAllBands(I,R,w):Promise.resolve(null)}findLoadedParent(f){const w=o.ad.fromLngLat(f,this.map.transform.tileSize),I=this.maxzoom+1,R=1<{if(R.signal.aborted)return;if(q)return void f(q);const Z=V?V.find(le=>le!=null):null,te=o.aP(this._options,Z,this.map._requestManager);te instanceof Error?f(te):f(null,te)}),{cancel:()=>R.abort()}}loadTile(E,f){const w=this.map._requestManager.normalizeTileURL(E.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),I=this.map._requestManager.transformRequest(w,o.R.Tile),R={uid:E.uid,tileID:E.tileID,source:this.id,type:this.type,scope:this.scope,request:I,encoding:this.encoding};E.actor&&E.state!=="expired"||(E.actor=this.dispatcher.getActor(),E.request=E.actor.send("loadTile",R,(function(q,V){return delete E.request,E.aborted?(E.state="unloaded",f(null)):q?(E.state="errored",f(q)):(V&&(this.map._refreshExpiredTiles&&E.setExpiryData(V),V.borderReady||E.neighboringTiles||(E.neighboringTiles=this._getNeighboringTiles(E.tileID)),E.dem=V.dem,E.dem.onDeserialize(),E.needsHillshadePrepare=!0,E.needsDEMTextureUpload=!0),E.state="loaded",void f(null))}).bind(this),void 0,!0))}abortTile(E,f){E.request&&(E.request.cancel(),delete E.request),E.actor&&E.actor.send("abortTile",{uid:E.uid,type:this.type,source:this.id,scope:this.scope}),f&&f()}_getNeighboringTiles(E){const f=E.canonical,w=Math.pow(2,f.z),I=(f.x-1+w)%w,R=f.x===0?E.wrap-1:E.wrap,q=(f.x+1+w)%w,V=f.x+1===w?E.wrap+1:E.wrap,Z={};return Z[new o.aU(E.overscaledZ,R,f.z,I,f.y).key]={backfilled:!1},Z[new o.aU(E.overscaledZ,V,f.z,q,f.y).key]={backfilled:!1},f.y>0&&(Z[new o.aU(E.overscaledZ,R,f.z,I,f.y-1).key]={backfilled:!1},Z[new o.aU(E.overscaledZ,E.wrap,f.z,f.x,f.y-1).key]={backfilled:!1},Z[new o.aU(E.overscaledZ,V,f.z,q,f.y-1).key]={backfilled:!1}),f.y+1{if(this._loaded=!0,this._pendingLoad=null,I)this.fire(new o.y(I));else{const q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&R&&R.resourceTiming&&R.resourceTiming[this.id]&&(q.resourceTiming=R.resourceTiming[this.id]),E&&(this._partialReload=!0),this.fire(new o.z("data",q)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(E),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const E=o.t(this.id,this.scope);this.map.style.clearSource(E),this._updateWorkerData()}loadTile(E,f){const w=E.actor?"reloadTile":"loadTile";E.actor=this.actor;const I=this.map.style?this.map.style.getLut(this.scope):null,R=I?{image:I.image.clone()}:null,q=this._partialReload,V={type:this.type,uid:E.uid,tileID:E.tileID,tileZoom:E.tileZoom,zoom:E.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:R,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:E.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};E.request=this.actor.send(w,V,(Z,te)=>q&&!te?(E.state="loaded",f(null)):(delete E.request,E.destroy(!1),E.aborted?f(null):Z?f(Z):(E.loadVectorData(te,this.map.painter,w==="reloadTile"),f(null))),void 0,w==="loadTile")}abortTile(E){E.request&&(E.request.cancel(),delete E.request),E.aborted=!0}unloadTile(E,f){this.actor.send("removeTile",{uid:E.uid,type:this.type,source:this.id,scope:this.scope}),E.destroy()}onRemove(E){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aY{constructor(E,f,w,I){super(E,f,w,I),this.roundZoom=!0,this.type="video",this.options=f}load(){this._loaded=!1;const E=this.options;this.urls=[];for(const f of E.urls)this.urls.push(this.map._requestManager.transformRequest(f,o.R.Source).url);o.aZ(this.urls,(f,w)=>{this._loaded=!0,f?this.fire(new o.y(f)):w&&(this.video=w,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(E){if(this.video){const f=this.video.seekable;Ef.end(0)?this.fire(new o.y(new $s(`sources.${this.id}`,null,`Playback for this video can be set only between the ${f.start(0)} and ${f.end(0)}-second mark.`))):this.video.currentTime=E}}getVideo(){return this.video}onAdd(E){this.map||(this.map=E,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const E=this.map.painter.context,f=E.gl;this.texture?this.video.paused||(this.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE),f.texSubImage2D(f.TEXTURE_2D,0,0,0,f.RGBA,f.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(E,this.video,f.RGBA8),this.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(E)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aY,model:o.a$,"batched-model":class extends o.E{constructor(E,f,w,I){super(),this.type="batched-model",this.id=E,this.tileSize=512,this._options=f,this.tiles=this._options.tiles,this.maxzoom=f.maxzoom||19,this.minzoom=f.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=w,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(I)}onAdd(E){this.map=E,this.load()}reload(){this.cancelTileJSONRequest();const E=o.t(this.id,this.scope);this.load(()=>this.map.style.clearSource(E))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(E){this._loaded=!1,this.fire(new o.z("dataloading",{dataType:"source"}));const f=Array.isArray(this.map._language)?this.map._language.join():this.map._language,w=this.map.getWorldview();this._tileJSONRequest=o.aN(this._options,this.map._requestManager,f,w,(I,R)=>{this._tileJSONRequest=null,this._loaded=!0,I?(f&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${f}`),w&&w.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${w}`),this.fire(new o.y(I))):R&&(Object.assign(this,R),R.bounds&&(this.tileBounds=new Gn(R.bounds,this.minzoom,this.maxzoom)),Te(R.tiles,this.map._requestManager._customAccessToken),this.fire(new o.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.z("data",{dataType:"source",sourceDataType:"content"}))),E&&E(I)})}hasTransition(){return!1}hasTile(E){return!this.tileBounds||this.tileBounds.contains(E.canonical)}loaded(){return this._loaded}loadTile(E,f){const w=this.map._requestManager.normalizeTileURL(E.tileID.canonical.url(this.tiles,this.scheme)),I={request:this.map._requestManager.transformRequest(w,o.R.Tile),data:void 0,uid:E.uid,tileID:E.tileID,tileZoom:E.tileZoom,zoom:E.tileID.overscaledZ,tileSize:this.tileSize*E.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:E.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(E.actor&&E.state!=="expired")if(E.state==="loading")E.reloadCallback=f;else{if(E.buckets){const q=Object.values(E.buckets);for(const V of q)V.dirty=!0;return void(E.state="loaded")}E.request=E.actor.send("reloadTile",I,R.bind(this))}else E.actor=this.dispatcher.getActor(),E.request=E.actor.send("loadTile",I,R.bind(this),void 0,!0);function R(q,V){return E.aborted?f(null):q&&q.status!==404?f(q):(this.map._refreshExpiredTiles&&V&&E.setExpiryData(V),E.loadModelData(V,this.map.painter),E.state="loaded",void f(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aY{constructor(E,f,w,I){super(E,f,w,I),f.coordinates?Array.isArray(f.coordinates)&&f.coordinates.length===4&&!f.coordinates.some(R=>!Array.isArray(R)||R.length!==2||R.some(q=>typeof q!="number"))||this.fire(new o.y(new $s(`sources.${E}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.y(new $s(`sources.${E}`,null,'missing required property "coordinates"'))),f.animate&&typeof f.animate!="boolean"&&this.fire(new o.y(new $s(`sources.${E}`,null,'optional "animate" property must be a boolean value'))),f.canvas?typeof f.canvas=="string"||f.canvas instanceof HTMLCanvasElement||this.fire(new o.y(new $s(`sources.${E}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new o.y(new $s(`sources.${E}`,null,'missing required property "canvas"'))),this.options=f,this.animate=f.animate===void 0||f.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.y(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(E){this.map=E,this.load(),this.canvas&&this.animate&&this.play()}onRemove(E){this.pause()}prepare(){let E=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,E=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,E=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const f=this.map.painter.context;this.texture?!E&&!this._playing||this.texture instanceof o.a_||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(f,this.canvas,f.gl.RGBA8,{premultiply:!0}),this._prepareData(f)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const E of[this.canvas.width,this.canvas.height])if(isNaN(E)||E<=0)return!0;return!1}},custom:class extends o.E{constructor(E,f,w,I){super(),this.id=E,this.type="custom",this._dataType="raster",this._dispatcher=w,this._implementation=f,this.setEventedParent(I),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.y(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.y(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new Gn(this._implementation.bounds,this.minzoom,this.maxzoom));const R=f;R.update=this._update.bind(this),R.clearTiles=this._clearTiles.bind(this),R.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aK(f,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aK(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.z("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(E){this.map=E,this._loaded=!1,this.fire(new o.z("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(E),this.load()}onRemove(E){this._implementation.onRemove&&this._implementation.onRemove(E)}hasTile(E){if(this._implementation.hasTile){const{x:f,y:w,z:I}=E.canonical;return this._implementation.hasTile({x:f,y:w,z:I})}return!this.tileBounds||this.tileBounds.contains(E.canonical)}loadTile(E,f){const{x:w,y:I,z:R}=E.tileID.canonical,q=new AbortController,V=Promise.resolve(this._implementation.loadTile({x:w,y:I,z:R},{signal:q.signal})).then((function(Z){return delete E.request,E.aborted?(E.state="unloaded",f(null)):Z===void 0?(E.state="errored",f(null)):Z===null?(this.loadTileData(E,{width:this.tileSize,height:this.tileSize,data:null}),E.state="loaded",f(null)):function(te){return te instanceof ImageData||te instanceof HTMLCanvasElement||te instanceof ImageBitmap||te instanceof HTMLImageElement}(Z)?(this.loadTileData(E,Z),E.state="loaded",void f(null)):(E.state="errored",f(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(Z=>{Z.name!=="AbortError"&&(E.state="errored",f(Z))});V.cancel=()=>q.abort(),E.request=V}loadTileData(E,f){E.setTexture(f,this.map.painter)}unloadTile(E,f){if(E.texture&&E.texture instanceof o.T?(E.destroy(!1),E.texture&&E.texture instanceof o.T&&this.map.painter.saveTileTexture(E.texture)):E.destroy(),this._implementation.unloadTile){const{x:w,y:I,z:R}=E.tileID.canonical;this._implementation.unloadTile({x:w,y:I,z:R})}f&&f()}abortTile(E,f){E.request&&E.request.cancel&&(E.request.cancel(),delete E.request),f&&f()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(E=>({x:E.canonical.x,y:E.canonical.y,z:E.canonical.z}))}_clearTiles(){const E=o.t(this.id,this.scope);this.map.style.clearSource(E)}_update(){this.fire(new o.z("data",{dataType:"source",sourceDataType:"content"}))}}},U_=function(E,f,w,I){const R=new Wa[f.type](E,f,w,I);if(R.id!==E)throw new Error(`Expected Source id to be ${E} instead of ${R.id}`);return o.b0(["load","abort","unload","serialize","prepare"],R),R};function $z(E,f,w=""){return`${w}:${f.id||""}:${f.layer.id}:${function(I){if("layerId"in I)return`layer:${I.layerId}`;{const{featuresetId:R,importId:q}=I;return`featureset:${R}${q?`:import:${q}`:""}`}}(E.target)}`}function Uz(E,f,w,I=""){if(E.uniqueFeatureID){const R=$z(E,f,I);if(w.has(R))return!0;w.add(R)}return!1}function qz(E,f,w,I,R=!1,q=void 0){const V=f.sourceCache.transform,Z=f.sourceCache.tilesIn(E,f.has3DLayers,R);Z.sort(uT);const te=[];for(const le of Z){const pe=le.tile.queryRenderedFeatures(f,le,w,I,V,R,q);Object.keys(pe).length&&te.push({wrappedTileID:le.tile.tileID.wrapped().key,queryResults:pe})}for(const le in f.layers){const pe=f.layers[le];if(pe.styleLayer){const Ae=pe.styleLayer.queryRenderedFeatures(E,f.sourceCache,I);Object.keys(Ae).length&&te.push({wrappedTileID:0,queryResults:Ae})}}return te.length===0?{}:function(le){const pe={},Ae={};for(const _e of le){const Le=_e.queryResults,Ve=_e.wrappedTileID,qe=Ae[Ve]=Ae[Ve]||{};for(const Ze in Le){const Xe=Le[Ze],ht=qe[Ze]=qe[Ze]||{},vt=pe[Ze]=pe[Ze]||[];for(const st of Xe)ht[st.featureIndex]||(ht[st.featureIndex]=!0,vt.push(st))}}return pe}(te)}function dT(E,f,w,I,R,q){const V={},Z=I.queryRenderedSymbols(E),te=[];for(const le of Object.keys(Z).map(Number))te.push(R[le]);te.sort(uT);for(const le of te){const pe=le.featureIndex.lookupSymbolFeatures(Z[le.bucketInstanceId],le.bucketIndex,le.sourceLayerIndex,f,w,q);for(const Ae in pe){const _e=V[Ae]=V[Ae]||[],Le=pe[Ae];Le.sort((Ve,qe)=>{const Ze=le.featureSortOrder;if(Ze){const Xe=Ze.indexOf(Ve.featureIndex);return Ze.indexOf(qe.featureIndex)-Xe}return qe.featureIndex-Ve.featureIndex});for(const Ve of Le)_e.push(Ve)}}return V}function Ep(E,f){const w=E.getRenderableIds().map(q=>E.getTileByID(q)),I=[],R={};for(let q=0;q{if(q)w(q);else try{const te=I.getHeaderLength(V);if(te>f)return void(this.request=this.fetchHeader(te,w));I.parseHeader(V),this._isHeaderLoaded=!0;let le=0;for(const pe of Object.values(I.layers))le=Math.max(le,pe.dataIndex.at(-1).lastByte);V.byteLength>=le&&(this.entireBuffer=V),w(null,this.entireBuffer||V,Z)}catch(te){w(te)}}),this.request}fetchBandForRender(f,w,I,R){this.fetchBand(f,w,I,q=>{if(q)return void R(q);this.updateTextureDescriptor(f,w,I);const V=this.textureDescriptorPerLayer.get(w);R(null,V?V.img:null)})}fetchBand(f,w,I,R,q=!0){const V=this._mrt;if(!this._isHeaderLoaded||!V)return void R(new Error("Tile header is not ready"));const Z=this.actor;if(!Z)return void R(new Error("Can't fetch tile band without an actor"));let te;const le=o.t(String(I),o.t(this.tileID.key,f));let pe=this._taskQueue.get(le);pe?pe.add(R):(pe=new Set,pe.add(R),this._taskQueue.set(le,pe));const Ae=(qe,Ze)=>{te.complete(qe,Ze),qe?R(qe):(pe.forEach(Xe=>Xe(null,Ze)),this._taskQueue.delete(le))},_e=(qe,Ze)=>{if(qe)return R(qe);const Xe=Z.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:Ze,task:te},Ae,void 0,!0);if(w!==null){const ht=this._workQueuePerLayer.get(w)||[];ht.push(()=>{Xe&&Xe.cancel(),te.cancel()}),this._workQueuePerLayer.has(w)||this._workQueuePerLayer.set(w,ht)}};let Le;try{Le=V.getLayer(f)}catch(qe){if(this.state==="reloading")return;throw qe}if(!Le)return void R(new Error(`Unknown sourceLayer "${f}"`));if(Le.hasDataForBand(I))return pe.forEach(qe=>qe(null,null)),void this._taskQueue.delete(le);const Ve=Le.getDataRange([I]);if(te=V.createDecodingTask(Ve),!te||te.tasks.length)if(w!==null&&this.flushQueues(w),this.entireBuffer)_e(null,this.entireBuffer.slice(Ve.firstByte,Ve.lastByte+1));else{const qe=Object.assign({},this.requestParams,{headers:{Range:`bytes=${Ve.firstByte}-${Ve.lastByte}`}}),Ze=o.b4(qe,_e);if(w!==null){const Xe=this._fetchQueuePerLayer.get(w)||[];Xe.push(()=>{Ze.cancel(),te.cancel()}),this._fetchQueuePerLayer.has(w)||this._fetchQueuePerLayer.set(w,Xe)}}}updateNeeded(f,w){return(!this.textureDescriptorPerLayer.get(f)||this.textureDescriptorPerLayer.get(f).band!==w||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(f,w,I){if(!this._mrt)return;const R=this._mrt.getLayer(f);if(!R||!R.hasBand(I)||!R.hasDataForBand(I))return;const{bytes:q,tileSize:V,buffer:Z,offset:te,scale:le}=R.getBandView(I),pe=V+2*Z,Ae=new o.q({width:pe,height:pe},q),_e=this.texturePerLayer.get(w);_e&&_e instanceof o.T&&_e.update(Ae,{premultiply:!1}),this.textureDescriptorPerLayer.set(w,{layer:f,band:I,img:Ae,buffer:Z,offset:te,tileSize:V,format:R.pixelFormat,mix:[le,256*le,65536*le,16777216*le]})}destroy(f=!1){if(super.destroy(f),delete this._mrt,!f)for(const w of this.texturePerLayer.values())w&&w instanceof o.T&&w.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 Gr{constructor(f,w){this.max=f,this.onRemove=w,this.reset()}reset(){for(const f in this.data)for(const w of this.data[f])w.timeout&&clearTimeout(w.timeout),this.onRemove(w.value);return this.data={},this.order=[],this}add(f,w,I){const R=f.wrapped().key;this.data[R]===void 0&&(this.data[R]=[]);const q={value:w,timeout:void 0};if(I!==void 0&&(q.timeout=setTimeout(()=>{this.remove(f,q)},I)),this.data[R].push(q),this.order.push(R),this.order.length>this.max){const V=this._getAndRemoveByKey(this.order[0]);V&&this.onRemove(V)}return this}has(f){return f.wrapped().key in this.data}getAndRemove(f){return this.has(f)?this._getAndRemoveByKey(f.wrapped().key):null}_getAndRemoveByKey(f){const w=this.data[f].shift();return w.timeout&&clearTimeout(w.timeout),this.data[f].length===0&&delete this.data[f],this.order.splice(this.order.indexOf(f),1),w.value}getByKey(f){const w=this.data[f];return w?w[0].value:null}get(f){return this.has(f)?this.data[f.wrapped().key][0].value:null}remove(f,w){if(!this.has(f))return this;const I=f.wrapped().key,R=w===void 0?0:this.data[I].indexOf(w),q=this.data[I][R];return this.data[I].splice(R,1),q.timeout&&clearTimeout(q.timeout),this.data[I].length===0&&delete this.data[I],this.onRemove(q.value),this.order.splice(this.order.indexOf(I),1),this}setMaxSize(f){for(this.max=f;this.order.length>this.max;){const w=this._getAndRemoveByKey(this.order[0]);w&&this.onRemove(w)}return this}filter(f){const w=[];for(const I in this.data)for(const R of this.data[I])f(R.value)||w.push(R);for(const I of w)this.remove(I.value.tileID,I)}}class _i{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(f,w,I){const R=String(w);if(this.stateChanges[f]=this.stateChanges[f]||{},this.stateChanges[f][R]=this.stateChanges[f][R]||{},Object.assign(this.stateChanges[f][R],I),this.deletedStates[f]===null){this.deletedStates[f]={};for(const q in this.state[f])q!==R&&(this.deletedStates[f][q]=null)}else if(this.deletedStates[f]&&this.deletedStates[f][R]===null){this.deletedStates[f][R]={};for(const q in this.state[f][R])I[q]||(this.deletedStates[f][R][q]=null)}else for(const q in I)this.deletedStates[f]&&this.deletedStates[f][R]&&this.deletedStates[f][R][q]===null&&delete this.deletedStates[f][R][q]}removeFeatureState(f,w,I){if(this.deletedStates[f]===null)return;const R=String(w);if(this.deletedStates[f]=this.deletedStates[f]||{},I&&w!==void 0)this.deletedStates[f][R]!==null&&(this.deletedStates[f][R]=this.deletedStates[f][R]||{},this.deletedStates[f][R][I]=null);else if(w!==void 0)if(this.stateChanges[f]&&this.stateChanges[f][R])for(I in this.deletedStates[f][R]={},this.stateChanges[f][R])this.deletedStates[f][R][I]=null;else this.deletedStates[f][R]=null;else this.deletedStates[f]=null}getState(f,w){const I=this.state[f]||{},R=this.stateChanges[f]||{},q=this.deletedStates[f];if(q===null)return{};if(w!==void 0){const Z=String(w),te=Object.assign({},I[Z],R[Z]);if(q){const le=q[w];if(le===null)return{};for(const pe in le)delete te[pe]}return te}const V=Object.assign({},I,R);if(q)for(const Z in q)delete V[Z];return V}initializeTileState(f,w){f.refreshFeatureState(w)}coalesceChanges(f,w){const I={};for(const R in this.stateChanges){this.state[R]=this.state[R]||{};const q={};for(const V in this.stateChanges[R])this.state[R][V]||(this.state[R][V]={}),Object.assign(this.state[R][V],this.stateChanges[R][V]),q[V]=this.state[R][V];I[R]=q}for(const R in this.deletedStates){this.state[R]=this.state[R]||{};const q={};if(this.deletedStates[R]===null)for(const V in this.state[R])q[V]={},this.state[R][V]={};else for(const V in this.deletedStates[R]){if(this.deletedStates[R][V]===null)this.state[R][V]={};else if(this.state[R][V])for(const Z of Object.keys(this.deletedStates[R][V]))delete this.state[R][V][Z];q[V]=this.state[R][V]}I[R]=I[R]||{},Object.assign(I[R],q)}if(this.stateChanges={},this.deletedStates={},Object.keys(I).length!==0)for(const R in f)f[R].refreshFeatureState(w,I)}}class $a extends o.E{constructor(f,w,I){super(),this.id=f,this._renderSourceType=I,this._maxzoomOverride=null,w.on("data",R=>{R.dataType==="source"&&R.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&R.dataType==="source"&&R.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),w.on("error",()=>{this._sourceErrored=!0}),this._source=w,this._tiles={},this._cache=new Gr(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=w.minTileCacheSize,this._maxTileCacheSize=w.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new _i,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(f){this.map=f,this._minTileCacheSize=this._minTileCacheSize===void 0&&f?f._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&f?f._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const f in this._tiles)if(!this._tiles[f].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const f=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,f&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(f){this._maxzoomOverride=f}_loadTile(f,w){return f.renderSourceType=this._renderSourceType,f.isExtraShadowCaster=this._shadowCasterTiles[f.tileID.key],this._source.loadTile(f,w)}_unloadTile(f){if(this._source.unloadTile)return this._source.unloadTile(f)}_abortTile(f){if(this._source.abortTile)return this._source.abortTile(f)}serialize(){return this._source.serialize()}prepare(f){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const w in this._tiles){const I=this._tiles[w];I.upload(f,this.map?this.map.painter:void 0),I.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(f=>f.tileID).sort(ah).map(f=>f.key)}getRenderableIds(f,w){const I=[];for(const R in this._tiles)this._isIdRenderable(+R,f,w)&&I.push(this._tiles[R]);return f?I.sort((R,q)=>{const V=R.tileID,Z=q.tileID,te=new o.P(V.canonical.x,V.canonical.y)._rotate(this.transform.angle),le=new o.P(Z.canonical.x,Z.canonical.y)._rotate(this.transform.angle);return V.overscaledZ-Z.overscaledZ||le.y-te.y||le.x-te.x}).map(R=>R.tileID.key):I.map(R=>R.tileID).sort(ah).map(R=>R.key)}hasRenderableParent(f){const w=this.findLoadedParent(f,0);return!!w&&this._isIdRenderable(w.tileID.key)}_isIdRenderable(f,w,I){return this._tiles[f]&&this._tiles[f].hasData()&&!this._coveredTiles[f]&&(w||!this._tiles[f].holdingForFade())&&(I||!this._shadowCasterTiles[f])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const f in this._tiles)this._tiles[f].state!=="errored"&&this._reloadTile(+f,"reloading")}}_reloadTile(f,w){const I=this._tiles[f];I&&(I.state!=="loading"&&(I.state=w),this._loadTile(I,this._tileLoaded.bind(this,I,f,w)))}_tileLoaded(f,w,I,R,q){if(R){if(f.state="errored",o.b5(R)){if(this._source.fire(new o.z("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:f})),!(f.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const Z=this.map.painter.terrain;this.update(this.transform,Z.getScaledDemTileSize(),!0),Z.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.y(R,{tile:f}));return}f.timeAdded=o.o.now(),I==="expired"&&(f.refreshedUponExpiration=!0),this._setTileReloadTimer(w,f),this._source.type==="raster-dem"&&f.dem&&this._backfillDEM(f),this._state.initializeTileState(f,this.map?this.map.painter:null);let V=new Map;q&&q.responseHeaders&&(V=q.responseHeaders),this._source.fire(new o.z("data",{dataType:"source",tile:f,coord:f.tileID,sourceCacheId:this.id,responseHeaders:V}))}_hasTunnelGeometry(){for(const f in this._tiles){const w=this._tiles[f];if(w&&w.hasTunnelGeometry)return!0}return!1}_backfillDEM(f){const w=this.getRenderableIds();for(let R=0;R1||(Math.abs(V)>1&&(Math.abs(V+te)===1?V+=te:Math.abs(V-te)===1&&(V-=te)),q.dem&&R.dem&&(R.dem.backfillBorder(q.dem,V,Z),R.neighboringTiles&&R.neighboringTiles[le]&&(R.neighboringTiles[le].backfilled=!0)))}}getTile(f){return this.getTileByID(f.key)}getTileByID(f){return this._tiles[f]}_retainLoadedChildren(f,w,I,R){for(const q in this._tiles){let V=this._tiles[q];if(R[q]||!V.hasData()||V.tileID.overscaledZ<=w||V.tileID.overscaledZ>I)continue;let Z=V.tileID;for(;V&&V.tileID.overscaledZ>w+1;){const le=V.tileID.scaledTo(V.tileID.overscaledZ-1);V=this._tiles[le.key],V&&V.hasData()&&(Z=le)}let te=Z;for(;te.overscaledZ>w;)if(te=te.scaledTo(te.overscaledZ-1),f[te.key]){R[Z.key]=Z;break}}}findLoadedParent(f,w){if(f.key in this._loadedParentTiles){const I=this._loadedParentTiles[f.key];return I&&I.tileID.overscaledZ>=w?I:null}for(let I=f.overscaledZ-1;I>=w;I--){const R=f.scaledTo(I),q=this._getLoadedTile(R);if(q)return q}}_getLoadedTile(f){const w=this._tiles[f.key];return w&&w.hasData()?w:this._cache.getByKey(this._source.reparseOverscaled?f.wrapped().key:f.canonical.key)}updateCacheSize(f,w){w=w||this._source.tileSize;const I=Math.ceil(f.width/w)+1,R=Math.ceil(f.height/w)+1,q=Math.floor(I*R*5),V=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,q):q,Z=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,V):V;this._cache.setMaxSize(Z)}handleWrapJump(f){const w=Math.round((f-(this._prevLng===void 0?f:this._prevLng))/360);if(this._prevLng=f,w){const I={};for(const R in this._tiles){const q=this._tiles[R];q.tileID=q.tileID.unwrapTo(q.tileID.wrap+w),I[q.tileID.key]=q}this._tiles=I;for(const R in this._timers)clearTimeout(this._timers[R]),delete this._timers[R];for(const R in this._tiles)this._setTileReloadTimer(+R,this._tiles[R])}}update(f,w,I,R,q){if(this.transform=f,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!I)return;this.updateCacheSize(f,w),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const V=this._source.type==="batched-model";let Z,te=this._source.maxzoom;this._maxzoomOverride!==null&&(te=Math.min(te,this._maxzoomOverride));const le=this.map&&this.map.painter?this.map.painter._terrain:null;if(le&&le.sourceCache===this&&le.attenuationRange()){const Le=le.attenuationRange()[0],Ve=Math.floor(Le)-Math.log2(le.getDemUpscale());te>Ve&&(te=Ve)}const pe=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)Z=f.getVisibleUnwrappedCoordinates(this._source.tileID).map(Le=>new o.aU(Le.canonical.z,Le.wrap,Le.canonical.z,Le.canonical.x,Le.canonical.y));else if(this.tileCoverLift!==0){const Le=f.clone();Le.tileCoverLift=this.tileCoverLift,Z=Le.coveringTiles({tileSize:w||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:te,roundZoom:this._source.roundZoom&&!I,reparseOverscaled:pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:V}),this._source.minzoom<=1&&f.projection.name==="globe"&&(Z.push(new o.aU(1,0,1,0,0)),Z.push(new o.aU(1,0,1,1,0)),Z.push(new o.aU(1,0,1,0,1)),Z.push(new o.aU(1,0,1,1,1)))}else if(Z=f.coveringTiles({tileSize:w||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:te,roundZoom:this._source.roundZoom&&!I,reparseOverscaled:pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:V}),this._source.hasTile){const Le=this._source.hasTile.bind(this._source);Z=Z.filter(Ve=>Le(Ve))}}else Z=[];if(Z.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Le=f.coveringZoomLevel({tileSize:w||this._source.tileSize,roundZoom:this._source.roundZoom&&!I}),Ve=Math.min(Le,te);if(V){const qe=f.extendTileCover(Z,Ve);for(const Ze of qe)Z.push(Ze)}else if(q){const qe=this.transform.getFrustum(Ve),Ze=f.extendTileCoverToNearPlane(Z,qe,Ve);for(const Xe of Ze)Z.push(Xe);if(Ve>=18&&this._hasTunnelGeometry()){const Xe=f.extendTileCoverForTunnels(Z,qe,Ve,20);for(const ht of Xe)Z.push(ht)}}else if(this.castsShadows&&R){const qe=f.extendTileCover(Z,Ve,R,16);for(const Ze of qe)this._shadowCasterTiles[Ze.key]=!0,Z.push(Ze)}}const Ae=this._updateRetainedTiles(Z);if(this._supportsFading&&Z.length!==0){const Le={},Ve={},qe=o.o.now(),Ze=Object.keys(Ae);for(const ht of Ze){const vt=Ae[ht],st=this._tiles[ht];if(!st||st.fadeEndTime!==void 0&&st.fadeEndTime<=qe)continue;const Ut=this.findLoadedParent(vt,Math.max(vt.overscaledZ-$a.maxOverzooming,this._source.minzoom));Ut&&(this._addTile(Ut.tileID),Le[Ut.tileID.key]=Ut.tileID),Ve[ht]=vt}const Xe=Z.at(-1).overscaledZ;for(const ht in this._tiles){const vt=this._tiles[ht];if(Ae[ht]||!vt.hasData())continue;let st=vt.tileID;for(;st.overscaledZ>Xe;){st=st.scaledTo(st.overscaledZ-1);const Ut=this._tiles[st.key];if(Ut&&Ut.hasData()&&Ve[st.key]){Ae[ht]=vt.tileID;break}}}for(const ht in Le)Ae[ht]||(this._coveredTiles[ht]=!0,Ae[ht]=Le[ht])}for(const Le in Ae)this._tiles[Le].clearFadeHold();const _e=o.b6(this._tiles,Ae);for(const Le of _e){const Ve=this._tiles[Le];Ve.hasSymbolBuckets&&!Ve.holdingForFade()?Ve.setHoldDuration(this.map._fadeDuration):Ve.hasSymbolBuckets&&!Ve.symbolFadeFinished()||this._removeTile(+Le)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b7.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const f in this._tiles)this._tiles[f].holdingForFade()&&this._removeTile(+f)}_updateRetainedTiles(f){const w={};if(f.length===0)return w;const I={},R=f.reduce((le,pe)=>Math.min(le,pe.overscaledZ),1/0),q=f[0].overscaledZ,V=Math.max(q-$a.maxOverzooming,this._source.minzoom),Z=Math.max(q+$a.maxUnderzooming,this._source.minzoom),te={};for(const le of f){const pe=this._addTile(le);w[le.key]=le,pe.hasData()||R=this._source.maxzoom){const _e=le.children(this._source.maxzoom)[0],Le=this.getTile(_e);if(Le&&Le.hasData()){w[_e.key]=_e;continue}}else{const _e=le.children(this._source.maxzoom);if(w[_e[0].key]&&w[_e[1].key]&&w[_e[2].key]&&w[_e[3].key])continue}let Ae=pe.wasRequested();for(let _e=le.overscaledZ-1;_e>=V;--_e){const Le=le.scaledTo(_e);if(I[Le.key]||(I[Le.key]=!0,pe=this.getTile(Le),!pe&&Ae&&(pe=this._addTile(Le)),pe&&(w[Le.key]=Le,Ae=pe.wasRequested(),pe.hasData())))break}}return w}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const f in this._tiles){const w=[];let I,R=this._tiles[f].tileID;for(;R.overscaledZ>0;){if(R.key in this._loadedParentTiles){I=this._loadedParentTiles[R.key];break}w.push(R.key);const q=R.scaledTo(R.overscaledZ-1);if(I=this._getLoadedTile(q),I)break;R=q}for(const q of w)this._loadedParentTiles[q]=I}}_addTile(f){let w=this._tiles[f.key];if(w)return w.isExtraShadowCaster!==!0||this._shadowCasterTiles[f.key]||this._reloadTile(f.key,"reloading"),w;w=this._cache.getAndRemove(f),w&&(this._setTileReloadTimer(f.key,w),w.tileID=f,this._state.initializeTileState(w,this.map?this.map.painter:null),this._cacheTimers[f.key]&&(clearTimeout(this._cacheTimers[f.key]),delete this._cacheTimers[f.key],this._setTileReloadTimer(f.key,w)));const I=!!w;if(!I){const R=this.map?this.map.painter:null,q=this._source.tileSize*f.overscaleFactor();w=this._source.type==="raster-array"?new E0(f,q,this.transform.tileZoom,R,this._isRaster):new o.b3(f,q,this.transform.tileZoom,R,this._isRaster,this._source.worldview),this._loadTile(w,this._tileLoaded.bind(this,w,f.key,w.state))}return w.uses++,this._tiles[f.key]=w,I||this._source.fire(new o.z("dataloading",{tile:w,coord:w.tileID,dataType:"source"})),w}_setTileReloadTimer(f,w){f in this._timers&&(clearTimeout(this._timers[f]),delete this._timers[f]);const I=w.getExpiryTimeout();I&&(this._timers[f]=setTimeout(()=>{this._reloadTile(f,"expired"),delete this._timers[f]},I))}_removeTile(f){const w=this._tiles[f];w&&(w.uses--,delete this._tiles[f],this._timers[f]&&(clearTimeout(this._timers[f]),delete this._timers[f]),w.uses>0||(w.hasData()&&w.state!=="reloading"||w.state==="empty"?this._cache.add(w.tileID,w,w.getExpiryTimeout()):(w.aborted=!0,this._abortTile(w),this._unloadTile(w))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const f in this._tiles)this._removeTile(+f);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(f,w,I){const R=[],q=this.transform;if(!q)return R;const V=q.projection.name==="globe",Z=o.aG(q.center.lng);for(const te in this._tiles){const le=this._tiles[te];if(I&&le.clearQueryDebugViz(),le.holdingForFade())continue;let pe;if(V){const Ae=le.tileID.canonical;if(Ae.z===0){const _e=[Math.abs(o.aB(Z,...Kx(Ae,-1))-Z),Math.abs(o.aB(Z,...Kx(Ae,1))-Z)];pe=[0,2*_e.indexOf(Math.min(..._e))-1]}else{const _e=[Math.abs(o.aB(Z,...Kx(Ae,-1))-Z),Math.abs(o.aB(Z,...Kx(Ae,0))-Z),Math.abs(o.aB(Z,...Kx(Ae,1))-Z)];pe=[_e.indexOf(Math.min(..._e))-1]}}else pe=[0];for(const Ae of pe){const _e=f.containsTile(le,q,w,Ae);_e&&R.push(_e)}}return R}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(f){return this._getRenderableCoordinates(f)}_getRenderableCoordinates(f,w){const I=this.getRenderableIds(f,w).map(q=>this._tiles[q].tileID),R=this.transform.projection.name==="globe";for(const q of I)q.projMatrix=this.transform.calculateProjMatrix(q.toUnwrapped()),q.expandedProjMatrix=R?this.transform.calculateProjMatrix(q.toUnwrapped(),!1,!0):q.projMatrix;return I}sortCoordinatesByDistance(f){const w=f.slice(),I=this.transform._camera.position,R=this.transform._camera.forward(),q={};for(const V of w){const Z=1/(1<q[V.key]-q[Z.key]),w}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const f=o.o.now();for(const w in this._tiles){const I=this._tiles[w];if(I.fadeEndTime!==void 0&&I.fadeEndTime>=f)return!0}}return!1}setFeatureState(f,w,I){this._state.updateState(f=f||"_geojsonTileLayer",w,I)}removeFeatureState(f,w,I){this._state.removeFeatureState(f=f||"_geojsonTileLayer",w,I)}getFeatureState(f,w){return this._state.getState(f=f||"_geojsonTileLayer",w)}setDependencies(f,w,I){const R=this._tiles[f];R&&R.setDependencies(w,I)}reloadTilesForDependencies(f,w){for(const I in this._tiles)this._tiles[I].hasDependency(f,w)&&this._reloadTile(+I,"reloading");this._cache.filter(I=>!I.hasDependency(f,w))}_preloadTiles(f,w){if(!this._sourceLoaded){const te=()=>{this._sourceLoaded&&(this._source.off("data",te),this._preloadTiles(f,w))};return void this._source.on("data",te)}const I=new Map,R=Array.isArray(f)?f:[f],q=this.map.painter.terrain,V=this.usedForTerrain&&q?q.getScaledDemTileSize():this._source.tileSize;for(const te of R){const le=te.coveringTiles({tileSize:V,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const pe of le)I.set(pe.key,pe);this.usedForTerrain&&te.updateElevation(!1)}const Z=Array.from(I.values());o.ao(Z,(te,le)=>{const pe=new o.b3(te,this._source.tileSize*te.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(pe,Ae=>{this._source.type==="raster-dem"&&pe.dem&&this._backfillDEM(pe),le(Ae,pe)})},w)}}function ah(E,f){const w=Math.abs(2*E.wrap)-+(E.wrap<0),I=Math.abs(2*f.wrap)-+(f.wrap<0);return E.overscaledZ-f.overscaledZ||I-w||f.canonical.y-E.canonical.y||f.canonical.x-E.canonical.x}function Kx(E,f){const w=1<0:I.type==="building"?R=!I.isHidden(f)&&I.paint.get("building-opacity")>0:I.type==="model"&&(R=!I.isHidden(f)&&I.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!R&&w.visible,w.visible=R}}updateZOffset(f,w){this.currentBuildingBuckets=[];for(const R of this.layers){const q=R.layer,V=this.style.getLayerSourceCache(q);let Z=1;q.type==="fill-extrusion"?Z=R.visible?q.paint.get("fill-extrusion-vertical-scale"):0:q.type==="building"&&(Z=R.visible?q.paint.get("building-vertical-scale"):0);let te=V?V.getTile(w):null;if(!te&&V)for(const le in V._tiles){const pe=V._tiles[le];if(w.canonical.isChildOf(pe.tileID.canonical)){te=pe;break}}this.currentBuildingBuckets.push({bucket:te?te.getBucket(q):null,tileID:te?te.tileID:w,verticalScale:Z})}f.hasAnyZOffset=!1;let I=!1;for(let R=0;R{I in f&&(w[I]=f[I])}),w}function uu(E){E=E.slice();const f=Object.create(null);for(const w of E)f[w.id]=w;for(let w=0;w0?(R-V)/Z:0;return this.points[q].mult(1-te).add(this.points[w].mult(te))}}const G_=Math.tan(85*Math.PI/180);function Rl(E,f,w,I,R,q,V){const Z=o.bd();if(w)if(q.name==="globe"){const te=o.be(R,f);o.aC(Z,Z,te)}else{const te=o.bf([],V);Z[0]=te[0],Z[1]=te[1],Z[4]=te[2],Z[5]=te[3],I||o.bc(Z,Z,R.angle)}else o.aC(Z,R.labelPlaneMatrix,E);return Z}function Ff(E,f,w,I,R,q,V){const Z=Rl(E,f,w,I,R,q,V);return q.name==="globe"&&w||(Z[2]=Z[6]=Z[10]=Z[14]=0),Z}function Ap(E,f,w,I,R,q,V){if(w){if(q.name==="globe"){const Z=Rl(E,f,w,I,R,q,V);return o.ba(Z,Z),o.aC(Z,E,Z),Z}{const Z=o.bb(E),[te,le,pe,Ae]=V,[_e,Le,Ve,qe,Ze,Xe,ht,vt]=Z;return Z[0]=te*_e+le*Ze,Z[1]=te*Le+le*Xe,Z[2]=te*Ve+le*ht,Z[3]=te*qe+le*vt,Z[4]=pe*_e+Ae*Ze,Z[5]=pe*Le+Ae*Xe,Z[6]=pe*Ve+Ae*ht,Z[7]=pe*qe+Ae*vt,I||o.bc(Z,Z,-R.angle),Z}}return R.glCoordMatrix}function No(E,f,w,I){const R=[E,f,w,1];w?o.aD(R,R,I):Yx(R,R,I);const q=R[3];return R[0]/=q,R[1]/=q,R[2]/=q,R}function hT(E,f){return Math.min(.5+E/f*.5,1.5)}function Mp(E,f){const w=E[0]/E[3],I=E[1]/E[3];return w>=-f[0]&&w<=f[0]&&I>=-f[1]&&I<=f[1]}function W_(E,f,w,I,R,q,V,Z,te,le,pe=1){const Ae=w.transform,_e=I?E.textSizeData:E.iconSizeData,Le=o.bl(_e,w.transform.zoom,pe),Ve=Ae.projection.name==="globe",qe=[256/w.width*2+1,256/w.height*2+1],Ze=I?E.text.dynamicLayoutVertexArray:E.icon.dynamicLayoutVertexArray;Ze.clear();let Xe=null;Ve&&(Xe=I?E.text.globeExtVertexArray:E.icon.globeExtVertexArray);const ht=E.lineVertexArray,vt=I?E.text.placedSymbolArray:E.icon.placedSymbolArray,st=w.transform.width/w.transform.height;let Ut,Pt=!1;for(let Vt=0;VtMath.abs(w)?{useVertical:!0}:E===o.bm.vertical?I>0?{needsFlipping:!0}:null:f!==0&&function(R,q){return R===0||Math.abs(q/R)>G_}(w,I)?f===1?{needsFlipping:!0}:null:w<0?{needsFlipping:!0}:null}function bL(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht,vt){const st=f/24,Ut=E.lineOffsetX*st,Pt=E.lineOffsetY*st,{lineStartIndex:Vt,glyphStartIndex:St,numGlyphs:Ct,segment:qt,writingMode:Zt,flipState:Wt}=E,hs=Vt+E.lineLength,ms=Zs=>{if(pe){const[Ps,Ms,Rs]=Zs.up,xr=le.length;o.bo(pe,xr+0,Ps,Ms,Rs),o.bo(pe,xr+1,Ps,Ms,Rs),o.bo(pe,xr+2,Ps,Ms,Rs),o.bo(pe,xr+3,Ps,Ms,Rs)}const[ts,Ns,rs]=Zs.point;o.bp(le,ts,Ns,rs,Zs.angle)};if(Ct>1){const Zs=mN(st,Z,Ut,Pt,w,Ae,_e,E,te,q,Le,qe,!1,Ze,Xe,ht,vt);if(!Zs)return{notEnoughRoom:!0};if(I&&!w){let[ts,Ns,rs]=Zs.first.point,[Ps,Ms,Rs]=Zs.last.point;[ts,Ns]=No(ts,Ns,rs,V),[Ps,Ms]=No(Ps,Ms,Rs,V);const xr=mT(Zt,Wt,(Ps-ts)*Ve,Ms-Ns);if(E.flipState=xr&&xr.needsFlipping?1:2,xr)return xr}ms(Zs.first);for(let ts=St+1;ts0?Ps:fN(_e,rs,ts,1,R,void 0,Ze,Xe.canonical),Rs=mT(Zt,Wt,(Ms[0]-ts[0])*Ve,Ms[1]-ts[1]);if(E.flipState=Rs&&Rs.needsFlipping?1:2,Rs)return Rs}const Zs=pN(st*Z.getoffsetX(St),Ut,Pt,w,Ae,_e,qt,Vt,hs,te,q,Le,qe,!1,!1,Ze,Xe,ht,vt);if(!Zs)return{notEnoughRoom:!0};ms(Zs)}return{}}function _L(E,f,w,I,R){const{x:q,y:V,z:Z}=I.projectTilePoint(E.x,E.y,f);if(!R)return No(q,V,Z,w);const[te,le,pe]=R.getElevation(E,R.elevation,R.elevationFeature);return No(q+te,V+le,Z+pe,w)}function fN(E,f,w,I,R,q,V,Z){const te=_L(E.sub(f)._unit()._add(E),Z,R,V,q);return o.aw(te,w,te),o.ax(te,te),o.bi(te,w,te,I)}function pN(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht){const vt=I?E-f:E+f;let st=vt>0?1:-1,Ut=0;I&&(st*=-1,Ut=Math.PI),st<0&&(Ut+=Math.PI);let Pt=Z+V+(st>0?0:1)|0,Vt=R,St=R,Ct=0,qt=0;const Zt=Math.abs(vt),Wt=[],hs=[];let ms=q,Zs=ms,ts=o.bg([]);const Ns=()=>fN(Zs,ms,St,Zt-Ct+1,pe,_e,qe,Ze.canonical);for(;Ct+qt<=Zt;){if(Pt+=st,Pt=te)return null;if(St=Vt,Zs=ms,Wt.push(St),Le&&hs.push(Zs),ms=new o.P(le.getx(Pt),le.gety(Pt)),Vt=Ae[Pt],!Vt){const Vr=_L(ms,Ze.canonical,pe,qe,_e);Vt=Vr[3]>0?Ae[Pt]=Vr:Ns()}Ct+=qt;const Ys=o.aw([],Vt,St),Wr=o.bh(St,Vt);if(w&&Wr>0&&qt>0&&o.bk(ts,Ys)/(qt*Wr)0,vt),Vt=le*Pt.perspectiveRatio,St=(I.x1*w+Z.x-I.padding)*Vt+Pt.point.x,Ct=(I.y1*w+Z.y-I.padding)*Vt+Pt.point.y,qt=(I.x2*w+Z.x+I.padding)*Vt+Pt.point.x,Zt=(I.y2*w+Z.y+I.padding)*Vt+Pt.point.y,Wt=Pt.perspectiveRatio<=.55||Pt.occluded;return!this.isInsideGrid(St,Ct,qt,Zt)||!te&&this.grid.hitTest(St,Ct,qt,Zt,Ae)||Wt?{box:[],offscreen:!1,occluded:Pt.occluded}:{box:[St,Ct,qt,Zt],offscreen:this.isOffscreen(St,Ct,qt,Zt),occluded:!1}}placeCollisionCircles(f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze){const Xe=[],ht=this.transform.elevation,vt=f.getProjection(),st=f.elevationType==="road",Ut=!!ht||st,Pt=o.bx.getAtTileOffsetFunc(Ze,this.transform.center.lat,this.transform.worldSize,vt),Vt=new o.P(I.tileAnchorX,I.tileAnchorY),St=new o.P(I.tileAnchorX,I.tileAnchorY);let{x:Ct,y:qt,z:Zt}=vt.projectTilePoint(St.x,St.y,Ze.canonical),Wt=null;if(Ut){const Wr=st?f.getElevationFeatureForText(R):null;Wt={getElevation:Pt,elevation:ht,elevationFeature:Wr};const[Vr,Ir,Rr]=Pt(Vt,ht,Wr);Ct+=Vr,qt+=Ir,Zt+=Rr}const hs=vt.name==="globe",ms=this.projectAndGetPerspectiveRatio(te,Ct,qt,Zt,Ze,hs||!!ht||this.transform.pitch>0,vt),{perspectiveRatio:Zs}=ms,ts=(_e?Z/Zs:Z*Zs)/o.bC,Ns=No(Ct,qt,Zt,le),rs=I.lineOffsetX*ts,Ps=I.lineOffsetY*ts,Ms=o.am(f.layers[0].layout.get("text-max-angle")),Rs=Math.cos(Ms),xr=ms.signedDistanceFromCamera>0?mN(ts,V,rs,Ps,st&&I.flipState===1,Ns,St,I,q,le,{},Ut&&!_e?Wt:null,_e&&Ut,vt,Ze,_e,Rs):null;let or=!1,Js=!1,Ys=!0;if(xr&&!ms.occluded){const Wr=.5*Ve*Zs+qe,Vr=new o.P(-100,-100),Ir=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Rr=new Hz,{first:mn,last:Ln}=xr,An=mn.path.length;let ta=[];for(let qn=An-1;qn>=1;qn--)ta.push(mn.path[qn]);for(let qn=1;qn(Ut&&!hs&&(Ai=Pt(Liqn[3]<=0)&&(ta=[]));let Ia=[];if(ta.length>0){let qn=1/0,Ha=-1/0,Ai=1/0,Li=-1/0;for(const zi of ta)qn=Math.min(qn,zi[0]),Ai=Math.min(Ai,zi[1]),Ha=Math.max(Ha,zi[0]),Li=Math.max(Li,zi[1]);Ha>=Vr.x&&qn<=Ir.x&&Li>=Vr.y&&Ai<=Ir.y&&(Ia=[ta.map(zi=>new o.P(zi[0],zi[1]))],(qnIr.x||AiIr.y)&&(Ia=o.by(Ia,Vr.x,Vr.y,Ir.x,Ir.y)))}for(const qn of Ia){Rr.reset(qn,.25*Wr);let Ha=0;Ha=Rr.length<=.5*Wr?1:Math.ceil(Rr.paddedLength/Tn)+1;for(let Ai=0;Ai0?(o.aD(te,te,f),this.fogState&&q&&Z.name!=="globe"&&(le=function(_e,Le,Ve,qe,Ze,Xe){const ht=Xe.calculateFogTileMatrix(Ze),vt=[Le,Ve,qe];return o.ae(vt,vt,ht),M1(_e,o.af(vt),Xe.pitch)}(this.fogState,w,I,R,q.toUnwrapped(),this.transform)>.9)):Yx(te,te,f);const pe=te[3];return{point:new o.P((te[0]/pe+1)/2*this.transform.width+Zx,(-te[1]/pe+1)/2*this.transform.height+Zx),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(Z)/pe*.5,1.5),signedDistanceFromCamera:pe,occluded:V&&te[2]>pe||le}}isOffscreen(f,w,I,R){return I=this.screenRightBoundary||Rthis.screenBottomBoundary}isInsideGrid(f,w,I,R){return I>=0&&f=0&&wI.collisionGroupID===w}}return this.collisionGroups[f]}}function Wz(E,f,w,I,R){const{horizontalAlign:q,verticalAlign:V}=o.bJ(E),Z=-(q-.5)*f,te=-(V-.5)*w,le=o.bK(E,I);return new o.P(Z+le[0]*R,te+le[1]*R)}function F1(E,f,w,I,R){const q=new o.P(E,f);return w&&q._rotate(I?R:-R),q}class yN{constructor(f,w,I,R,q,V){this.transform=f.clone(),this.projection=f.projection.name,this.collisionIndex=new wL(this.transform,q),this.buildingIndex=V,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=w,this.retainedQueryData={},this.collisionGroups=new uye(I),this.collisionCircleArrays={},this.prevPlacement=R,R&&(R.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(f,w,I,R,q=1){const V=I.getBucket(w),Z=I.latestFeatureIndex;if(!V||!Z||w.fqid!==V.layerIds[0])return;const te=V.layers[0].layout,le=V.layers[0].paint,pe=I.collisionBoxArray,Ae=Math.pow(2,this.transform.zoom-I.tileID.overscaledZ),_e=I.tileSize/o.ak,Le=I.tileID.toUnwrapped();this.transform.setProjection(V.projection);const Ve=(qe=I.tileID,Ze=V.getProjection(),Xe=this.transform,Ze.name===this.projection?Xe.calculateProjMatrix(qe.toUnwrapped()):hu(Xe,Ze,qe));var qe,Ze,Xe;const ht=te.get("text-pitch-alignment")==="map",vt=te.get("text-rotation-alignment")==="map";w.compileFilter(w.options);const st=w.dynamicFilter(),Ut=w.dynamicFilterNeedsFeature(),Pt=w.dynamicFilterNeedsGeometry(),Vt=this.transform.calculatePixelsToTileUnitsMatrix(I),St=Ff(Ve,I.tileID.canonical,ht,vt,this.transform,V.getProjection(),Vt);let Ct=null;const qt=V.getProjection().createInversionMatrix(this.transform,I.tileID.canonical);if(ht){const Ps=Ap(Ve,I.tileID.canonical,ht,vt,this.transform,V.getProjection(),Vt);Ct=o.aC([],this.transform.labelPlaneMatrix,Ps)}let Zt=null;st&&I.latestFeatureIndex&&(Zt={unwrappedTileID:Le,dynamicFilter:st,dynamicFilterNeedsFeature:Ut,needGeometry:Pt}),this.retainedQueryData[V.bucketInstanceId]=new gN(V.bucketInstanceId,Z,V.sourceLayerIndex,V.index,I.tileID);const[Wt,hs]=V.layers[0].layout.get("text-size-scale-range"),ms=o.aB(q,Wt,hs),[Zs,ts]=te.get("icon-size-scale-range"),Ns=o.aB(q,Zs,ts),rs={bucket:V,layout:te,paint:le,posMatrix:Ve,invMatrix:qt,mercatorCenter:[o.aG(this.transform.center.lng),o.aJ(this.transform.center.lat)],textLabelPlaneMatrix:St,labelToScreenMatrix:Ct,clippingData:Zt,scale:Ae,textPixelRatio:_e,holdingForFade:I.holdingForFade(),collisionBoxArray:pe,partiallyEvaluatedTextSize:o.bl(V.textSizeData,this.transform.zoom,ms),partiallyEvaluatedIconSize:o.bl(V.iconSizeData,this.transform.zoom,Ns),collisionGroup:this.collisionGroups.get(V.sourceID),latestFeatureIndex:I.latestFeatureIndex};if(R)for(const Ps of V.sortKeyRanges){const{sortKey:Ms,symbolInstanceStart:Rs,symbolInstanceEnd:xr}=Ps;f.push({sortKey:Ms,symbolInstanceStart:Rs,symbolInstanceEnd:xr,parameters:rs})}else f.push({symbolInstanceStart:0,symbolInstanceEnd:V.symbolInstances.length,parameters:rs})}attemptAnchorPlacement(f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht,vt,st,Ut){const{textOffset0:Pt,textOffset1:Vt,crossTileID:St}=qe,Ct=[Pt,Vt],qt=Wz(f,V,Z,Ct,te),Zt=this.collisionIndex.placeCollisionBox(Xe,te,w,I,R,q,F1(qt.x,qt.y,le,pe,this.transform.angle),Ve,Ae,_e,Le.predicate);if(vt){const Wt=Xe.getSymbolInstanceIconSize(Ut,this.transform.zoom,qe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(Xe,Wt,vt,I,R,q,F1(qt.x,qt.y,le,pe,this.transform.angle),Ve,Ae,_e,Le.predicate).box.length===0)return}if(Zt.box.length>0){let Wt;return this.prevPlacement&&this.prevPlacement.variableOffsets[St]&&this.prevPlacement.placements[St]&&this.prevPlacement.placements[St].text&&(Wt=this.prevPlacement.variableOffsets[St].anchor),this.variableOffsets[St]={textOffset:Ct,width:V,height:Z,anchor:f,textScale:te,prevAnchor:Wt},this.markUsedJustification(Xe,f,qe,ht),Xe.allowVerticalPlacement&&(this.markUsedOrientation(Xe,ht,qe),this.placedOrientations[St]=ht),{shift:qt,placedGlyphBoxes:Zt}}}placeLayerBucketPart(f,w,I,R,q=1){const{bucket:V,layout:Z,paint:te,posMatrix:le,textLabelPlaneMatrix:pe,labelToScreenMatrix:Ae,clippingData:_e,textPixelRatio:Le,mercatorCenter:Ve,invMatrix:qe,holdingForFade:Ze,collisionBoxArray:Xe,partiallyEvaluatedTextSize:ht,partiallyEvaluatedIconSize:vt,collisionGroup:st,latestFeatureIndex:Ut}=f.parameters,Pt=Z.get("text-optional"),Vt=Z.get("icon-optional"),St=Z.get("text-allow-overlap"),Ct=Z.get("icon-allow-overlap"),qt=Z.get("text-rotation-alignment")==="map",Zt=Z.get("icon-rotation-alignment")==="map",Wt=Z.get("text-pitch-alignment")==="map",hs=te.get("symbol-z-offset"),ms=Z.get("symbol-elevation-reference")==="sea",Zs=Z.get("symbol-placement"),[ts,Ns]=Z.get("text-size-scale-range"),[rs,Ps]=Z.get("icon-size-scale-range"),Ms=o.aB(q,ts,Ns),Rs=o.aB(q,rs,Ps),xr=Z.get("text-variable-anchor"),or=qt&&Zs!=="point",Js=Zt&&Zs!=="point",Ys=xr&&V.hasTextData(),Wr=V.hasIconTextFit()&&Ys&&V.hasIconData();this.transform.setProjection(V.projection);const Vr=Ys||or,Ir=Js||Wr;let Rr=St&&(Ct||!V.hasIconData()||Vt),mn=Ct&&(St||!V.hasTextData()||Pt);const Ln=!hs.isConstant();!V.collisionArrays&&Xe&&V.deserializeCollisionBoxes(Xe),I&&R&&V.updateCollisionDebugBuffers(this.transform.zoom,Xe,Ms,Rs);const An=(Tn,Ia,qn)=>{const{crossTileID:Ha,numVerticalGlyphVertices:Ai}=Tn;let Li=null;if(_e&&_e.dynamicFilterNeedsFeature||Ln){const ii=this.retainedQueryData[V.bucketInstanceId],Mi=Ut.loadFeature({featureIndex:Tn.featureIndex,bucketIndex:ii.bucketIndex,sourceLayerIndex:ii.sourceLayerIndex,layoutVertexArrayOffset:0}),pi=Mi.properties?Mi.properties.worldview:null;if(V.localizable&&V.worldview&&typeof pi=="string")if(pi==="all")Mi.properties.$localized=!0;else{if(!pi.split(",").includes(V.worldview))return;Mi.properties.$localized=!0,Mi.properties.worldview=V.worldview}Li=_e&&_e.needGeometry?o.bH(Mi,!0):Mi}if(_e&&!(0,_e.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:V.worldview},Li,this.retainedQueryData[V.bucketInstanceId].tileID.canonical,new o.P(Tn.tileAnchorX,Tn.tileAnchorY),this.transform.calculateDistanceTileData(_e.unwrappedTileID)))return this.placements[Ha]=new O1(!1,!1,!1,!0),void w.add(Ha);const zi=hs.evaluate(Li,{});if((Tn.zOffset||0)+(zi||0)>0&&this.frontCutoffStart>0){const ii=2*this.frontCutoffStart-1,Mi=[Tn.tileAnchorX,Tn.tileAnchorY,0,1],pi=o.aD(o.bI(),Mi,le);if(pi[1]/pi[3]{ii.tileID=this.retainedQueryData[V.bucketInstanceId].tileID;const Mi=this.transform.elevation;ii.elevation=ms?zi:zi+o.bx.getAtTileOffset(ii.tileID,new o.P(ii.tileAnchorX,ii.tileAnchorY),Mi,Qc),ii.elevation+=Tn.zOffset},dh=qn.textBox;if(dh){nc(dh);const ii=pi=>{let Nl=o.bm.horizontal;if(V.allowVerticalPlacement&&!pi&&this.prevPlacement){const Rc=this.prevPlacement.placedOrientations[Ha];Rc&&(this.placedOrientations[Ha]=Rc,Nl=Rc,this.markUsedOrientation(V,Nl,Tn))}return Nl},Mi=(pi,Nl)=>{if(V.allowVerticalPlacement&&Ai>0&&qn.verticalTextBox){for(const Rc of V.writingModes)if(Rc===o.bm.vertical?($n=Nl(),ho=$n):$n=pi(),$n&&$n.box&&$n.box.length)break}else $n=pi()};if(xr){let pi=xr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Ha]){const Jo=this.prevPlacement.variableOffsets[Ha];pi.indexOf(Jo.anchor)>0&&(pi=pi.filter(Mu=>Mu!==Jo.anchor),pi.unshift(Jo.anchor))}const Nl=(Jo,Mu,Iu)=>{const Rp=V.getSymbolInstanceTextSize(ht,Tn,this.transform.zoom,Ia),_m=(Jo.x2-Jo.x1)*Rp+2*Jo.padding,ef=(Jo.y2-Jo.y1)*Rp+2*Jo.padding,_y=Tn.hasIconTextFit&&!Ct?Mu:null;_y&&nc(_y);let Op={box:[],offscreen:!1,occluded:!1};const WN=St?2*pi.length:pi.length;for(let H0=0;H0=pi.length,Tn,Ia,V,Iu,_y,ht,vt);if(nb&&(Op=nb.placedGlyphBoxes,Op&&Op.box&&Op.box.length)){ai=!0,wi=nb.shift;break}}return Op};Mi(()=>Nl(dh,qn.iconBox,o.bm.horizontal),()=>{const Jo=qn.verticalTextBox;return Jo&&nc(Jo),V.allowVerticalPlacement&&!($n&&$n.box&&$n.box.length)&&Ai>0&&Jo?Nl(Jo,qn.verticalIconBox,o.bm.vertical):{box:null,offscreen:null,occluded:null}}),$n&&(ai=$n.box,la=$n.offscreen,$i=$n.occluded);const Rc=ii(!(!$n||!$n.box));if(!ai&&this.prevPlacement){const Jo=this.prevPlacement.variableOffsets[Ha];Jo&&(this.variableOffsets[Ha]=Jo,this.markUsedJustification(V,Jo.anchor,Tn,Rc))}}else{const pi=(Nl,Rc)=>{const Jo=V.getSymbolInstanceTextSize(ht,Tn,this.transform.zoom,Ia),Mu=this.collisionIndex.placeCollisionBox(V,Jo,Nl,Ve,qe,Vr,new o.P(0,0),St,Le,le,st.predicate);return Mu&&Mu.box&&Mu.box.length&&(this.markUsedOrientation(V,Rc,Tn),this.placedOrientations[Ha]=Rc),Mu};Mi(()=>pi(dh,o.bm.horizontal),()=>{const Nl=qn.verticalTextBox;return V.allowVerticalPlacement&&Ai>0&&Nl?(nc(Nl),pi(Nl,o.bm.vertical)):{box:null,offscreen:null,occluded:null}}),ii(!!($n&&$n.box&&$n.box.length))}}if(qi=$n,ai=qi&&qi.box&&qi.box.length>0,la=qi&&qi.offscreen,$i=qi&&qi.occluded,Tn.useRuntimeCollisionCircles){const ii=Tn.centerJustifiedTextSymbolIndex>=0?Tn.centerJustifiedTextSymbolIndex:Tn.verticalPlacedTextSymbolIndex,Mi=V.text.placedSymbolArray.get(ii),pi=o.bn(V.textSizeData,ht,Mi),Nl=Z.get("text-padding");cl=this.collisionIndex.placeCollisionCircles(V,St,Mi,ii,V.lineVertexArray,V.glyphOffsetArray,pi,le,pe,Ae,I,Wt,st.predicate,Tn.collisionCircleDiameter*pi/o.bC,Nl,this.retainedQueryData[V.bucketInstanceId].tileID),ai=St||cl.circles.length>0&&!cl.collisionDetected,la=la&&cl.offscreen,$i=cl.occluded}if(qn.iconFeatureIndex&&(bc=qn.iconFeatureIndex),qn.iconBox){const ii=Mi=>{nc(Mi);const pi=Tn.hasIconTextFit&&wi?F1(wi.x,wi.y,qt,Wt,this.transform.angle):new o.P(0,0),Nl=V.getSymbolInstanceIconSize(vt,this.transform.zoom,Tn.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(V,Nl,Mi,Ve,qe,Ir,pi,Ct,Le,le,st.predicate)};ho&&ho.box&&ho.box.length&&qn.verticalIconBox?(Oa=ii(qn.verticalIconBox),sa=Oa.box.length>0):(Oa=ii(qn.iconBox),sa=Oa.box.length>0),la=la&&Oa.offscreen,Qo=Oa.occluded}const uh=Pt||Tn.numHorizontalGlyphVertices===0&&Ai===0,Ol=Vt||Tn.numIconVertices===0;if(uh||Ol?Ol?uh||(sa=sa&&ai):ai=sa&&ai:sa=ai=sa&&ai,ai&&qi&&qi.box&&this.collisionIndex.insertCollisionBox(qi.box,Z.get("text-ignore-placement"),V.bucketInstanceId,ho&&ho.box&&Kd?Kd:jl,st.ID),sa&&Oa&&this.collisionIndex.insertCollisionBox(Oa.box,Z.get("icon-ignore-placement"),V.bucketInstanceId,bc,st.ID),cl&&(ai&&this.collisionIndex.insertCollisionCircles(cl.circles,Z.get("text-ignore-placement"),V.bucketInstanceId,jl,st.ID),I)){const ii=V.bucketInstanceId;let Mi=this.collisionCircleArrays[ii];Mi===void 0&&(Mi=this.collisionCircleArrays[ii]=new Gz);for(let pi=0;pi=0;--Ia){const qn=Tn[Ia];An(V.symbolInstances.get(qn),qn,V.collisionArrays[qn])}V.hasAnyZOffset&&o.w(`${V.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(V.hasAnyZOffset){const Tn=V.getSortedIndexesByZOffset();for(let Ia=0;Ia=0&&(f.text.placedSymbolArray.get(q).crossTileID=Ae>=0&&q!==Ae?0:le),V>=0&&(f.text.placedSymbolArray.get(V).crossTileID=Ae>=0&&V!==Ae?0:le),Z>=0&&(f.text.placedSymbolArray.get(Z).crossTileID=Ae>=0&&Z!==Ae?0:le),te>=0&&(f.text.placedSymbolArray.get(te).crossTileID=Ae>=0&&te!==Ae?0:le)}markUsedOrientation(f,w,I){const R=w===o.bm.horizontal||w===o.bm.horizontalOnly?w:0,q=w===o.bm.vertical?w:0,{leftJustifiedTextSymbolIndex:V,centerJustifiedTextSymbolIndex:Z,rightJustifiedTextSymbolIndex:te,verticalPlacedTextSymbolIndex:le}=I,pe=f.text.placedSymbolArray;V>=0&&(pe.get(V).placedOrientation=R),Z>=0&&(pe.get(Z).placedOrientation=R),te>=0&&(pe.get(te).placedOrientation=R),le>=0&&(pe.get(le).placedOrientation=q)}commit(f){this.commitTime=f,this.zoomAtLastRecencyCheck=this.transform.zoom;const w=this.prevPlacement;let I=!1;this.prevZoomAdjustment=w?w.zoomAdjustment(this.transform.zoom):0;const R=w?w.symbolFadeChange(f):1,q=w?w.opacities:{},V=w?w.variableOffsets:{},Z=w?w.placedOrientations:{};for(const te in this.placements){const le=this.placements[te],pe=q[te];pe?(this.opacities[te]=new xN(pe,R,le.text,le.icon,null,le.clipped),I=I||le.text!==pe.text.placed||le.icon!==pe.icon.placed):(this.opacities[te]=new xN(null,R,le.text,le.icon,le.skipFade,le.clipped),I=I||le.text||le.icon)}for(const te in q){const le=q[te];if(!this.opacities[te]){const pe=new xN(le,R,!1,!1);pe.isHidden()||(this.opacities[te]=pe,I=I||le.text.placed||le.icon.placed)}}for(const te in V)this.variableOffsets[te]||!this.opacities[te]||this.opacities[te].isHidden()||(this.variableOffsets[te]=V[te]);for(const te in Z)this.placedOrientations[te]||!this.opacities[te]||this.opacities[te].isHidden()||(this.placedOrientations[te]=Z[te]);I?this.lastPlacementChangeTime=f:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=w?w.lastPlacementChangeTime:f)}updateLayerOpacities(f,w,I,R){R&&(this.lastReplacementSourceUpdateTime=R.updateTime);const q=new Set;for(const V of w){const Z=V.getBucket(f);Z&&V.latestFeatureIndex&&f.fqid===Z.layerIds[0]&&(this.updateBucketOpacities(Z,q,V,V.collisionBoxArray,I,R,V.tileID,f.scope),Z.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Z,V.tileID),Z.elevationType==="road"&&Z.updateRoadElevation(V.tileID.canonical),Z.updateZOffset())}}updateBucketOpacities(f,w,I,R,q,V,Z,te){f.hasTextData()&&f.text.opacityVertexArray.clear(),f.hasIconData()&&f.icon.opacityVertexArray.clear(),f.hasIconCollisionBoxData()&&f.iconCollisionBox.collisionVertexArray.clear(),f.hasTextCollisionBoxData()&&f.textCollisionBox.collisionVertexArray.clear();const le=f.layers[0].layout,pe=f.layers[0].paint,Ae=!!f.layers[0].dynamicFilter(),_e=new xN(null,0,!1,!1,!0),Le=le.get("text-allow-overlap"),Ve=le.get("icon-allow-overlap"),qe=le.get("text-variable-anchor"),Ze=le.get("text-rotation-alignment")==="map",Xe=le.get("text-pitch-alignment")==="map",ht=pe.get("symbol-z-offset"),vt=le.get("symbol-elevation-reference")==="sea",st=!ht.isConstant(),Ut=new xN(null,0,Le&&(Ve||!f.hasIconData()||le.get("icon-optional")),Ve&&(Le||!f.hasTextData()||le.get("text-optional")),!0);!f.collisionArrays&&R&&(f.hasIconCollisionBoxData()||f.hasTextCollisionBoxData())&&f.deserializeCollisionBoxes(R);const Pt=(St,Ct,qt)=>{for(let Zt=0;Zt0||Zt>0,xr=hs>0,or=this.placedOrientations[Wt],Js=or===o.bm.vertical,Ys=or===o.bm.horizontal||or===o.bm.horizontalOnly;!Rs&&!xr||Ms.isHidden()||Vt++;let Wr=!1;if((Rs||xr)&&V)for(const Vr of f.activeReplacements){if(o.bD(Vr,q,o.bE.Symbol,te)||Vr.min.x>ms||ms>Vr.max.x||Vr.min.y>Zs||Zs>Vr.max.y)continue;const Ir=o.bF(ms,Zs,Z.canonical,Vr.footprintTileId.canonical);if(Wr=o.bG(Ir,Vr.footprint),Wr)break}if(Wr&&this.collisionIndex.markSymbolAsClipped(f.bucketInstanceId,Ct.featureIndex),Rs){const Vr=Wr?Z_:Yz(Ms.text);Pt(f.text,qt,Js?Z_:Vr),Pt(f.text,Zt,Ys?Z_:Vr);const Ir=Ms.text.isHidden(),{leftJustifiedTextSymbolIndex:Rr,centerJustifiedTextSymbolIndex:mn,rightJustifiedTextSymbolIndex:Ln,verticalPlacedTextSymbolIndex:An}=Ct,ta=f.text.placedSymbolArray,Tn=Ir||Js?1:0;Rr>=0&&(ta.get(Rr).hidden=Tn),mn>=0&&(ta.get(mn).hidden=Tn),Ln>=0&&(ta.get(Ln).hidden=Tn),An>=0&&(ta.get(An).hidden=Ir||Ys?1:0);const Ia=this.variableOffsets[Wt];Ia&&this.markUsedJustification(f,Ia.anchor,Ct,or);const qn=this.placedOrientations[Wt];qn&&(this.markUsedJustification(f,"left",Ct,qn),this.markUsedOrientation(f,qn,Ct))}if(xr){const Vr=Wr?Z_:Yz(Ms.icon),{placedIconSymbolIndex:Ir,verticalPlacedIconSymbolIndex:Rr}=Ct,mn=f.icon.placedSymbolArray,Ln=Ms.icon.isHidden()?1:0;Ir>=0&&(Pt(f.icon,hs,Js?Z_:Vr),mn.get(Ir).hidden=Ln),Rr>=0&&(Pt(f.icon,Ct.numVerticalIconVertices,Ys?Z_:Vr),mn.get(Rr).hidden=Ln)}if(f.hasIconCollisionBoxData()||f.hasTextCollisionBoxData()){const Vr=f.collisionArrays[St];if(Vr){let Ir=new o.P(0,0),Rr=!0;if(Vr.textBox||Vr.verticalTextBox){if(qe){const Ln=this.variableOffsets[Wt];Ln?(Ir=Wz(Ln.anchor,Ln.width,Ln.height,Ln.textOffset,Ln.textScale),Ze&&Ir._rotate(Xe?this.transform.angle:-this.transform.angle)):Rr=!1}Ae&&(Rr=!Ms.clipped),Vr.textBox&&fT(f.textCollisionBox.collisionVertexArray,Ms.text.placed,!Rr||Js,rs,vt,Ir.x,Ir.y),Vr.verticalTextBox&&fT(f.textCollisionBox.collisionVertexArray,Ms.text.placed,!Rr||Ys,rs,vt,Ir.x,Ir.y)}const mn=Rr&&!!(!Ys&&Vr.verticalIconBox);Vr.iconBox&&fT(f.iconCollisionBox.collisionVertexArray,Ms.icon.placed,mn,rs,vt,Ct.hasIconTextFit?Ir.x:0,Ct.hasIconTextFit?Ir.y:0),Vr.verticalIconBox&&fT(f.iconCollisionBox.collisionVertexArray,Ms.icon.placed,!mn,rs,vt,Ct.hasIconTextFit?Ir.x:0,Ct.hasIconTextFit?Ir.y:0)}}}if(f.fullyClipped=Vt===0,f.sortFeatures(this.transform.angle),this.retainedQueryData[f.bucketInstanceId]&&(this.retainedQueryData[f.bucketInstanceId].featureSortOrder=f.featureSortOrder),f.hasTextData()&&f.text.opacityVertexBuffer&&f.text.opacityVertexBuffer.updateData(f.text.opacityVertexArray),f.hasIconData()&&f.icon.opacityVertexBuffer&&f.icon.opacityVertexBuffer.updateData(f.icon.opacityVertexArray),f.hasIconCollisionBoxData()&&f.iconCollisionBox.collisionVertexBuffer&&f.iconCollisionBox.collisionVertexBuffer.updateData(f.iconCollisionBox.collisionVertexArray),f.hasTextCollisionBoxData()&&f.textCollisionBox.collisionVertexBuffer&&f.textCollisionBox.collisionVertexBuffer.updateData(f.textCollisionBox.collisionVertexArray),f.bucketInstanceId in this.collisionCircleArrays){const St=this.collisionCircleArrays[f.bucketInstanceId];f.placementInvProjMatrix=St.invProjMatrix,f.placementViewportMatrix=St.viewportMatrix,f.collisionCircleArray=St.circles,delete this.collisionCircleArrays[f.bucketInstanceId]}}symbolFadeChange(f){return this.fadeDuration===0?1:(f-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(f){return Math.max(0,(this.transform.zoom-f)/1.5)}hasTransitions(f){return f-this.lastPlacementChangeTimef}isStale(){return this.stale}setStale(){this.stale=!0}}function fT(E,f,w,I,R,q,V){E.emplaceBack(f?1:0,w?1:0,q||0,V||0,I,R?1:0),E.emplaceBack(f?1:0,w?1:0,q||0,V||0,I,R?1:0),E.emplaceBack(f?1:0,w?1:0,q||0,V||0,I,R?1:0),E.emplaceBack(f?1:0,w?1:0,q||0,V||0,I,R?1:0)}const hye=Math.pow(2,25),Y_=Math.pow(2,24),Kz=Math.pow(2,17),pT=Math.pow(2,16),jL=Math.pow(2,9),M0=Math.pow(2,8),mye=Math.pow(2,1);function Yz(E){if(E.opacity===0&&!E.placed)return 0;if(E.opacity===1&&E.placed)return 4294967295;const f=E.placed?1:0,w=Math.floor(127*E.opacity);return w*hye+f*Y_+w*Kz+f*pT+w*jL+f*M0+w*mye+f}const Z_=0;class Zz{constructor(f){this._sortAcrossTiles=f.layout.get("symbol-z-order")!=="viewport-y"&&f.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(f,w,I,R,q,V){const Z=this._bucketParts;for(;this._currentTileIndexte.sortKey-le.sortKey));this._currentPartIndex{const te=o.o.now()-V;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&te>2};for(;this._currentPlacementIndex>=0;){const te=w[f[this._currentPlacementIndex]],le=this.placement.collisionIndex.transform.zoom;if(te.type==="symbol"&&te.visibility!=="none"&&(!te.minzoom||te.minzoom<=le)&&(!te.maxzoom||te.maxzoom>le)){const pe=te,Ae=pe.layout.get("symbol-z-elevate"),_e=pe.layout.get("symbol-sort-key").constantOr(1)!==void 0,Le=pe.layout.get("symbol-z-order"),Ve=Le==="viewport-y"||Le==="auto"&&!(Le!=="viewport-y"&&_e),qe=pe.layout.get("text-allow-overlap")||pe.layout.get("icon-allow-overlap")||pe.layout.get("text-ignore-placement")||pe.layout.get("icon-ignore-placement"),Ze=Ve&&qe,Xe=this._inProgressLayer=this._inProgressLayer||new Zz(pe),ht=o.t(te.source,te.scope);if(Xe.continuePlacement(Ae||Ze?R[ht]:I[ht],this.placement,this._showCollisionBoxes,te,Z,q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(f){return this.placement.commit(f),this.placement}}const vN=512/o.ak/2;class Qz{constructor(f,w,I){this.tileID=f,this.bucketInstanceId=I,this.index=new o.bM(w.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const R=f.canonical.x*o.ak,q=f.canonical.y*o.ak;for(let V=0;VZe-Xe);for(const Ze of qe){const Xe=this.crossTileIDs[Ze];if(this.keys[Ze]===pe&&!I.has(Xe)){I.add(Xe),le.crossTileID=Xe;break}}}}}class Jz{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class e7{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(f){const w=Math.round((f-this.lng)/360);if(w!==0)for(const I in this.indexes){const R=this.indexes[I],q={};for(const V in R){const Z=R[V];Z.tileID=Z.tileID.unwrapTo(Z.tileID.wrap+w),q[Z.tileID.key]=Z}this.indexes[I]=q}this.lng=f}addBucket(f,w,I){if(this.indexes[f.overscaledZ]&&this.indexes[f.overscaledZ][f.key]){if(this.indexes[f.overscaledZ][f.key].bucketInstanceId===w.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(f.overscaledZ,this.indexes[f.overscaledZ][f.key])}for(let q=0;qf.overscaledZ)for(const Z in V){const te=V[Z];te.tileID.isChildOf(f)&&te.findMatches(w.symbolInstances,f,R)}else{const Z=V[f.scaledTo(Number(q)).key];Z&&Z.findMatches(w.symbolInstances,f,R)}}for(let q=0;q{w[I]=!0});for(const I in this.layerIndexes)w[I]||delete this.layerIndexes[I]}}const Xx=770,Qx=771;class En{constructor(f,w,I,R){this.blendFunction=f,this.blendColor=w.toNonPremultipliedRenderColor(null),this.mask=I,this.blendEquation=R}}En.Replace=[1,0,1,0],En.disabled=new En(En.Replace,o.C.transparent,[!1,!1,!1,!1]),En.unblended=new En(En.Replace,o.C.transparent,[!0,!0,!0,!0]),En.alphaBlended=new En([1,Qx,1,Qx],o.C.transparent,[!0,!0,!0,!0]),En.alphaBlendedNonPremultiplied=new En([Xx,Qx,Xx,Qx],o.C.transparent,[!0,!0,!0,!0]),En.multiply=new En([774,0,774,0],o.C.transparent,[!0,!0,!0,!0]),En.multiplyAccumulateAlpha=new En([774,0,1,Qx],o.C.transparent,[!0,!0,!0,!0]),En.additive=new En([1,1,1,1],o.C.transparent,[!0,!0,!0,!0]),En.additiveAlphaWeighted=new En([Xx,1,773,1],o.C.transparent,[!0,!0,!0,!0]),En.additiveAlphaWeightedUnboundedAlpha=new En([Xx,1,1,1],o.C.transparent,[!0,!0,!0,!0]);class Br{constructor(f,w,I){this.func=f,this.mask=w,this.range=I}}Br.ReadOnly=!1,Br.ReadWrite=!0,Br.disabled=new Br(519,Br.ReadOnly,[0,1]);const B1=7680;class kn{constructor(f,w,I,R,q,V){this.test=f,this.ref=w,this.mask=I,this.fail=R,this.depthFail=q,this.pass=V}}kn.disabled=new kn({func:519,mask:0},0,0,B1,B1,B1);const xT=1029,bN=2305;class en{constructor(f,w,I){this.enable=f,this.mode=w,this.frontFace=I}}function _N(E,f){const w=o.bS(E,3);o.bV(E,f),o.b_(E,3,w)}function mr(E,f){const w=o.bP([]);return o.bQ(w,w,-f),o.bR(w,w,-E),w}function NL(E,f){const w=[E[0],E[1],0],I=[f[0],f[1],0];if(o.af(w)>=1e-15){const V=o.ax([],w);o.bN(I,V,o.bk(I,V)),f[0]=I[0],f[1]=I[1]}const R=o.bj([],f,E);if(o.bO(R)<1e-15)return null;const q=Math.atan2(-R[1],R[0]);return mr(Math.atan2(Math.sqrt(E[0]*E[0]+E[1]*E[1]),-E[2]),q)}en.disabled=new en(!1,xT,bN),en.backCCW=new en(!0,xT,bN),en.backCW=new en(!0,xT,2304),en.frontCW=new en(!0,1028,2304),en.frontCCW=new en(!0,1028,bN);class kL{constructor(f,w){this.position=f,this.orientation=w}get position(){return this._position}set position(f){if(f){const w=f instanceof o.ad?f:new o.ad(f[0],f[1],f[2]);this._renderWorldCopies&&(w.x=o.bv(w.x,0,1)),this._position=w}else this._position=null}lookAtPoint(f,w,I){if(this.orientation=null,!this.position)return;const R=this.position,q=I||(this._elevation?this._elevation.getAtPointOrZero(o.ad.fromLngLat(f)):0),V=o.ad.fromLngLat(f,q),Z=[V.x-R.x,V.y-R.y,V.z-R.z];w||(w=[0,0,1]),w[2]=Math.abs(w[2]),this.orientation=NL(Z,w)}setPitchBearing(f,w){this.orientation=mr(o.am(f),o.am(-w))}}class z1{constructor(f,w){this._transform=o.bA([]),this.orientation=w,this.position=f}get mercatorPosition(){const f=this.position;return new o.ad(f[0],f[1],f[2])}get position(){const f=o.bS(this._transform,3);return[f[0],f[1],f[2]]}set position(f){var w;f&&o.b_(this._transform,3,[(w=f)[0],w[1],w[2],1])}get orientation(){return this._orientation}set orientation(f){this._orientation=f||o.bP([]),f&&_N(this._transform,this._orientation)}getPitchBearing(){const f=this.forward(),w=this.right();return{bearing:Math.atan2(-w[1],w[0]),pitch:Math.atan2(Math.sqrt(f[0]*f[0]+f[1]*f[1]),-f[2])}}setPitchBearing(f,w){this._orientation=mr(f,w),_N(this._transform,this._orientation)}forward(){const f=o.bS(this._transform,2);return[-f[0],-f[1],-f[2]]}up(){const f=o.bS(this._transform,1);return[-f[0],-f[1],-f[2]]}right(){const f=o.bS(this._transform,0);return[f[0],f[1],f[2]]}getCameraToWorld(f,w){const I=new Float64Array(16);return o.ba(I,this.getWorldToCamera(f,w)),I}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(f,w,I){const R=this.position;o.bN(R,R,-f);const q=new Float64Array(16);return o.bT(q,[I,I,I]),o.bB(q,q,R),q[10]*=w,q}getWorldToCamera(f,w){const I=new Float64Array(16),R=new Float64Array(4),q=this.position;return o.bU(R,this._orientation),o.bN(q,q,-f),o.bV(I,R),o.bB(I,I,q),I[1]*=-1,I[5]*=-1,I[9]*=-1,I[13]*=-1,I[8]*=w,I[9]*=w,I[10]*=w,I[11]*=w,I}getCameraToClipPerspective(f,w,I,R){const q=new Float64Array(16);return o.bW(q,f,w,I,R),q}getCameraToClipOrthographic(f,w,I,R,q,V){const Z=new Float64Array(16);return o.bX(Z,f,w,I,R,q,V),Z}getDistanceToElevation(f,w=!1){const I=f===0?0:o.bY(f,w?o.bZ(this.position[1]):this.position[1]),R=this.forward();return(I-this.position[2])/R[2]}clone(){return new z1([...this.position],[...this.orientation])}}const uy=(E,f)=>({u_matrix:E,u_ground_shadow_factor:f});class wN{constructor(f=0,w=0,I=0,R=0){if(isNaN(f)||f<0||isNaN(w)||w<0||isNaN(I)||I<0||isNaN(R)||R<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=f,this.bottom=w,this.left=I,this.right=R}interpolate(f,w,I){return w.top!=null&&f.top!=null&&(this.top=o.aj(f.top,w.top,I)),w.bottom!=null&&f.bottom!=null&&(this.bottom=o.aj(f.bottom,w.bottom,I)),w.left!=null&&f.left!=null&&(this.left=o.aj(f.left,w.left,I)),w.right!=null&&f.right!=null&&(this.right=o.aj(f.right,w.right,I)),this}getCenter(f,w){const I=o.aB((this.left+f-this.right)/2,0,f),R=o.aB((this.top+w-this.bottom)/2,0,w);return new o.P(I,R)}equals(f){return this.top===f.top&&this.bottom===f.bottom&&this.left===f.left&&this.right===f.right}clone(){return new wN(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Km=15;class X_{constructor(f,w,I,R,q,V,Z){this.tileSize=512,this._renderWorldCopies=q===void 0||q,this._minZoom=f||0,this._maxZoom=w||22,this._minPitch=I??0,this._maxPitch=R??60,this.setProjection(V),this.setMaxBounds(Z),this.width=0,this.height=0,this._center=new o.aX(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 wN,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new z1,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,this.mercatorMatrix=new Float64Array(16),this.mercatorFogMatrix=new Float32Array(16),this.invProjMatrix=new Float64Array(16),this._expandedFarZProjMatrixBuf=new Float64Array(16),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf,this.starsProjMatrix=new Float32Array(16),this.skyboxMatrix=new Float32Array(16),this._mat4Scratch=new Float64Array(16),this.alignedProjMatrix=new Float64Array(16),this.labelPlaneMatrix=new Float32Array(16),this.glCoordMatrix=new Float32Array(16),this.pixelMatrix=new Float64Array(16),this.pixelMatrixInverse=new Float64Array(16)}clone(){const f=new X_(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return f._elevation=this._elevation,f._centerAltitude=this._centerAltitude,f._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,f.tileSize=this.tileSize,f.mercatorFromTransition=this.mercatorFromTransition,f.width=this.width,f.height=this.height,f.cameraElevationReference=this.cameraElevationReference,f._center=this._center,f._setZoom(this.zoom),f._seaLevelZoom=this._seaLevelZoom,f.angle=this.angle,f._fov=this._fov,f._pitch=this._pitch,f._nearZ=this._nearZ,f._farZ=this._farZ,f._nearClipOffset=this._nearClipOffset,f._averageElevation=this._averageElevation,f._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,f._unmodified=this._unmodified,f._edgeInsets=this._edgeInsets.clone(),f._camera=this._camera.clone(),f._calcMatrices(),f.freezeTileCoverage=this.freezeTileCoverage,f.frustumCorners=this.frustumCorners,f._allowWorldUnderZoom=this._allowWorldUnderZoom,f}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||f===Number.NEGATIVE_INFINITY&&(!w||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const I=this._elevation;w||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&I.exaggeration()&&this._centerAltitudeValidForExaggeration!==I.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*I.exaggeration(),this._centerAltitudeValidForExaggeration=I.exaggeration()):(this._centerAltitude=f||0,this._centerAltitudeValidForExaggeration=I.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const f=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(f)}sampleAverageElevation(){if(!this._elevation)return 0;const f=this._elevation,w=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],I=this.horizonLineFromTop();let R=0,q=0;for(let V=0;V{const Ze=o.cm(_e,Ae,Le,Ve,qe);te.has(Ze)||(q.push(new o.aU(Ae,_e,Le,Ve,qe)),te.add(Ze))};for(let Ae=0;Ae_e.canonical.z)continue;const Le=_e.canonical,Ve=_e.overscaledZ,qe=_e.wrap,Ze=1<0,vt=Le.y+10,Ut=_e.wrap-(ht?0:1),Pt=_e.wrap+(Xe?0:1),Vt=ht?Le.x-1:Ze-1,St=Xe?Le.x+1:0;if(V)I[0]<0?(le(Ve,Pt,Le.z,St,Le.y),I[1]<0&&vt&&(le(Ve,qe,Le.z,Le.x,Le.y+1),le(Ve,Pt,Le.z,St,Le.y+1)),I[1]>0&&st&&(le(Ve,qe,Le.z,Le.x,Le.y-1),le(Ve,Pt,Le.z,St,Le.y-1))):I[0]>0?(le(Ve,Ut,Le.z,Vt,Le.y),I[1]<0&&vt&&(le(Ve,qe,Le.z,Le.x,Le.y+1),le(Ve,Ut,Le.z,Vt,Le.y+1)),I[1]>0&&st&&(le(Ve,qe,Le.z,Le.x,Le.y-1),le(Ve,Ut,Le.z,Vt,Le.y-1))):I[1]<0&&vt?le(Ve,qe,Le.z,Le.x,Le.y+1):st&&le(Ve,qe,Le.z,Le.x,Le.y-1);else{const Ct=_e.visibleQuadrants;1&Ct&&(le(Ve,Ut,Le.z,Vt,Le.y),st&&(le(Ve,qe,Le.z,Le.x,Le.y-1),le(Ve,Ut,Le.z,Vt,Le.y-1))),2&Ct&&(le(Ve,Pt,Le.z,St,Le.y),st&&(le(Ve,qe,Le.z,Le.x,Le.y-1),le(Ve,Pt,Le.z,St,Le.y-1))),4&Ct&&(le(Ve,Ut,Le.z,Vt,Le.y),vt&&(le(Ve,qe,Le.z,Le.x,Le.y+1),le(Ve,Ut,Le.z,Vt,Le.y+1))),8&Ct&&(le(Ve,Pt,Le.z,St,Le.y),vt&&(le(Ve,qe,Le.z,Le.x,Le.y+1),le(Ve,Pt,Le.z,St,Le.y+1)))}}const pe=[];for(const Ae of q)q.some(_e=>Ae.isChildOf(_e))||pe.push(Ae);if(q=pe.filter(Ae=>!f.some(_e=>!!(Ae.overscaledZ{const Xe=Ze.canonical.x+.5-Le[0],ht=Ze.canonical.y+.5-Le[1];return Xe*Xe+ht*ht{const Vt=o.cm(vt,ht,st,Ut,Pt);q.has(Vt)||(R.push(new o.aU(ht,vt,st,Ut,Pt)),q.add(Vt))},Z=f.reduce((ht,vt)=>Math.max(ht,vt.overscaledZ),I),te=1<{const st=Math.floor(ht[0]),Ut=Math.floor(ht[1]),Pt=(ht[0]-st)*o.ak,Vt=(ht[1]-Ut)*o.ak,St=Math.floor(vt[0]),Ct=Math.floor(vt[1]),qt=(vt[0]-St)*o.ak,Zt=(vt[1]-Ct)*o.ak;for(let Wt=-1;Wt<=1;Wt++){const hs=st+Wt;if(!(hs<0||hs>=te)){pe.x=Pt-Wt*o.ak,Ae.x=qt-(hs-St)*o.ak;for(let ms=-1;ms<=1;ms++){const Zs=Ut+ms;pe.y=Vt-ms*o.ak,Ae.y=Zt-(Zs-Ct)*o.ak,o.cM(pe,Ae,le)&&V(Z,0,I,hs,Zs)}}}},Le=w.points,Ve=Le[o.cb],qe=Le[o.cc],Ze=this._projectToGround(Ve,Le[o.cd]),Xe=this._projectToGround(qe,Le[o.ce]);return _e(Ve,Ze),_e(qe,Xe),R}_projectToGround(f,w){return o.cf(o.cg(),f,w,f[2]/(f[2]-w[2]))}_projectToZ(f,w,I){const R=f[2]-w[2];return Math.abs(R)<1e-6?o.ch(f):o.cf(o.cg(),f,w,(f[2]-I)/R)}extendTileCoverForTunnels(f,w,I,R){if(I<18)return[];const q=w.points,V=q[o.ci],Z=q[o.cj],te=q[o.ck],le=q[o.cl];if(te[2]>=0&&le[2]>=0||V[2]<=0||Z[2]<=0)return[];const pe=te[2]<0?this._projectToZ(V,te,0):te,Ae=le[2]<0?this._projectToZ(Z,le,0):le,_e=-R,Le=te[2]<_e?this._projectToZ(V,te,_e):te,Ve=le[2]<_e?this._projectToZ(Z,le,_e):le,qe=this._findExtensionTilesInQuad(f,I,[Ve,Le,Ae,pe],[.5*(pe[0]+Ae[0]),.5*(pe[1]+Ae[1])]);return qe.length>3&&(qe.length=3),qe}_findExtensionTilesInQuad(f,w,I,R){const q=[],V=new Set;for(const St of f)V.add(St.key);const Z=f.reduce((St,Ct)=>Math.max(St,Ct.overscaledZ),w),te=1<{const qt=St.canonical.x+.5-Pt,Zt=St.canonical.y+.5-Vt,Wt=Ct.canonical.x+.5-Pt,hs=Ct.canonical.y+.5-Vt;return qt*qt+Zt*Zt-(Wt*Wt+hs*hs)||St.canonical.x-Ct.canonical.x||St.canonical.y-Ct.canonical.y}),q}coveringTiles(f){let w=this.coveringZoomLevel(f);const I=w,R=this.elevation&&this.elevation.exaggeration(),q=R&&!f.isTerrainDEM,V=this.projection.name==="mercator";if(f.minzoom!==void 0&&wf.maxzoom&&(w=f.maxzoom);const Z=this.locationCoordinate(this.center),te=this.center.lat,le=1<{const Ms=new o.ad(rs.x+25e-6,rs.y,rs.z),Rs=new o.ad(rs.x,rs.y+25e-6,rs.z),xr=rs.toLngLat(),or=Ms.toLngLat(),Js=Rs.toLngLat(),Ys=this.locationCoordinate(xr),Wr=this.locationCoordinate(or),Vr=this.locationCoordinate(Js),Ir=Math.hypot(Wr.x-Ys.x,Wr.y-Ys.y),Rr=Math.hypot(Vr.x-Ys.x,Vr.y-Ys.y);return Math.sqrt(Ir*Rr)*Vt/25e-6},Ct=rs=>{const Ps=Ut,Ms=Pt;return{aabb:o.cr(this,le,0,0,0,rs,Ms,Ps,this.projection),zoom:0,x:0,y:0,minZ:Ms,maxZ:Ps,wrap:rs,fullyVisible:!1}},qt=[];let Zt=[];const Wt=w,hs=f.reparseOverscaled?I:w,ms=(Ze-this._centerAltitude)*qe,Zs=rs=>{if(!this._elevation||!rs.tileID||!V)return;const Ps=this._elevation.getMinMaxForTile(rs.tileID),Ms=rs.aabb;Ps?(Ms.min[2]=Ps.min,Ms.max[2]=Ps.max,Ms.center[2]=(Ms.min[2]+Ms.max[2])/2):(rs.shouldSplit=Ns(rs),rs.shouldSplit||(Ms.min[2]=Ms.max[2]=Ms.center[2]=this._centerAltitude))},ts=(rs,Ps)=>{if(.707*Ps{if(rs.zoom=.9)return!0}else if(q&&(Rs=rs.aabb.distanceZ(Xe)*qe),this.projection.isReprojectedInTileSpace&&I<=5){const Rr=Math.pow(2,rs.zoom),mn=St(new o.ad((rs.x+.5)/Rr,(rs.y+.5)/Rr));xr=mn>.85?1:mn}if(!V&&!Ae){const Rr=Math.sqrt(Ps*Ps+Ms*Ms+Rs*Rs);let mn=(1<0;){const rs=qt.pop(),Ps=rs.x,Ms=rs.y;let Rs=rs.fullyVisible;const xr=()=>this.projection.name==="globe"&&(rs.y===0||rs.y===(1<or)continue;let Js=0;if(!Rs){let Ir=ht?rs.aabb.intersectsPrecise(Le):rs.aabb.intersectsPreciseFlat(Le);if(Ir===0&&xr()){const Rr=new o.cp(rs.zoom,Ps,Ms);Ir=o.cq(this,le,Rr,!0).intersectsPrecise(Le)}if(Ir===0)continue;if(f.calculateQuadrantVisibility)if(Le.containsPoint(rs.aabb.center))Js=15;else for(let Rr=0;Rr<4;Rr++)rs.aabb.quadrant(Rr).intersects(Le)!==0&&(Js|=1<>1),Wr={aabb:V?rs.aabb.quadrant(or):o.cr(this,le,rs.zoom+1,Js,Ys,rs.wrap,rs.minZ,rs.maxZ,this.projection),zoom:rs.zoom+1,x:Js,y:Ys,wrap:rs.wrap,fullyVisible:Rs,tileID:void 0,shouldSplit:void 0,minZ:rs.minZ,maxZ:rs.maxZ};q&&!Ae&&(Wr.tileID=new o.aU(rs.zoom+1===Wt?hs:rs.zoom+1,rs.wrap,rs.zoom+1,Js,Ys),Zs(Wr)),qt.push(Wr)}}if(this.fogCullDistSq){const rs=this.fogCullDistSq,Ps=this.horizonLineFromTop();Zt=Zt.filter(Ms=>{const Rs=[0,0,0,1],xr=[o.ak,o.ak,0,1],or=this.calculateFogTileMatrix(Ms.tileID.toUnwrapped());o.aD(Rs,Rs,or),o.aD(xr,xr,or);const Js=o.cs([],Rs,xr),Ys=o.ct([],Rs,xr),Wr=o.cO(Js,Ys);if(Wr===0)return!0;let Vr=!1;const Ir=this._elevation;if(Ir&&Wr>rs&&Ps!==0){const Rr=this.calculateProjMatrix(Ms.tileID.toUnwrapped());let mn;f.isTerrainDEM||(mn=Ir.getMinMaxForTile(Ms.tileID)),mn||(mn={min:Pt,max:Ut});const Ln=o.cu(this.rotation),An=[Ln[0]*o.ak,Ln[1]*o.ak,mn.max];o.ae(An,An,Rr),Vr=(1-An[1])*this.height*.5rs.distanceSq-Ps.distanceSq).map(rs=>rs.tileID)}resize(f,w){this.width=f,this.height=w,this.pixelsToGLUnits=[2/f,-2/w],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(f){return Math.pow(2,f)}scaleZoom(f){return Math.log2(f)}project(f){const w=o.aB(f.lat,-o.cv,o.cv),I=this.projection.project(f.lng,w);return new o.P(I.x*this.worldSize,I.y*this.worldSize)}unproject(f){return this.projection.unproject(f.x/this.worldSize,f.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bY(1,this.center.lat)/this.worldSize}setLocationAtPoint(f,w){let I,R;const q=this.centerPoint;if(this.projection.name==="globe"){const Z=this.worldSize;I=(w.x-q.x)/Z,R=(w.y-q.y)/Z}else{const Z=this.pointCoordinate(w),te=this.pointCoordinate(q);I=Z.x-te.x,R=Z.y-te.y}const V=this.locationCoordinate(f);this.setLocation(new o.ad(V.x-I,V.y-R))}setLocation(f){this.center=this.coordinateLocation(f),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(f,w){return this.projection.locationPoint(this,f,w)}locationPoint3D(f,w){return this.projection.locationPoint(this,f,w,!0)}pointLocation(f){return this.coordinateLocation(this.pointCoordinate(f))}pointLocation3D(f,w){return this.coordinateLocation(this.pointCoordinate3D(f,w))}locationCoordinate(f,w){const I=w?o.bY(w,f.lat):void 0,R=this.projection.project(f.lng,f.lat);return new o.ad(R.x,R.y,I)}coordinateLocation(f){return this.projection.unproject(f.x,f.y)}pointRayIntersection(f,w){const I=w??this._centerAltitude,R=[f.x,f.y,0,1],q=[f.x,f.y,1,1];o.aD(R,R,this.pixelMatrixInverse),o.aD(q,q,this.pixelMatrixInverse);const V=q[3];o.cw(R,R,1/R[3]),o.cw(q,q,1/V);const Z=R[2],te=q[2];return{p0:R,p1:q,t:Z===te?0:(I-Z)/(te-Z)}}screenPointToMercatorRay(f){const w=[f.x,f.y,0,1],I=[f.x,f.y,1,1];return o.aD(w,w,this.pixelMatrixInverse),o.aD(I,I,this.pixelMatrixInverse),o.cw(w,w,1/w[3]),o.cw(I,I,1/I[3]),w[2]=o.bY(w[2],this._center.lat)*this.worldSize,I[2]=o.bY(I[2],this._center.lat)*this.worldSize,o.cw(w,w,1/this.worldSize),o.cw(I,I,1/this.worldSize),new o.ay([w[0],w[1],w[2]],o.ax([],o.aw([],I,w)))}rayIntersectionCoordinate(f){const{p0:w,p1:I,t:R}=f,q=o.bY(w[2],this._center.lat),V=o.bY(I[2],this._center.lat);return new o.ad(o.aj(w[0],I[0],R)/this.worldSize,o.aj(w[1],I[1],R)/this.worldSize,o.aj(q,V,R))}pointCoordinate(f,w=this._centerAltitude){return this.projection.pointCoordinate(this,f.x,f.y,w)}pointCoordinate3D(f,w){if(!this.elevation)return this.pointCoordinate(f,w);let I=this.projection.pointCoordinate3D(this,f.x,f.y);if(I)return new o.ad(I[0],I[1],I[2]);let R=0,q=this.horizonLineFromTop();if(f.y>q)return this.pointCoordinate(f,w);const V=.02*q,Z=f.clone();for(let te=0;te<10&&q-R>V;te++){Z.y=o.aj(R,q,.66);const le=this.projection.pointCoordinate3D(this,Z.x,Z.y);le?(q=Z.y,I=le):R=Z.y}return I?new o.ad(I[0],I[1],I[2]):this.pointCoordinate(f)}isPointAboveHorizon(f){return this.projection.isPointAboveHorizon(this,f)}isPointOnSurface(f){if(f.y<0||f.y>this.height||f.x<0||f.x>this.width)return!1;if(this.elevation||this.zoom>=o.cx)return!this.isPointAboveHorizon(f);const w=this.pointCoordinate(f);return w.y>=0&&w.y<=1}_coordinatePoint(f,w){const I=w&&this.elevation?this.elevation.getAtPointOrZero(f,this._centerAltitude):this._centerAltitude,R=[f.x*this.worldSize,f.y*this.worldSize,I+f.toAltitude(),1];return o.aD(R,R,this.pixelMatrix),R[3]>0?new o.P(R[0]/R[3],R[1]/R[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:f,left:w}=this._edgeInsets,I=this.height-this._edgeInsets.bottom,R=this.width-this._edgeInsets.right,q=this.pointLocation3D(new o.P(w,f)),V=this.pointLocation3D(new o.P(R,f)),Z=this.pointLocation3D(new o.P(R,I)),te=this.pointLocation3D(new o.P(w,I));let le=Math.min(q.lng,V.lng,Z.lng,te.lng),pe=Math.max(q.lng,V.lng,Z.lng,te.lng),Ae=Math.min(q.lat,V.lat,Z.lat,te.lat),_e=Math.max(q.lat,V.lat,Z.lat,te.lat);const Le=Math.pow(2,-this.zoom)/16*270,Ve=this.projection.name==="globe"?1:4,qe=(Ze,Xe,ht,vt,st)=>{const Ut=(Ze+ht)/2,Pt=(Xe+vt)/2,Vt=new o.P(Ut,Pt),{lng:St,lat:Ct}=this.pointLocation3D(Vt),qt=Math.max(0,le-St,Ae-Ct,St-pe,Ct-_e);le=Math.min(le,St),pe=Math.max(pe,St),Ae=Math.min(Ae,Ct),_e=Math.max(_e,Ct),(stLe)&&(qe(Ze,Xe,Ut,Pt,st+1),qe(Ut,Pt,ht,vt,st+1))};if(qe(w,f,R,f,1),qe(R,f,R,I,1),qe(R,I,w,I,1),qe(w,I,w,f,1),this.projection.name==="globe"){const[Ze,Xe]=o.cy(this);Ze?(_e=90,pe=180,le=-180):Xe&&(Ae=-90,pe=180,le=-180)}return new o.aI(new o.aX(le,Ae),new o.aX(pe,_e))}_getBoundsRectangular(f,w){const{top:I,left:R}=this._edgeInsets,q=this.height-this._edgeInsets.bottom,V=this.width-this._edgeInsets.right,Z=new o.P(R,I),te=new o.P(V,I),le=new o.P(V,q),pe=new o.P(R,q);let Ae=this.pointCoordinate(Z,f),_e=this.pointCoordinate(te,f);const Le=this.pointCoordinate(le,w),Ve=this.pointCoordinate(pe,w),qe=(Ze,Xe)=>(Xe.y-Ze.y)/(Xe.x-Ze.x);return Ae.y>1&&_e.y>=0?Ae=new o.ad((1-Ve.y)/qe(Ve,Ae)+Ve.x,1):Ae.y<0&&_e.y<=1&&(Ae=new o.ad(-Ve.y/qe(Ve,Ae)+Ve.x,0)),_e.y>1&&Ae.y>=0?_e=new o.ad((1-Le.y)/qe(Le,_e)+Le.x,1):_e.y<0&&Ae.y<=1&&(_e=new o.ad(-Le.y/qe(Le,_e)+Le.x,0)),new o.aI().extend(this.coordinateLocation(Ae)).extend(this.coordinateLocation(_e)).extend(this.coordinateLocation(Ve)).extend(this.coordinateLocation(Le))}_getBoundsRectangularTerrain(){const f=this.elevation;if(!f.visibleDemTiles.length||f.isUsingMockSource())return this._getBoundsRectangular(0,0);const w=f.visibleDemTiles.reduce((I,R)=>{if(R.dem){const q=R.dem.tree;I.min=Math.min(I.min,q.minimums[0]),I.max=Math.max(I.max,q.maximums[0])}return I},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(w.min*f.exaggeration(),w.max*f.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(f=!0){const w=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,I=this.height/2-w*(1-this._horizonShift);return f?Math.max(0,I):I}getMaxBounds(){return this.maxBounds}setMaxBounds(f){this.maxBounds=f,this.minLat=-o.cv,this.maxLat=o.cv,this.minLng=-180,this.maxLng=180,f&&(this.minLat=f.getSouth(),this.maxLat=f.getNorth(),this.minLng=f.getWest(),this.maxLng=f.getEast(),this.maxLngAe&&(Z=Ae-le),Ae-peLe&&(V=Le-te),Le-_e{for(let hs=0;hs<16;hs++)Ct[hs]=o.aj(qt[hs],Zt[hs],Wt)})(Z,Z,te,o.cP(this.pitch>=Km?1:this.pitch/Km))}else Z=te;const le=o.cB([],te,V),pe=o.cB([],Z,V);if(this.projection.isReprojectedInTileSpace){const Ut=this.locationCoordinate(this.center);o.bA(this._mat4Scratch);const Pt=this._mat4Scratch;o.bB(Pt,Pt,[Ut.x*this.worldSize,Ut.y*this.worldSize,0]),o.aC(Pt,Pt,o.cC(this)),o.bB(Pt,Pt,[-Ut.x*this.worldSize,-Ut.y*this.worldSize,0]),o.aC(pe,pe,Pt),o.aC(le,le,Pt),this.inverseAdjustmentMatrix=o.cD(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(o.cE(this.mercatorMatrix,pe,[this.worldSize,this.worldSize,this.worldSize/q,1]),this.projMatrix=pe,o.ba(this.invProjMatrix,this.projMatrix),w){const Ut=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Ut[8]=2*-f.x/this.width,Ut[9]=2*f.y/this.height,o.cB(this._expandedFarZProjMatrixBuf,Ut,V),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;o.ba(this._mat4Scratch,Z),this.frustumCorners=o.cF.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cn.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!w),o.bT(this.skyboxMatrix,[1,-1,1]),o.cG(this.skyboxMatrix,this.skyboxMatrix,this._pitch),o.bc(this.skyboxMatrix,this.skyboxMatrix,this.angle),o.bW(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const Ae=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;o.cH(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-f.x/this.width,this._mat4Scratch[9]=2*(f.y+Ae)/this.height,o.aC(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const _e=this.point,Le=_e.x,Ve=_e.y,qe=this.width%2/2,Ze=this.height%2/2,Xe=Math.cos(this.angle),ht=Math.sin(this.angle),vt=Le-Math.round(Le)+Xe*qe+ht*Ze,st=Ve-Math.round(Ve)+Xe*Ze+ht*qe;if(o.cH(this.alignedProjMatrix,pe),o.bB(this.alignedProjMatrix,this.alignedProjMatrix,[vt>.5?vt-1:vt,st>.5?st-1:st,0]),o.bT(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),o.bB(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),o.bT(this.glCoordMatrix,[1,-1,1]),o.bB(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),o.cE(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),o.aC(this.pixelMatrix,this.labelPlaneMatrix,le),this._calcFogMatrices(),this._distanceTileDataCache={},!o.ba(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if(this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cI(this);const Ut=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ae(Ut,Ut,V),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const f=this.cameraWorldSizeForFog,w=this.cameraPixelsPerMeter,I=this._camera.position,R=1/this.height/this._pixelsPerMercatorPixel,q=[f,f,w];o.bN(q,q,R),o.bN(I,I,-1),o.cJ(I,I,q),o.cK(this.mercatorFogMatrix,I),o.cE(this.mercatorFogMatrix,this.mercatorFogMatrix,q),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(f,w,R)}_computeCameraPosition(f){const w=(f=f||this.pixelsPerMeter)/this.pixelsPerMeter,I=this._camera.forward(),R=this.point,q=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*w-f/this.worldSize*this._centerAltitude;return[R.x/this.worldSize-I[0]*q,R.y/this.worldSize-I[1]*q,f/this.worldSize*this._centerAltitude-I[2]*q]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(f){const w=this._maxCameraBoundsDistance()*Math.cos(this._pitch),I=this._camera.position[2],R=f[2];let q=1;this.projection.wrap&&(this.center=this.center.wrap()),R>0&&(q=Math.min((w-I)/R,1)),this._camera.position=o.bi([],this._camera.position,f,q),this._updateStateFromCamera()}_updateStateFromCamera(){const f=this._camera.position,w=this._camera.forward(),{pitch:I,bearing:R}=this._camera.getPitchBearing(),q=o.bY(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,V=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.am(this._maxPitch)),Z=Math.max((f[2]-q)/Math.cos(I),V),te=this._zoomFromMercatorZ(Z);o.bi(f,f,w,Z),this._pitch=o.aB(I,o.am(this.minPitch),o.am(this.maxPitch)),this.angle=o.bv(R,-Math.PI,Math.PI),this._setZoom(o.aB(te,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ad(f[0],f[1],f[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(f){return Math.pow(2,f)*this.tileSize}_mercatorZfromZoom(f){return this.cameraToCenterDistance/this._worldSizeFromZoom(f)}_minimumHeightOverTerrain(){const f=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(f)}_zoomFromMercatorZ(f){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,f)*this.tileSize))}zoomFromMercatorZAdjusted(f){let w=0,I=o.cx,R=0,q=1/0;for(;I-w>1e-6&&I>w;){const V=w+.5*(I-w),Z=this.tileSize*Math.pow(2,V),te=this.getCameraToCenterDistance(this.projection,V,Z),le=this.scaleZoom(te/(Math.max(0,f)*this.tileSize)),pe=Math.abs(V-le);pele||_e.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cL(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(f,w){const I=o.af(o.aw([],this._camera.position,f)),R=this._zoomFromMercatorZ(I)+w;return I-this._mercatorZfromZoom(R)}getCameraPoint(){if(this.projection.name==="globe"){const f=function([w,I,R],q){const V=[w,I,R,1];o.aD(V,V,q);const Z=V[3]=Math.max(V[3],1e-6);return V[0]/=Z,V[1]/=Z,V[2]/=Z,V}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(f[0],f[1])}{const f=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,f))}}getCameraToCenterDistance(f,w=this.zoom,I=this.worldSize){const R=o.cA(f,w,this.width,this.height,1024),q=f.pixelSpaceConversion(this.center.lat,I,R);let V=.5/Math.tan(.5*this._fov)*this.height*q;return this.isOrthographic&&(V=o.aj(1,V,o.cP(this.pitch>=Km?1:this.pitch/Km))),V}getWorldToCameraMatrix(){const f=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aC(f,f,this.globeMatrix),f}getFrustum(f){return o.cn.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,f,this.projection.zAxisUnit==="meters")}}const Ym=(E,f)=>{if(f>0&&E.terrain&&o.w("Cutoff is currently disabled on terrain"),f<=0||E.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const w=E.transform,I=w.pitch,R=w.isLODDisabled(!1)?60:30;if(I0,uniformValues:{u_cutoff_params:[w._nearZ,w._farZ,(pe-w._nearZ)/q,(pe-_e-w._nearZ)/q]}}},s7=[];function r7(E){return s7[E]=s7[E]||new Float64Array(16)}class gT{constructor(f,w){this.aabb=f,this.lastCascade=w}}class fye{add(f,w){const I=this.receivers[f.key];I!==void 0?(I.aabb.min[0]=Math.min(I.aabb.min[0],w.min[0]),I.aabb.min[1]=Math.min(I.aabb.min[1],w.min[1]),I.aabb.min[2]=Math.min(I.aabb.min[2],w.min[2]),I.aabb.max[0]=Math.max(I.aabb.max[0],w.max[0]),I.aabb.max[1]=Math.max(I.aabb.max[1],w.max[1]),I.aabb.max[2]=Math.max(I.aabb.max[2],w.max[2])):this.receivers[f.key]=new gT(w,null)}clear(){this.receivers={}}get(f){return this.receivers[f.key]}computeRequiredCascades(f,w,I){const R=o.cY.fromPoints(f.points);let q=0;for(const V in this.receivers){const Z=this.receivers[V];if(!Z||!R.intersectsAabb(Z.aabb))continue;Z.aabb.min=R.closestPoint(Z.aabb.min),Z.aabb.max=R.closestPoint(Z.aabb.max);const te=Z.aabb.getCorners();for(let le=0;le1||_e[1]<-1||_e[1]>1){pe=!1;break}}if(Z.lastCascade=le,q=Math.max(q,le),pe)break}}return q+1}}class n7{constructor(f){this.painter=f,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new fye,this._depthMode=new Br(f.context.gl.LEQUAL,Br.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._devtoolsFolder=null,this.useNormalOffset=!1,this._shadowParameters={cascadeCount:2,normalOffset:3,shadowMapResolution:2048}}destroy(){for(const f of this._cascades)f.texture.destroy(),f.framebuffer.destroy();this._cascades=[]}updateShadowParameters(f,w){const I=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!w||!w.properties)return;const R=w.properties.get("shadow-intensity"),q=w.properties.get("shadow-draw-before-layer");if(!w.shadowsEnabled()||R<=0)return;let V=-1,Z=0;for(const Xe of I.style.order){const ht=I.style._mergedLayers[Xe];ht.hasShadowPass()&&!ht.isHidden(f.zoom)&&(V=Z),!q||q!==Xe&&q!==ht.slot||(this._drawShadowAfterLayer=Z>0?Z-1:0),Z+=1}if(this._enabled=V>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=V);const te=I.context,le=this._shadowParameters.shadowMapResolution,pe=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let Xe=0;Xevt.dem).forEach(vt=>{const st=vt.dem.tree;ht[0]=Math.min(ht[0],st.minimums[0]),ht[1]=Math.max(ht[1],st.maximums[0])}),ht[0]!==1e4&&(Ae=(ht[1]-ht[0])*Xe.exaggeration())}const _e=1.5*f.cameraToCenterDistance,Le=3*_e,Ve=new Float64Array(16);for(let Xe=0;Xe=0)return{};const q=function(te,le,pe){const Ae=pe/(1<0&&(o.cX(q[1],q[1],[R[0]*V,0,0]),o.cX(q[2],q[2],[R[0]*V,0,0])),R[1]<0?(o.cX(q[0],q[0],[0,R[1]*V,0]),o.cX(q[1],q[1],[0,R[1]*V,0])):R[1]>0&&(o.cX(q[2],q[2],[0,R[1]*V,0]),o.cX(q[3],q[3],[0,R[1]*V,0]));const Z={};return Z.vertices=q,Z.planes=[jN(q[1],q[0],q[4]),jN(q[2],q[1],q[5]),jN(q[3],q[2],q[6]),jN(q[0],q[3],q[7])],Z}addShadowReceiver(f,w,I){this._receivers.add(f,o.cY.fromTileIdAndHeight(f,w,I))}getMaxCascadeForTile(f){const w=this._receivers.get(f);return w&&w.lastCascade?w.lastCascade:0}}function jN(E,f,w){const I=o.aw([],w,f),R=o.aw([],E,f),q=o.bj([],I,R),V=o.af(q);return V===0?[0,0,1,0]:(o.bN(q,q,1/V),[q[0],q[1],q[2],-o.bk(q,f)])}function yT(E){const f=E.properties.get("direction"),w=o.cT(f.x,f.y,f.z);w[2]=o.aB(w[2],0,75);const I=o.cV([w[0],w[1],w[2]]);return o.cU(I.x,I.y,I.z)}function $1(E,f,w){const I=f.properties.get("color-use-theme")==="none",R=f.properties.get("color"),q=f.properties.get("intensity"),V=f.properties.get("direction"),Z=[V.x,V.y,V.z],te=w.properties.get("color-use-theme")==="none",le=w.properties.get("color"),pe=w.properties.get("intensity"),Ae=Math.max(o.bk([0,0,1],Z),0),_e=[0,0,0];o.bN(_e,le.toPremultipliedRenderColor(te?null:E.getLut(f.scope)).toArray01Linear().slice(0,3),pe);const Le=[0,0,0];return o.bN(Le,R.toPremultipliedRenderColor(I?null:E.getLut(w.scope)).toArray01Linear().slice(0,3),Ae*q),o.c_([_e[0]>0?_e[0]/(_e[0]+Le[0]):0,_e[1]>0?_e[1]/(_e[1]+Le[1]):0,_e[2]>0?_e[2]/(_e[2]+Le[2]):0])}function pye(E,f,w,I,R,q){const V=E.zoom,Z=E.scale,te=E.worldSize,le=1/te,pe=E.aspect,Ae=Math.sqrt(1+pe*pe)*Math.tan(.5*E.fovX),_e=Ae*Ae,Le=I-w,Ve=I+w;let qe,Ze;_e>Le/Ve?(qe=I,Ze=I*Ae):(qe=.5*Ve*(1+_e),Ze=.5*Math.sqrt(Le*Le+2*(I*I+w*w)*_e+Ve*Ve*_e*_e));const Xe=E.projection.pixelsPerMeter(E.center.lat,te),ht=E._camera.getCameraToWorldMercator(),vt=[0,0,-qe*le];o.ae(vt,vt,ht);let st=Ze*le;const Ut=function(Rs){return Rs[0]/=Z,Rs[1]/=Z,Rs[2]=o.bY(Rs[2],E._center.lat),Rs},Pt=E._edgeInsets;if(!(Pt.left===0&&Pt.top===0&&Pt.right===0&&Pt.bottom===0||Pt.left===Pt.right&&Pt.top===Pt.bottom)){const Rs=E._camera.getWorldToCamera(E.worldSize,E.projection.zAxisUnit==="meters"?Xe:1),xr=E._camera.getCameraToClipPerspective(E._fov,E.width/E.height,w,I);xr[8]=2*-E.centerOffset.x/E.width,xr[9]=2*E.centerOffset.y/E.height;const or=new Float64Array(16);o.cB(or,xr,Rs);const Js=new Float64Array(16);o.ba(Js,or);const Ys=o.cn.fromInvProjectionMatrix(Js,te,V,!0);for(const Wr of Ys.points){const Vr=Ut(Wr);st=Math.max(st,o.bO(o.cZ([],vt,Vr)))}}st*=R/(R-1);const Vt=Math.acos(f[2]),St=Math.atan2(-f[0],-f[1]),Ct=new z1;Ct.position=vt,Ct.setPitchBearing(Vt,St);const qt=Ct.getWorldToCamera(te,Xe),Zt=st*te,Wt=Math.min(E._mercatorZfromZoom(17)*te*-2,-2*Zt),hs=Ct.getCameraToClipOrthographic(-Zt,Zt,-Zt,Zt,Wt,(Zt+q*Xe)/f[2]),ms=new Float64Array(16);o.aC(ms,hs,qt);const Zs=o.cU(Math.floor(1e6*vt[0])/1e6*te,Math.floor(1e6*vt[1])/1e6*te,0),ts=.5*R,Ns=[0,0,0];o.ae(Ns,Zs,ms),o.bN(Ns,Ns,ts);const rs=[Math.floor(Ns[0]),Math.floor(Ns[1]),Math.floor(Ns[2])],Ps=[0,0,0];o.aw(Ps,Ns,rs),o.bN(Ps,Ps,-1/ts);const Ms=new Float64Array(16);return o.bA(Ms),o.bB(Ms,Ms,Ps),o.aC(ms,Ms,ms),[ms,Zt]}class xye extends o.E{constructor(f){super(),this.requestManager=f,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(f,w){return o.c$(this.requestManager.transformRequest(w,o.R.Model).url).then(I=>{const R=o.d0(I),q=new o.d1(f,w,void 0,void 0,R);return q.computeBoundsAndApplyParent(),q}).catch(I=>{if(I&&I.status===404)return null;this.fire(new o.y(new Error(`Could not load model ${f} from ${w}: ${I.message}`)))})}load(f,w,I={forceReload:!1}){this.models[w]||(this.models[w]={});const R=Object.keys(f),q=[],V=[];for(const Z of R){const te=f[Z];this.hasURLBeenRequested(te)&&!I.forceReload||(this.modelByURL[te]={modelId:Z,scope:w},q.push(this.loadModel(Z,te)),V.push(Z)),this.models[w][Z]||(this.models[w][Z]={model:null,numReferences:1})}this.numModelsLoading[w]=(this.numModelsLoading[w]||0)+V.length,Promise.allSettled(q).then(Z=>{for(let te=0;te{this.fire(new o.y(new Error(`Could not load models: ${Z.message}`)))})}isLoaded(){for(const f in this.numModelsLoading)if(this.numModelsLoading[f]>0)return!1;return!0}hasModel(f,w,I={exactIdMatch:!1}){return!!(I.exactIdMatch?this.getModel(f,w):this.getModelByURL(this.modelUris[w][f]))}getModel(f,w){return this.models[w]||(this.models[w]={}),this.models[w][f]?this.models[w][f].model:void 0}getModelByURL(f){if(!f)return null;const w=this.modelByURL[f];return w?this.models[w.scope][w.modelId].model:null}hasModelBeenAdded(f,w){return this.models[w]&&this.models[w][f]!==void 0}getModelURIs(f){return this.modelUris[f]||{}}addModel(f,w,I){this.models[I]||(this.models[I]={}),this.modelUris[I]||(this.modelUris[I]={});const R=this.requestManager.normalizeModelURL(w);if((this.hasModel(f,I,{exactIdMatch:!0})||this.hasModelBeenAdded(f,I))&&this.modelUris[I][f]===R)this.models[I][f].numReferences++;else if(this.hasURLBeenRequested(R)){const{scope:q,modelId:V}=this.modelByURL[R];this.models[q][V].numReferences++}else this.modelUris[I][f]=R,this.load({[f]:this.modelUris[I][f]},I)}addModelURLs(f,w){this.models[w]||(this.models[w]={}),this.modelUris[w]||(this.modelUris[w]={});const I=this.modelUris[w];for(const R in f)I[R]=this.requestManager.normalizeModelURL(f[R])}reloadModels(f){this.load(this.modelUris[f],f,{forceReload:!0})}addModelsFromBucket(f,w){this.models[w]||(this.models[w]={}),this.modelUris[w]||(this.modelUris[w]={});const I={};for(const R of f)this.hasModel(R,w,{exactIdMatch:!0})||this.hasURLBeenRequested(R)?this.models[w][R].numReferences++:this.modelUris[w][R]&&!this.hasURLBeenRequested(R)?I[R]=this.modelUris[w][R]:!this.hasURLBeenRequested(R)&&Dl(R,!1)&&(this.modelUris[w][R]=this.requestManager.normalizeModelURL(R),I[R]=this.modelUris[w][R]);this.load(I,w)}hasURLBeenRequested(f){return this.modelByURL[f]!==void 0}removeModel(f,w,I=!1,R=!1){if(this.models[w]&&this.models[w][f]&&(this.models[w][f].numReferences--,this.models[w][f].numReferences===0||R)){const q=this.modelUris[w][f];I||delete this.modelUris[w][f],delete this.modelByURL[q];const V=this.models[w][f].model;if(!V)return;delete this.models[w][f],V.destroy()}}destroy(){for(const f of Object.keys(this.models))for(const w of Object.keys(this.models[f])){const I=this.models[f][w].model;delete this.models[f][w],I&&I.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(f){return this.models[f]||(this.models[f]={}),Object.keys(this.models[f])}upload(f,w){this.models[w]||(this.models[w]={});for(const I in this.models[w])this.models[w][I].model&&this.models[w][I].model.upload(f.context)}}const gye=["RENDER_SHADOWS","NORMAL_OFFSET"],a7=new Set(["symbol","circle"]),SL=class Jje{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(f,w,I){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const R=I.stylesheet,q=!!I.fog,V=!!(I.getTerrain()||R&&R.terrain),Z=!(!I.projection||I.projection.name!=="globe"),te=V||Z,le=!(!I.directionalLight||!I.directionalLight.shadowsEnabled()),pe=I.map&&I.map.painter,Ae=!pe||!pe.context.extParallelShaderCompile,_e=!!pe&&pe.emissiveMode==="mrt-fallback",Le=(Ve,qe=[],Ze={})=>{this._queue.push({programId:Ve,params:Object.assign({},Ze.params,{defines:qe,overrideFog:!!Ze.fog,overrideTerrain:!!Ze.terrain,overrideGlobe:!!Ze.globe,overrideRtt:!!Ze.rtt,precompiled:!0})})};for(const Ve of f){if(Ve.visibility==="none")continue;const qe=Ve.getProgramIds();if(qe)for(const Ze of qe){if(a7.has(Ze))continue;const Xe=Ve.getDefaultProgramParams(Ze,w.zoom,I._styleColorTheme.lut);if(!Xe)continue;const ht=pe?pe.getShaderSource(Ze):null,vt=te&&(!ht||ht.usedDefines.has("RENDER_TO_TEXTURE")),st=_e&&vt?(Xe.defines||[]).concat("USE_MRT1"):Xe.defines;if(Ae){Le(Ze,Xe.defines,{params:Xe}),vt&&Le(Ze,st,{params:Xe,rtt:!0});continue}const Ut=q&&(!ht||ht.usedDefines.has("FOG")),Pt=V&&!Ve.isDraped()&&(!ht||ht.usedDefines.has("TERRAIN")),Vt=Z&&(!ht||ht.usedDefines.has("GLOBE")),St=le&&Ve.hasElevation()&&(!ht||ht.usedDefines.has("RENDER_SHADOWS"));for(const Ct of St?[!1,!0]:[!1]){const qt=Ct?(Xe.defines||[]).concat(gye):Xe.defines||[];for(const Zt of Pt?[!1,!0]:[!1])for(const Wt of Vt?[!1,!0]:[!1])for(const hs of Ut?[!1,!0]:[!1])Le(Ze,qt,{params:Xe,fog:hs,terrain:Zt,globe:Wt})}vt&&Le(Ze,st,{params:Xe,rtt:!0})}}if(Le("clippingMask"),V)for(const Ve of[!1,!0])Le("terrainRaster",Ve?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:q});if(!Ae){if(f.some(Ve=>Ve.type==="hillshade")&&Le("hillshadePrepare"),le)for(const Ve of[!1,!0])for(const qe of[!1,!0]){const Ze=[];Ve&&Ze.push("RENDER_CUTOFF"),Ze.push("RENDER_SHADOWS"),qe&&Ze.push("NORMAL_OFFSET"),Le("groundShadow",Ze),q&&Le("groundShadow",Ze,{fog:!0})}if(Z){for(const Ve of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const qe of[!1,!0]){const Ze=[...Ve,"PROJECTION_GLOBE_VIEW"];qe&&Ze.push("CUSTOM_ANTIALIASING"),Le("globeRaster",Ze,{terrain:V,globe:!0,fog:q})}for(const Ve of[!1,!0]){const qe=Ve?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Le("globeAtmosphere",qe,{fog:!0,terrain:V,globe:Ve}),Le("globeAtmosphere",[...qe,"ALPHA_PASS"],{fog:!0,terrain:V,globe:Ve})}Le("stars",[],{fog:q,terrain:V,globe:!0})}}}_executeBatch(f,w,I){if(I.map&&I.map.isMoving())return void(this._idleHandle=o.o.requestIdleCallback(Z=>this._executeBatch(Z,w,I)));w.context.sweepPendingPrograms();const R=w.context.extParallelShaderCompile?Jje.DEADLINE_MARGIN_KHR_MS:Jje.DEADLINE_MARGIN_SYNC_MS;let q=0;for(;this._queue.length>0;){const Z=this._queue.shift();if(!Z||(w.style=I,w._fogVisible=!!Z.params.overrideFog,w.getOrCreateProgram(Z.programId,Z.params),q++,f.timeRemaining()<=R))break}const V=this._queue.length===0||f.timeRemaining()>R;q>0&&V&&w.context.gl.flush(),this._idleHandle=this._queue.length>0||w.context._pendingPrograms.size>0?o.o.requestIdleCallback(Z=>this._executeBatch(Z,w,I)):null}processQueue(f,w){this._queue.length!==0&&(this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=o.o.requestIdleCallback(I=>this._executeBatch(I,f,w)))}reset(){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};SL.DEADLINE_MARGIN_KHR_MS=5,SL.DEADLINE_MARGIN_SYNC_MS=25;let vT=SL;const CL=o.a6.colorTheme,i7=new o.a8({data:new o.a9(CL.data)});function TL(E){if(!E.metadata||!E.metadata.content_area)return;const f=o.o.devicePixelRatio,{left:w,top:I,width:R,height:q}=E.metadata.content_area,V=w*f,Z=I*f;return[V,Z,V+R*f,Z+q*f]}function NN(E){if(E)return E.map(([f,w])=>[f*o.o.devicePixelRatio,w*o.o.devicePixelRatio])}class EL{constructor(f,w,I){this.id=f,this.scope=w,this.sourceCache=I,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(f){this.missingRequests.has(f.name)||this.pendingRequests.has(f.name)||this.pendingRequests.add(f.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const f=new Map;if(!this.sourceCache.loaded())return f;const w=this.sourceCache.getVisibleCoordinates();if(w.length===0)return f;const I=this.sourceCache.getSource();if(!(I instanceof Jr))return f;const R=w.map(V=>this.sourceCache.getTile(V)),q=I.getImages(R,Array.from(this.pendingRequests));for(const[V,Z]of q)f.set(o.I.from({name:V,iconsetId:this.id}),Z),this.pendingRequests.delete(V);for(const V of this.pendingRequests)this.missingRequests.add(V);return this.pendingRequests.clear(),f}}class U1{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(f,w,I,R,q){if(Ite*this._hysteresisRatio&&(V=this._previousClosestBuildingId):le&&!V&&(V=this._previousClosestBuildingId),this._previousClosestBuildingId=V,V}_calculateDistance(f,w){if(!w.center)return Number.MAX_VALUE;const I=f.lat-w.center[1],R=f.lng-w.center[0];return I*I+R*R}_isBuildingVisible(f,w,I){if(!I)return!1;for(const R of f.floorIds){const q=f.floors[R];if(!q.geometry)continue;const V=q.geometry;if(V.type==="Polygon"){const Z=this._convertRingToPoints(V.coordinates[0]);if(o.bz(Z,I))return!0}else if(V.type==="MultiPolygon"){const Z=this._convertMultiPolygonToPoints(V.coordinates);if(o.d2(I,Z))return!0}}return!1}_convertRingToPoints(f){return f.map(w=>new o.P(w[0],w[1]))}_convertMultiPolygonToPoints(f){return f.map(w=>w.length===0?[]:w[0].map(I=>new o.P(I[0],I[1])))}}class q1 extends o.E{constructor(f){super(),this._style=f,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new U1,this._initialLoadDone=!1,o.b0(["_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(f){f===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=f,this._recalculateActiveFloors())}setActiveFloorsVisibility(f){this._updateActiveFloors(f),this._updateIndoorSelector()}setIndoorData(f){let w=!1;for(const[I,R]of Object.entries(f.buildings))if(this._buildings[I])for(const q of R.floorIds)this._buildings[I].floorIds.add(q),this._buildings[I].floors[q]?this._mergeFloors(this._buildings[I].floors[q],R.floors[q]):(this._buildings[I].floors[q]=R.floors[q],w=!0);else this._buildings[I]=R,w=!0;w&&this._recalculateActiveFloors()}getIndoorTileOptions(f,w){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(f,w),indoorState:this._indoorState}:null}getControlState(){const f=this._buildings,w=this._closestBuildingId,I=w&&f?f[w]:void 0;if(!I)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let R=null;for(const V of I.floorIds)if(this._activeFloors&&this._activeFloors.has(V)){R=V;break}const q=Array.from(I.floorIds).map(V=>({id:V,name:I.floors[V].name,zIndex:I.floors[V].zIndex})).sort((V,Z)=>Z.zIndex-V.zIndex).filter((V,Z,te)=>Z===0||V.zIndex!==te[Z-1].zIndex);return{selectedFloorId:R,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:q}}_updateUI(){this._initialLoadDone=!0;const f=this._style.map.transform,w=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,f.center,f.zoom,f.getBounds(),this._makeViewportPolygon());if(w!==this._closestBuildingId){const I=this._closestBuildingId;this._closestBuildingId=w,this._onBuildingTransition(I,w),this._updateIndoorSelector()}}_onBuildingTransition(f,w){if(!this._indoorState)return;!w&&f?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!w&&!f&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.z("selector-update",this.getControlState()))}_updateActiveFloors(f){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:f,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const f=o.d3.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(w,I){if(w===I)return!0;if(!w||!I||w.size!==I.size)return!1;for(const R of w)if(!I.has(R))return!1;return!0})(f,this._activeFloors)||(this._activeFloors=f,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(f,w){w.geometry&&(f.geometry?(f.geometry.type==="Polygon"&&(f.geometry={type:"MultiPolygon",coordinates:[f.geometry.coordinates]}),w.geometry.type==="Polygon"?f.geometry.coordinates.push(w.geometry.coordinates):w.geometry.type==="MultiPolygon"&&f.geometry.coordinates.push(...w.geometry.coordinates)):f.geometry=w.geometry)}_makeViewportPolygon(){const f=this._style.map.transform,w=f.width,I=f.height;return[f.pointLocation(new o.P(0,0)),f.pointLocation(new o.P(w,0)),f.pointLocation(new o.P(w,I)),f.pointLocation(new o.P(0,I))].map(R=>new o.P(R.lng,R.lat))}}const Bf=(E,f)=>fm(E,f&&f.filter(w=>w.identifier!=="source.canvas")),Jx=o.aK(ea,["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"]),o7=o.aK(ea,["setCenter","setZoom","setBearing","setPitch"]),kN=new Set(["background","sky","slot","custom"]),l7=new Set(["building"]),V1={version:8,layers:[],sources:{}},SN={duration:300,delay:0};class pm extends o.E{constructor(f,w={}){if(super(),this.map=f,this.scope=w.scope||"",this.globalId=null,this.fragments=[],this.importDepth=w.importDepth||0,this.importsCache=w.importsCache||new Map,this.resolvedImports=w.resolvedImports||new Set,this.transition=Object.assign({},SN),this._buildingIndex=new Si(this),this.crossTileSymbolIndex=new t7,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=w.styleChanges||new at,this._hasDataDrivenEmissive=!1,this.indoorManager=new q1(this),this.dispatcher=w.dispatcher?w.dispatcher:new L1(q_(),this),this.map.painter&&this.map.painter.context){const R=this.map.painter.context.maxUniformBufferBindings,q=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:R,maxUniformBlockSizeDwords:q,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}w.imageManager?this.imageManager=w.imageManager:(this.imageManager=new Qr(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=w.glyphManager?w.glyphManager:new o.d4(f._requestManager,w.localFontFamily?o.d5.all:w.localIdeographFontFamily?o.d5.ideographs:o.d5.none,w.localFontFamily||w.localIdeographFontFamily,w.fontstackCompositing),w.modelManager?this.modelManager=w.modelManager:(this.modelManager=new xye(f._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new vT:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=w.configOptions?w.configOptions:new Map,this._configDependentLayers=w.configDependentLayers?w.configDependentLayers:new Set,this._indoorDependentLayers=w.indoorDependentLayers?w.indoorDependentLayers:new Set,this._config=w.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:w.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=w.initialConfig,this.dispatcher.broadcast("setReferrer",o.d6()),this.dispatcher.broadcast("setConfig",o.d7());const I=this;this._rtlTextPluginCallback=pm.registerForPluginStateChange(R=>{I.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:R.pluginStatus,pluginURL:R.pluginURL},(q,V)=>{if(o.d8(q),V&&V.every(Z=>Z))for(const Z in I._sourceCaches){const te=I._sourceCaches[Z],le=te.getSource().type;le!=="vector"&&le!=="geojson"||te.reload()}})}),this.on("data",R=>{if(R.dataType!=="source"||R.sourceDataType!=="metadata")return;const q=this.getOwnSource(R.sourceId);if(q&&q.vectorLayerIds)for(const V in this._layers){const Z=this._layers[V];Z.source===q.id&&this._validateLayer(Z)}})}load(f){return f?(typeof f=="string"?this.loadURL(f):this.loadJSON(f),this):this}_getGlobalId(f){if(!f)return null;if(typeof f=="string"){if(o.e(f))return f;const w=o.d9(f);if(!w.startsWith("http"))try{return new URL(w,location.href).toString()}catch{return w}return w}return`json://${o.da(JSON.stringify(f))}`}_diffStyle(f,w,I){this.globalId=this._getGlobalId(f);const R=(q,V)=>{try{V(null,this.setState(q,I))}catch(Z){V(Z,!1)}};if(typeof f=="string"){const q=this.map._requestManager.normalizeStyleURL(f),V=this.map._requestManager.transformRequest(q,o.R.Style);o.m(V,(Z,te)=>{Z?this.fire(new o.y(Z)):te&&R(te,w)})}else typeof f=="object"&&R(f,w)}loadURL(f,w={}){this.fire(new o.z("dataloading",{dataType:"style"}));const I=typeof w.validate=="boolean"?w.validate:!o.e(f);this.globalId=this._getGlobalId(f),f=this.map._requestManager.normalizeStyleURL(f,w.accessToken),this.resolvedImports.add(f);const R=this.importsCache.get(f);if(R)return this._load(R,I);const q=this.map._requestManager.transformRequest(f,o.R.Style);this._request=o.m(q,(V,Z)=>{if(this._request=null,V)this.fire(new o.y(V));else if(Z)return this.importsCache.set(f,Z),this._load(Z,I)})}loadJSON(f,w={}){this.fire(new o.z("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(f),this._request=o.o.frame(()=>{this._request=null,this._load(f,w.validate!==!1)})}loadEmpty(){this.fire(new o.z("dataloading",{dataType:"style"})),this._load(V1,!1)}_loadImports(f,w,I){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const R=[];for(const q of f){const V=this._createFragmentStyle(q),Z=new Promise(pe=>{V.once("style.import.load",pe),V.once("error",pe)}).then(()=>{this.mergeAll(),this.fire(new o.z("data",{dataType:"style"}))});if(R.push(Z),this.resolvedImports.has(q.url)){V.loadEmpty();continue}const te=q.data||this.importsCache.get(q.url);te?(q.data?(V.fire(new o.z("dataloading",{dataType:"style"})),V.globalId=V._getGlobalId(te),queueMicrotask(()=>V._load(te,w))):V.loadJSON(te,{validate:w}),this._isInternalStyle(te)&&(V.globalId=null)):q.url?V.loadURL(q.url,{validate:w}):V.loadEmpty();const le={style:V,id:q.id,config:q.config};if(I){const pe=this.fragments.findIndex(({id:Ae})=>Ae===I);this.fragments=this.fragments.slice(0,pe).concat(le).concat(this.fragments.slice(pe))}else this.fragments.push(le)}return Promise.allSettled(R)}getImportGlobalIds(f=this,w=new Set){for(const I of f.fragments)I.style.globalId&&w.add(I.style.globalId),this.getImportGlobalIds(I.style,w);return[...w.values()]}_createFragmentStyle(f){const w=this.scope?o.t(f.id,this.scope):f.id;let I;const R=this._initialConfig&&this._initialConfig[w];(f.config||R)&&(I=Object.assign({},f.config,R));const q=new pm(this.map,{scope:w,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:I,configOptions:this.options,colorThemeOverride:f["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return q.setEventedParent(this.map,{style:q}),q}_reloadImports(f=!1){this.mergeAll(),this._updateMapProjection(),f||this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),(!f||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(f&&this.isRootStyle()?(this.forEachFragmentStyle(w=>{this.dispatcher.broadcast("setLayers",{layers:w._serializeLayers(w._order),scope:w.scope,options:w.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(f){return this.isRootStyle()&&(f.fragment||!!f.schema&&f.fragment!==!1)}_load(f,w){if(this._isInternalStyle(f)){const q=Object.assign({},V1,{imports:[{id:"basemap",data:f,url:""}]},f.center?{center:f.center}:{},f.bearing?{bearing:f.bearing}:{},f.pitch?{pitch:f.pitch}:{},f.zoom?{zoom:f.zoom}:{},f.light?{light:f.light}:{});return this._importedAsBasemap=!0,void this._load(q,w)}if(this.updateConfig(this._config,f.schema),w&&Bf(this,Df(f)))return;this._loaded=!0;for(const q in f.sources)this.addSource(q,f.sources[q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.db(f);const I=()=>{if(f.iconsets)for(const te in f.iconsets)this.addIconset(te,f.iconsets[te]);f.sprite?this._loadIconset(f.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&f.glyphs&&this.glyphManager.setURL(f.glyphs);const q=uu(this.stylesheet.layers);if(this._order=q.map(te=>te.id),this.stylesheet.light&&o.w("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(this.stylesheet.lights.length===1&&this.stylesheet.lights[0].type==="flat"){const te=this.stylesheet.lights[0];this.light=new cN(te.properties,te.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new cN(this.stylesheet.light)),this._layers={};for(const te of q){const le=o.dh(te,this.scope,this._styleColorTheme.lut,this.options);le.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(le.fqid),le.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(le.fqid),this._hasAppearances=this._hasAppearances||le.getAppearances().length!==0,le.setEventedParent(this,{layer:{id:le.id}}),this._layers[le.id]=le;const pe=this.getOwnLayerSourceCache(le),Ae=!!this.directionalLight&&this.directionalLight.shadowsEnabled();pe&&le.canCastShadows()&&Ae&&(pe.castsShadows=!0)}if(this.glyphManager.url){const te=new Set;for(const le in this._layers){const pe=this._layers[le];if(pe.type==="symbol"&&pe.layout){const Ae=pe.layout.get("text-font");Ae&&Ae.value&&Ae.value.kind==="constant"&&te.add(Ae.value.value.join(","))}}for(const le of te)this.glyphManager.prefetchRange(le,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const V=this.stylesheet.terrain;V&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(V,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.z("data",{dataType:"style"}));const Z=this.isRootStyle();f.imports?this._loadImports(f.imports,w).then(()=>{this._reloadImports(!0),this.fire(new o.z(Z?"style.load":"style.import.load"))}).catch(te=>{this.fire(new o.y(new Error("Failed to load imports",te))),this.fire(new o.z(Z?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new o.z(Z?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const R=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(R){const q=this._evaluateColorThemeData(R);this._loadColorTheme(q).then(()=>{I()}).catch(V=>{o.w(`Couldn't load color theme from the stylesheet: ${V}`),I()})}else this._styleColorTheme.lut=null,I()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(f=>f.style.hasAppearances())}mergeAll(){let f,w,I,R,q,V,Z,te,le,pe;const Ae={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(_e=>{if(_e.stylesheet){if(_e.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),_e.light!=null&&(f=_e.light),_e.stylesheet.lights)for(const Le of _e.stylesheet.lights)Le.type==="ambient"&&_e.ambientLight!=null&&(w=_e.ambientLight),Le.type==="directional"&&_e.directionalLight!=null&&(I=_e.directionalLight);R=this._prioritizeTerrain(R,_e.terrain,_e.stylesheet.terrain),_e.stylesheet.fog&&_e.fog!=null&&(q=_e.fog),_e.stylesheet.snow&&_e.snow!=null&&(V=_e.snow),_e.stylesheet.rain&&_e.rain!=null&&(Z=_e.rain),_e.stylesheet.camera!=null&&(pe=_e.stylesheet.camera),_e.stylesheet.projection!=null&&(te=_e.stylesheet.projection),_e.stylesheet.transition!=null&&(le=_e.stylesheet.transition),Ae[_e.scope]=_e._styleColorTheme}}),this.light=f,this.ambientLight=w,this.directionalLight=I,this.fog=q,this.snow=V,this.rain=Z,this._styleColorThemeForScope=Ae,R===null?delete this.terrain:this.terrain=R,this.camera=pe||{"camera-projection":"perspective"},this.projection=te||{name:"mercator"},this.transition=Object.assign({},SN,le),this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(f){const w=I=>{for(const R of I.fragments)w(R.style);f(I)};w(this)}_prioritizeTerrain(f,w,I){const R=f&&f.drapeRenderMode===0;return I===null?w&&w.drapeRenderMode===0?w:R?f:null:w!=null&&(!f||R||w&&w.drapeRenderMode===1)?w:f}mergeTerrain(){let f;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(w=>{f=this._prioritizeTerrain(f,w.terrain,w.stylesheet.terrain)}),f===null?delete this.terrain:this.terrain=f,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let f;this.forEachFragmentStyle(w=>{w.stylesheet.projection!=null&&(f=w.stylesheet.projection)}),this.projection=f||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const f={},w={},I={},R={};this.forEachFragmentStyle(q=>{for(const V in q._sourceCaches){const Z=o.t(V,q.scope);f[Z]=q._sourceCaches[V]}for(const V in q._otherSourceCaches){const Z=o.t(V,q.scope);w[Z]=q._otherSourceCaches[V]}for(const V in q._symbolSourceCaches){const Z=o.t(V,q.scope);I[Z]=q._symbolSourceCaches[V]}for(const V in q._fillExtrusionSourceCaches){const Z=o.t(V,q.scope);R[Z]=q._fillExtrusionSourceCaches[V]}}),this._mergedSourceCaches=f,this._mergedOtherSourceCaches=w,this._mergedSymbolSourceCaches=I,this._mergedFillExtrusionSourceCaches=R}mergeIndoor(){this.forEachFragmentStyle(f=>{if(f.stylesheet&&f.stylesheet.indoor)for(const w of Object.values(f.stylesheet.indoor)){const I=w,R=o.t(I.sourceId,f.scope);this._mergedIndoor[R]=new Set(I.sourceLayers||[])}})}mergeLayers(){const f={},w=[],I={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(V=>{for(const Z of V._order){const te=V._layers[Z];if(te.type==="slot"){const le=o.dc(Z);if(f[le])continue;f[le]=[]}te.slot&&f[te.slot]?f[te.slot].push(te):w.push(te)}}),this._mergedOrder=[];let R=-1;const q=(V=[])=>{for(const Z of V)if(Z.type==="slot"){const te=o.dc(Z.id);f[te]&&q(f[te]),this._mergedSlots.push(te)}else{const te=o.t(Z.id,Z.scope);this._mergedOrder.push(te),I[te]=Z,Z.is3D(!!this.terrain)&&(this._has3DLayers=!0,R=this._mergedOrder.length-1),Z.type==="circle"&&(this._hasCircleLayers=!0),Z.type==="symbol"&&(this._hasSymbolLayers=!0),Z.type==="clip"&&(this._clipLayerPresent=!0)}};if(q(w),this._has3DLayers){const V={};for(let Z=0;ZV[Z]-V[te])}this._mergedLayers=I,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(f){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,f),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(f){return f.data?function(w,I,R){const q=Object.assign({},I);for(const Z of Object.keys(CL))q[Z]===void 0&&(q[Z]=CL[Z].default);const V=new o.a7(i7,w,new Map(R));return V.setTransitionOrValue(q,R),V.untransitioned().possiblyEvaluate(new o.ab(0,{worldview:void 0}))}(this.scope,f,this.options).get("data"):null}_loadColorTheme(f){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const w=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((I,R)=>{const q="data:image/png;base64,";if(!f||f.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void I();let V=f;V.startsWith(q)||(V=q+V);const Z=o.I.from("mapbox-reserved-lut"),te=new Image;te.src=V,te.onerror=()=>{this._styleColorTheme.lutLoading=!1,R(new Error("Failed to load image data"))},te.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==w)return void I();this._styleColorTheme.lutLoading=!1;const{width:le,height:pe,data:Ae}=o.o.getImageData(te);if(pe>32)return void R(new Error("The height of the image must be less than or equal to 32 pixels."));if(le!==pe*pe)return void R(new Error("The width of the image must be equal to the height squared."));this.getImage(Z)&&this.removeImage(Z),this.addImage(Z,{data:new o.q({width:le,height:pe},Ae),pixelRatio:1,sdf:!1,usvg:!1,version:0});const _e=this.imageManager.getImage(Z,this.scope);_e?(this._styleColorTheme.lut={image:_e.data,data:f},I()):R(new Error("Missing LUT image."))}})}getLut(f){const w=this._styleColorThemeForScope[f];return w?w.lut:null}setProjection(f){f?this.stylesheet.projection=f: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(f){this._spriteRequest=function(w,I,R){let q,V,Z;const te=o.o.devicePixelRatio>1?"@2x":"";let le=o.m(I.transformRequest(I.normalizeSpriteURL(w,te,".json"),o.R.SpriteJSON),(_e,Le)=>{le=null,Z||(Z=_e,q=Le,Ae())}),pe=o.n(I.transformRequest(I.normalizeSpriteURL(w,te,".png"),o.R.SpriteImage),(_e,Le)=>{pe=null,Z||(Z=_e,V=Le,Ae())});function Ae(){if(Z)R(Z);else if(q&&V){const _e=o.o.getImageData(V),Le={};for(const Ve in q){const{width:qe,height:Ze,x:Xe,y:ht,sdf:vt,pixelRatio:st,stretchX:Ut,stretchY:Pt,content:Vt}=q[Ve],St=new o.q({width:qe,height:Ze});o.q.copy(_e,St,{x:Xe,y:ht},{x:0,y:0},{width:qe,height:Ze},null),Le[Ve]={data:St,pixelRatio:st!==void 0?st:1,sdf:vt!==void 0&&vt,stretchX:Ut,stretchY:Pt,content:Vt,usvg:!1,version:0}}R(null,Le)}}return{cancel(){le&&(le.cancel(),le=null),pe&&(pe.cancel(),pe=null)}}}(f,this.map._requestManager,(w,I)=>{if(this._spriteRequest=null,w)this.fire(new o.y(w));else if(I){const R=new Map;for(const q in I)R.set(o.I.from(q),I[q]);this.addImages(R)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.z("data",{dataType:"style"}))})}addIconset(f,w){if(w.type==="sprite")return void this._loadSprite(w.url);const I=this.getOwnSourceCache(w.source);if(!I)return void this.fire(new o.y(new Error(`Source "${w.source}" as specified by iconset "${f}" does not exist and cannot be used as an iconset source`)));const R=I.getSource();if(R.type!=="raster-array")return void this.fire(new o.y(new Error(`Source "${w.source}" as specified by iconset "${f}" is not a "raster-array" source and cannot be used as an iconset source`)));R.partial=!1;const q=new EL(f,this.scope,I);this.imageManager.addImageProvider(q,this.scope)}removeIconset(f){this.imageManager.removeImageProvider(f,this.scope)}_loadIconset(f){if(!o.e(f)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(f);const w=this.map._spriteFormat==="auto";var I,R;this._spriteRequest=(R=(q,V)=>{if(this._spriteRequest=null,q)w?this._loadSprite(f):this.fire(new o.y(q));else if(V){const Z=new Map;for(const te in V)Z.set(o.I.from(te),V[te]);this.addImages(Z)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.z("data",{dataType:"style"}))},o.b4((I=this.map._requestManager).transformRequest(I.normalizeIconsetURL(f),o.R.Iconset),(q,V)=>{if(q)return void R(q);const Z={},te=new o.b2(V).readFields(Dt,{icons:[]},void 0);for(const le of te.icons){const pe={version:1,pixelRatio:o.o.devicePixelRatio,content:TL(le),stretchX:le.metadata?NN(le.metadata.stretch_x_areas):void 0,stretchY:le.metadata?NN(le.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:le};Z[le.name]=pe}R(null,Z)}))}_validateLayer(f){const w=this.getOwnSource(f.source);if(!w)return;const I=f.sourceLayer;I&&(w.type==="geojson"||w.vectorLayerIds&&!w.vectorLayerIds.includes(I))&&this.fire(new o.y(new Error(`Source layer "${I}" does not exist on source "${w.id}" as specified by style layer "${f.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const f in this._sourceCaches)if(!this._sourceCaches[f].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:f}of this.fragments)if(!f.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((f,w)=>{const I=this.fragments[w];return I&&I.style&&(f.data=I.style.serialize()),f})}_serializeSources(){const f={};for(const w in this._sourceCaches){const I=this._sourceCaches[w].getSource();f[I.id]||(f[I.id]=I.serialize())}return f}_serializeLayers(f){const w=[];for(const I of f){const R=this._layers[I];R&&R.type!=="custom"&&w.push(R.serialize())}return w}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 f in this._sourceCaches)if(this._sourceCaches[f].hasTransition())return!0;for(const f in this._layers)if(this._layers[f].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const f in this._mergedLayers){const w=this._mergedLayers[f];if(w._transitionablePaint&&w._transitionablePaint._values){const I=w._transitionablePaint._values["line-emissive-strength"];if(I&&I.value&&I.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(f){return f?this.order:this._mergedOrder}isLayerDraped(f){return!!this.terrain&&f.isDraped(this.getLayerSourceCache(f))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(f){const w=this.getOwnLayer(f);if(w)return w;this.fire(new o.y(new Error(`The layer '${f}' does not exist in the map's style.`)))}_checkSource(f){const w=this.getOwnSource(f);if(w)return w;this.fire(new o.y(new Error(`The source '${f}' does not exist in the map's style.`)))}handleIdle(){const f=this.map.painter;f&&(f.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(f,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(f){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(f),this.directionalLight&&this.directionalLight.recalculate(f);const w=this.calculateLightsBrightness();f.brightness=w||0,w!==this._brightness&&(this._brightness=w,this.dispatcher.broadcast("setBrightness",w)),f.worldview!==this._worldview&&(this._worldview=f.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const I=this._changes.isDirty();let R=!1;if(this._changes.isDirty()){const te=this._changes.getLayerUpdatesByScope();for(const le in te){const{updatedIds:pe,removedIds:Ae}=te[le];(pe||Ae)&&(this._updateWorkerLayers(le,pe,Ae),R=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(f),this.light&&this.light.updateTransitions(f),this.ambientLight&&this.ambientLight.updateTransitions(f),this.directionalLight&&this.directionalLight.updateTransitions(f),this.fog&&this.fog.updateTransitions(f),this.snow&&this.snow.updateTransitions(f),this.rain&&this.rain.updateTransitions(f),this._changes.reset()}const q={};for(const te in this._mergedSourceCaches){const le=this._mergedSourceCaches[te];q[te]=le.used,le.used=!1,le.tileCoverLift=0}const V={};for(const te of this._mergedOrder){const le=this._mergedLayers[te];if((le.visibility!=="none"||le.hasTransition())&&le.recalculate(f,this._availableImages),!le.isHidden(f.zoom)){l7.has(le.type)&&o.dd();const pe=this.getLayerSourceCache(le);pe&&(pe.used=!0,pe.tileCoverLift=Math.max(pe.tileCoverLift,le.tileCoverLift()))}if(le.type==="fill-extrusion"){const pe=o.t(le.source,le.scope);if(pe in this._mergedFillExtrusionSourceCaches){const Ae=le.layout&&le.layout.get("source-max-zoom");if(Ae!=null){const _e=V[pe];V[pe]=_e==null?Ae:Math.min(_e,Ae)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const te=this._mergedOrder.map(le=>this._mergedLayers[le]);this._programPrecompiler.buildQueue(te,f,this)}for(const te in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[te].setMaxzoomOverride(V[te]!=null?V[te]:null);this.terrain&&R&&this.mergeLayers();const Z=this.imageManager.getPendingImageProviders();for(const te of Z)te.sourceCache.used=!0;for(const te in q){const le=this._mergedSourceCaches[te];q[te]!==le.used&&le.getSource().fire(new o.z("data",{sourceDataType:"visibility",dataType:"source",sourceId:le.getSource().id}))}this.light&&this.light.recalculate(f),this.terrain&&this.terrain.recalculate(f),this.fog&&this.fog.recalculate(f),this.snow&&this.snow.recalculate(f),this.rain&&this.rain.recalculate(f),this.z=f.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),I&&this.fire(new o.z("data",{dataType:"style"}))}updateImageProviders(){const f=this.imageManager.getPendingImageProviders();for(const w of f){const I=w.resolvePendingRequests(),R=this.getFragmentStyle(w.scope);R&&R.addImages(I)}}_updateTilesForChangedImages(){const f={};for(const w in this._mergedSourceCaches){const I=this._mergedSourceCaches[w].getSource().scope;f[I]=f[I]||this._changes.getUpdatedImages(I),f[I].length!==0&&this._mergedSourceCaches[w].reloadTilesForDependencies(["icons","patterns"],f[I])}for(const w in f)this._changes.resetUpdatedImages(w)}_updateWorkerLayers(f,w,I){const R=this.getFragmentStyle(f);R&&this.dispatcher.broadcast("updateLayers",{layers:w?R._serializeLayers(w):[],scope:f,removedIds:I||[],options:R.options})}setState(f,w){if(this._checkLoaded(),Bf(this,Df(f)))return!1;(f=o.db(f)).layers=uu(f.layers);const I=function(V,Z){if(!V)return[{command:ea.setStyle,args:[Z]}];let te=[];try{if(!o.b9(V.version,Z.version))return[{command:ea.setStyle,args:[Z]}];if(o.b9(V.center,Z.center)||te.push({command:ea.setCenter,args:[Z.center]}),o.b9(V.zoom,Z.zoom)||te.push({command:ea.setZoom,args:[Z.zoom]}),o.b9(V.bearing,Z.bearing)||te.push({command:ea.setBearing,args:[Z.bearing]}),o.b9(V.pitch,Z.pitch)||te.push({command:ea.setPitch,args:[Z.pitch]}),o.b9(V.sprite,Z.sprite)||te.push({command:ea.setSprite,args:[Z.sprite]}),o.b9(V.glyphs,Z.glyphs)||te.push({command:ea.setGlyphs,args:[Z.glyphs]}),o.b9(V.imports,Z.imports)||function(Le=[],Ve=[],qe){Ve=Ve||[];const Ze=(Le=Le||[]).map(H_),Xe=Ve.map(H_),ht=Le.reduce(R1,{}),vt=Ve.reduce(R1,{}),st=Ze.slice();let Ut,Pt,Vt,St;for(Ut=0,Pt=0;Ut{Le.source&&le[Le.source]?te.push({command:ea.removeLayer,args:[Le.id]}):Ae.push(Le)});let _e=V.terrain;_e&&le[_e.source]&&(te.push({command:ea.setTerrain,args:[void 0]}),_e=void 0),te=te.concat(pe),o.b9(_e,Z.terrain)||te.push({command:ea.setTerrain,args:[Z.terrain]}),function(Le,Ve,qe){Ve=Ve||[];const Ze=(Le=Le||[]).map(H_),Xe=Ve.map(H_),ht=Le.reduce(R1,{}),vt=Ve.reduce(R1,{}),st=Ze.slice(),Ut=Object.create(null);let Pt,Vt,St,Ct,qt,Zt,Wt;for(Pt=0,Vt=0;Pt!(V.command in o7));if(I.length===0)return!1;const R=I.filter(V=>!(V.command in Jx));if(R.length>0)throw new Error(`Unimplemented: ${R.map(V=>V.command).join(", ")}.`);const q=[];return I.forEach(V=>{q.push(this[V.command](...V.args))}),w&&Promise.all(q).then(w).catch(w),this.stylesheet=f,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(f){if(f.size===0)return this;for(const[w,I]of f.entries()){if(this.getImage(w))return this.fire(new o.y(new Error(`An image with the name "${w.name}" already exists.`)));this.imageManager.addImage(w,this.scope,I),this._changes.updateImage(w,this.scope)}return this._updateWorkerImages(),this.fire(new o.z("data",{dataType:"style"})),this}addImage(f,w){return this.getImage(f)?this.fire(new o.y(new Error(`An image with the name "${f.name}" already exists.`))):(this.imageManager.addImage(f,this.scope,w),this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new o.z("data",{dataType:"style"})),this)}updateImage(f,w,I=!1){this.imageManager.updateImage(f,this.scope,w),I&&(this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new o.z("data",{dataType:"style"})))}getImage(f){return this.imageManager.getImage(f,this.scope)}removeImage(f){return this.getImage(f)?(this.imageManager.removeImage(f,this.scope),this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new o.z("data",{dataType:"style"})),this):this.fire(new o.y(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(f){return this.modelManager.addModelURLs(f,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.z("data",{dataType:"style"})),this}addModel(f,w,I={}){return this._checkLoaded(),this._validate(du,`models.${f}`,w,null,I)||(this.modelManager.addModel(f,w,this.getActualScope()),this.fire(new o.z("data",{dataType:"style"}))),this}hasModel(f){return this.modelManager.hasModel(f,this.getActualScope())}removeModel(f){return this.hasModel(f)?(this.modelManager.removeModel(f,this.getActualScope(),!1,!0),this.fire(new o.z("data",{dataType:"style"})),this):this.fire(new o.y(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(f,w,I={}){if(this._checkLoaded(),this.getOwnSource(f)!==void 0)throw new Error(`There is already a source with ID "${f}".`);if(!w.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(w).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(w.type)&&this._validate(bd,`sources.${f}`,w,null,I))return;this.map&&this.map._collectResourceTiming&&(w.collectResourceTiming=!0);const R=U_(f,w,this.dispatcher,this);R.scope=this.scope,R.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(R.id),source:R.serialize(),sourceId:R.id}));const q=V=>{const Z=(V===o.b7.Symbol?"symbol:":V===o.b7.FillExtrusion?"fill-extrusion:":"other:")+R.id,te=o.t(Z,this.scope),le=this._sourceCaches[Z]=new $a(te,R,V);V===o.b7.Symbol?this._symbolSourceCaches[R.id]=le:V===o.b7.FillExtrusion?this._fillExtrusionSourceCaches[R.id]=le:this._otherSourceCaches[R.id]=le,le.onAdd(this.map)};q(o.b7.Other),w.type!=="vector"&&w.type!=="geojson"||(q(o.b7.Symbol),w.type==="vector"&&q(o.b7.FillExtrusion)),R.onAdd&&R.onAdd(this.map),I.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(f){this._checkLoaded();const w=this.getOwnSource(f);if(!w)throw new Error("There is no source with this ID");for(const R in this._layers)if(this._layers[R].source===f)return this.fire(new o.y(new Error(`Source "${f}" cannot be removed while layer "${R}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===f)return this.fire(new o.y(new Error(`Source "${f}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const R=Object.entries(this.stylesheet.iconsets).find(([q,V])=>V.type==="source"&&V.source===f);if(R)return this.fire(new o.y(new Error(`Source "${f}" cannot be removed while iconset "${R[0]}" is using it.`)))}const I=this.getOwnSourceCaches(f);for(const R of I){const q=o.dc(R.id);delete this._sourceCaches[q],this._changes.discardSourceCacheUpdate(R.id),R.fire(new o.z("data",{sourceDataType:"metadata",dataType:"source",sourceId:R.getSource().id})),R.setEventedParent(null),R.clearTiles()}return delete this._otherSourceCaches[f],delete this._symbolSourceCaches[f],delete this._fillExtrusionSourceCaches[f],this.mergeSources(),w.setEventedParent(null),w.onRemove&&w.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(f,w){this._checkLoaded(),this.getOwnSource(f).setData(w),this._changes.setDirty()}getOwnSource(f){const w=this.getOwnSourceCache(f);return w&&w.getSource()}getOwnSources(){const f=[];for(const w in this._otherSourceCaches){const I=this.getOwnSourceCache(w);I&&f.push(I.getSource())}return f}areTilesLoaded(){const f=this._mergedSourceCaches;for(const w in f){const I=f[w]._tiles;for(const R in I){const q=I[R];if(q.state!=="loaded"&&q.state!=="errored")return!1}}return!0}setLights(f){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!f)return delete this.ambientLight,void delete this.directionalLight;const w=this._getTransitionParameters();for(const q of f){if(this._validate(oN,"lights",q))return;switch(q.type){case"ambient":if(this.ambientLight){const V=this.ambientLight;V.set(q),V.updateTransitions(w)}else this.ambientLight=new T0(q,lT(),this.scope,this.options);break;case"directional":if(this.directionalLight){const V=this.directionalLight;V.set(q),V.updateTransitions(w)}else this.directionalLight=new T0(q,It(),this.scope,this.options)}}const I=Object.assign(w,{worldview:this.map.getWorldview()}),R=new o.ab(this.z||0,I);this.ambientLight&&this.ambientLight.recalculate(R),this.directionalLight&&this.directionalLight.recalculate(R),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const f=this.directionalLight,w=this.ambientLight;if(!f||!w)return;const I=_e=>.2126*(_e[0]<=.03928?_e[0]/12.92:Math.pow((_e[0]+.055)/1.055,2.4))+.7152*(_e[1]<=.03928?_e[1]/12.92:Math.pow((_e[1]+.055)/1.055,2.4))+.0722*(_e[2]<=.03928?_e[2]/12.92:Math.pow((_e[2]+.055)/1.055,2.4)),R=f.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),q=f.properties.get("intensity"),V=f.properties.get("direction"),Z=1-o.cT(V.x,V.y,V.z)[2]/90,te=I(R)*q*Z,le=w.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),pe=w.properties.get("intensity"),Ae=I(le)*pe;return Number(((te+Ae)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const f=[];return this.directionalLight&&f.push(this.directionalLight.get()),this.ambientLight&&f.push(this.ambientLight.get()),f}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(f){if(f==null||f===""&&this.isRootStyle())return this;if(o.de(f)){const w=o.df(f),I=this.fragments.find(({id:q})=>q===w);if(!I)return;const R=o.dc(f);return I.style.getFragmentStyle(R)}{const w=this.fragments.find(({id:I})=>I===f);return w?w.style:void 0}}setFeaturesetSelectors(f){if(!f)return;const w=(I,R="")=>`${I}::${R}`;this._featuresetSelectors={};for(const I in f){const R={},q=this._featuresetSelectors[I]=[];for(const V of f[I].selectors){if(V.featureNamespace){const te=this.getOwnLayer(V.layer);if(!te){o.w(`Layer is undefined for selector: ${V.layer}`);continue}const le=w(te.source,te.sourceLayer);if(le in R&&R[le]!==V.featureNamespace){o.w(`"featureNamespace ${V.featureNamespace} of featureset ${I}'s selector is not associated to the same source, skip this selector`);continue}R[le]=V.featureNamespace}let Z;if(V.properties)for(const te in V.properties){const le=o.U(V.properties[te]);le.result==="success"&&(Z=Z||{},Z[te]=le.value)}q.push({layerId:V.layer,namespace:V.featureNamespace,properties:Z,uniqueFeatureID:V._uniqueFeatureID})}}}getFeaturesetDescriptors(f){const w=this.getFragmentStyle(f);if(!w||!w.stylesheet.featuresets)return[];const I=[];for(const R in w.stylesheet.featuresets)I.push({featuresetId:R,importId:w.scope?w.scope:void 0});return I}getFeaturesetLayers(f,w){const I=this.getFragmentStyle(w),R=I.stylesheet.featuresets;if(!R||!R[f])return this.fire(new o.y(new Error(`The featureset '${f}' does not exist in the map's style and cannot be queried.`))),[];const q=[];for(const V of R[f].selectors){const Z=I.getOwnLayer(V.layer);Z&&q.push(Z)}return q}getConfigProperty(f,w){const I=this.getFragmentStyle(f);if(!I)return null;const R=o.t(w,I.scope),q=I.options.get(R),V=q?q.value||q.default:null;return V?V.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(f,w){const I=o.t(f,w);return this._mergedIndoor[I]}setIndoorData(f,w){this.indoorManager.setIndoorData(w)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(f,w,I){const R=this.getFragmentStyle(f);if(!R)return;const q=R.stylesheet.schema;if(!q||!q[w])return;const V=o.U(I);if(V.result!=="success")return void Bf(this,V.value);const Z=V.value.expression,te=o.t(w,R.scope),le=R.options.get(te);if(!le)return;let pe;const{minValue:Ae,maxValue:_e,stepValue:Le,type:Ve,values:qe}=q[w],Ze=o.U(q[w].default);Ze.result==="success"&&(pe=Ze.value.expression),pe?(this.options.set(te,Object.assign({},le,{value:Z,default:pe,minValue:Ae,maxValue:_e,stepValue:Le,type:Ve,values:qe})),this.updateConfigDependencies(w)):this.fire(new o.y(new Error(`No schema defined for the config option "${w}" in the "${f}" fragment.`)))}getConfig(f){const w=this.getFragmentStyle(f);if(!w)return null;const I=w.stylesheet.schema;if(!I)return null;const R={};for(const q in I){const V=o.t(q,w.scope),Z=w.options.get(V),te=Z?Z.value||Z.default:null;R[q]=te?te.serialize():null}return R}setConfig(f,w){const I=this.getFragmentStyle(f);I&&(I.updateConfig(w,I.stylesheet.schema),this.updateConfigDependencies())}getSchema(f){const w=this.getFragmentStyle(f);return w?w.stylesheet.schema:null}setSchema(f,w){const I=this.getFragmentStyle(f);I&&(I.stylesheet.schema=w,I.updateConfig(I._config,w),this.updateConfigDependencies())}updateConfig(f,w){if(this._config=f,f||w)if(w)for(const I in w){let R,q;const V=o.U(w[I].default);if(V.result==="success"&&(R=V.value.expression),f&&f[I]!==void 0){const _e=o.U(f[I]);_e.result==="success"&&(q=_e.value.expression)}const{minValue:Z,maxValue:te,stepValue:le,type:pe,values:Ae}=w[I];if(R){const _e=o.t(I,this.scope);this.options.set(_e,{default:R,value:q,minValue:Z,maxValue:te,stepValue:le,type:pe,values:Ae})}else this.fire(new o.y(new Error(`No schema defined for config option "${I}".`)))}else this.fire(new o.y(new Error("Attempting to set config for a style without schema.")))}_updateLayers(f,w=()=>!0){for(const I of f){const R=this.getLayer(I);R&&w(R)&&(R.possiblyEvaluateVisibility(),this._updateLayer(R),this._changes.setDirty())}}updateConfigDependencies(f){this._updateLayers(this._configDependentLayers,w=>!f||w.expressionDependencies.configDependencies.has(f)),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(w=>{const I=w._styleColorTheme.colorThemeOverride?w._styleColorTheme.colorThemeOverride:w._styleColorTheme.colorTheme;if(I){const R=w._evaluateColorThemeData(I);(!w._styleColorTheme.lut&&R!==""||w._styleColorTheme.lut&&R!==w._styleColorTheme.lut.data)&&w.setColorTheme(I)}}),this._changes.setDirty()}addLayer(f,w,I={}){this._checkLoaded();const R=f.id;if(this._layers[R])return void this.fire(new o.y(new Error(`Layer with id "${R}" already exists on this map`)));let q;if(f.type==="custom"){if(Bf(this,o.dg(f)))return;q=o.dh(f,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof f.source=="object"&&(this.addSource(R,f.source),f=o.db(f),f=Object.assign(f,{source:R})),this._validate(Np,`layers.${R}`,f,{arrayIndex:-1},I))return;q=o.dh(f,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(q),q.setEventedParent(this,{layer:{id:R}})}const V=o.t(q.source,q.scope);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(V),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(V);let Z=this._order.length;if(w){const Ae=this._order.indexOf(w);if(Ae===-1)return void this.fire(new o.y(new Error(`Layer with id "${w}" does not exist on this map.`)));q.slot&&q.slot!==this._layers[w].slot?o.w(`Layer with id "${w}" has a different slot. Layers can only be rearranged within the same slot.`):Z=Ae}this._order.splice(Z,0,R),this._handleLayerOrderChange(),this._layers[R]=q;const te=this.getOwnLayerSourceCache(q),le=!!this.directionalLight&&this.directionalLight.shadowsEnabled();te&&q.canCastShadows()&&le&&(te.castsShadows=!0);const pe=this._changes.getRemovedLayer(q);if(pe&&q.source&&te&&q.type!=="custom"){this._changes.discardLayerRemoval(q);const Ae=o.t(q.source,q.scope);pe.type!==q.type?this._changes.updateSourceCache(Ae,"clear"):(this._changes.updateSourceCache(Ae,"reload"),te.pause())}this._updateLayer(q),q.onAdd&&q.onAdd(this.map),q.scope=this.scope,this.mergeLayers()}moveLayer(f,w){this._checkLoaded();const I=this._checkLayer(f);if(!I||f===w)return;const R=this._order.indexOf(f);this._order.splice(R,1);let q=this._order.length;if(w){const V=this._order.indexOf(w);if(V===-1)return void this.fire(new o.y(new Error(`Layer with id "${w}" does not exist on this map.`)));I.slot&&I.slot!==this._layers[w].slot?o.w(`Layer with id "${w}" has a different slot. Layers can only be rearranged within the same slot.`):q=V}this._order.splice(q,0,f),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(f){this._checkLoaded();const w=this._checkLayer(f);if(!w)return;w.setEventedParent(null);const I=this._order.indexOf(f);this._order.splice(I,1),delete this._layers[f],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(w.fqid),this._indoorDependentLayers.delete(w.fqid),this._changes.removeLayer(w);const R=this.getOwnLayerSourceCache(w);if(R&&R.castsShadows){let q=!1;for(const V in this._layers)if(this._layers[V].source===w.source&&this._layers[V].canCastShadows()){q=!0;break}R.castsShadows=q}w.onRemove&&w.onRemove(this.map),this.mergeLayers()}getOwnLayer(f){return this._layers[f]}hasLayer(f){return f in this._mergedLayers}hasLayerType(f){for(const w in this._layers)if(this._layers[w].type===f)return!0;return!1}setLayerZoomRange(f,w,I){this._checkLoaded();const R=this._checkLayer(f);R&&(R.minzoom===w&&R.maxzoom===I||(w!=null&&(R.minzoom=w),I!=null&&(R.maxzoom=I),this._updateLayer(R)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(f,w){this._checkLoaded();const I=this._checkLayer(f);I&&I.slot!==w&&(I.slot=w,this._updateLayer(I))}setFilter(f,w,I={}){this._checkLoaded();const R=this._checkLayer(f);if(R&&!o.b9(R.filter,w))return w==null?(R.filter=void 0,void this._updateLayer(R)):void(this._validate(mm,`layers.${R.id}.filter`,w,{layerType:R.type},I)||(R.filter=o.db(w),this._updateLayer(R)))}getFilter(f){const w=this._checkLayer(f);if(w)return o.db(w.filter)}setLayoutProperty(f,w,I,R={}){this._checkLoaded();const q=this._checkLayer(f);if(q&&!o.b9(q.getLayoutProperty(w),I)){if(I!=null&&(!R||R.validate!==!1)&&Bf(q,k0.call(Df,{key:`layers.${f}.layout.${w}`,layerType:q.type,objectKey:w,value:I,styleSpec:o.a6,style:{glyphs:!0,sprite:!0}})))return;q.setLayoutProperty(w,I),q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),this._updateLayer(q)}}setLayerProperty(f,w,I,R={}){this._checkLoaded();const q=this._checkLayer(f);q&&(w==="appearances"?(q.setAppearances(I),this._updateLayer(q)):q.isPaintProperty(w)?this.setPaintProperty(f,w,I,R):this.setLayoutProperty(f,w,I,R))}getLayoutProperty(f,w){const I=this._checkLayer(f);if(I)return I.getLayoutProperty(w)}setPaintProperty(f,w,I,R={}){this._checkLoaded();const q=this._checkLayer(f);if(!q||o.b9(q.getPaintProperty(w),I)||I!=null&&(!R||R.validate!==!1)&&Bf(q,Rf.call(Df,{key:`layers.${f}.paint.${w}`,layerType:q.type,objectKey:w,value:I,styleSpec:o.a6})))return;const V=q.setPaintProperty(w,I);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),V&&this._updateLayer(q),this._changes.updatePaintProperties(q)}getPaintProperty(f,w){const I=this._checkLayer(f);if(I)return I.getPaintProperty(w)}setFeatureState(f,w){if(this._checkLoaded(),"target"in f){if("featuresetId"in f.target){const{featuresetId:te,importId:le}=f.target,pe=this.getFragmentStyle(le),Ae=pe.getFeaturesetLayers(te);for(const{source:_e,sourceLayer:Le}of Ae)pe.setFeatureState({id:f.id,source:_e,sourceLayer:Le},w)}else if("layerId"in f.target){const{layerId:te}=f.target,le=this.getLayer(te);this.setFeatureState({id:f.id,source:le.source,sourceLayer:le.sourceLayer},w)}return}const I=f.source,R=f.sourceLayer,q=this._checkSource(I);if(!q)return;const V=q.type;if(V==="geojson"&&R)return void this.fire(new o.y(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(V==="vector"&&!R)return void this.fire(new o.y(new Error("The sourceLayer parameter must be provided for vector source types.")));f.id===void 0&&this.fire(new o.y(new Error("The feature id parameter must be provided.")));const Z=this.getOwnSourceCaches(I);for(const te of Z)te.setFeatureState(R,f.id,w)}removeFeatureState(f,w){if(this._checkLoaded(),"target"in f){if("featuresetId"in f.target){const{featuresetId:te,importId:le}=f.target,pe=this.getFragmentStyle(le),Ae=pe.getFeaturesetLayers(te);for(const{source:_e,sourceLayer:Le}of Ae)pe.removeFeatureState({id:f.id,source:_e,sourceLayer:Le},w)}else if("layerId"in f.target){const{layerId:te}=f.target,le=this.getLayer(te);this.removeFeatureState({id:f.id,source:le.source,sourceLayer:le.sourceLayer},w)}return}const I=f.source,R=this._checkSource(I);if(!R)return;const q=R.type,V=q==="vector"?f.sourceLayer:void 0;if(q==="vector"&&!V)return void this.fire(new o.y(new Error("The sourceLayer parameter must be provided for vector source types.")));if(w&&typeof f.id!="string"&&typeof f.id!="number")return void this.fire(new o.y(new Error("A feature id is required to remove its specific state property.")));const Z=this.getOwnSourceCaches(I);for(const te of Z)te.removeFeatureState(V,f.id,w)}getFeatureState(f){if(this._checkLoaded(),"target"in f){let q;if("featuresetId"in f.target){const{featuresetId:V,importId:Z}=f.target,te=this.getFragmentStyle(Z),le=te.getFeaturesetLayers(V);for(const{source:pe,sourceLayer:Ae}of le){const _e=te.getFeatureState({id:f.id,source:pe,sourceLayer:Ae});if(_e&&!q)q=_e;else if(!o.b9(q,_e))return void this.fire(new o.y(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 f.target){const{layerId:V}=f.target,Z=this.getLayer(V);q=this.getFeatureState({id:f.id,source:Z.source,sourceLayer:Z.sourceLayer})}return q}const w=f.source,I=f.sourceLayer,R=this._checkSource(w);if(R){if(R.type!=="vector"||I)return f.id===void 0&&this.fire(new o.y(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(w)[0].getFeatureState(I,f.id);this.fire(new o.y(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(f){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,f),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(f){f!==this._worldview&&(this._worldview=f,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const f=this.getTerrain(),w=f&&this.terrain&&this.terrain.scope===this.scope?f:this.stylesheet.terrain;return o.di({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:w,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)},I=>I!==void 0)}_updateFilteredLayers(f){for(const w of Object.values(this._mergedLayers))f(w)&&this._updateLayer(w)}_updateLayer(f){this._changes.updateLayer(f);const w=this.getLayerSourceCache(f),I=o.t(f.source,f.scope),R=this._changes.getUpdatedSourceCaches();f.source&&!R[I]&&w&&w.getSource().type!=="raster"&&(this._changes.updateSourceCache(I,"reload"),w.pause()),f.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(f){const w=Z=>this._mergedLayers[Z].is3D(!!this.terrain),I=this.order,R={},q=[];for(let Z=I.length-1;Z>=0;Z--){const te=I[Z];if(w(te)){R[te]=Z;for(const le of f){const pe=le[te];if(pe)for(const Ae of pe)q.push(Ae)}}}q.sort((Z,te)=>te.intersectionZ-Z.intersectionZ);const V=[];for(let Z=I.length-1;Z>=0;Z--){const te=I[Z];if(w(te))for(let le=q.length-1;le>=0;le--){const pe=q[le].feature;if(pe.layer&&R[pe.layer.id]{if(kN.has(pe.type))return;const Ae=this.getOwnLayerSourceCache(pe),_e=q[Ae.id]=q[Ae.id]||{sourceCache:Ae,layers:{},has3DLayers:!1};pe.is3D(!!this.terrain)&&(_e.has3DLayers=!0),_e.layers[pe.fqid]=_e.layers[pe.fqid]||{styleLayer:pe,targets:[]},_e.layers[pe.fqid].targets.push({filter:R})};if(w&&w.layers){if(!Array.isArray(w.layers))return this.fire(new o.y(new Error("parameters.layers must be an Array."))),[];for(const pe of w.layers){const Ae=this._layers[pe];if(!Ae)return this.fire(new o.y(new Error(`The layer '${pe}' does not exist in the map's style and cannot be queried for features.`))),[];V(Ae)}}else for(const pe in this._layers)V(this._layers[pe]);const Z=this._queryRenderedFeatures(f,q,I),te=this._flattenAndSortRenderedFeatures(Z),le=[];for(const pe of te)o.dk(pe.layer.id)===this.scope&&le.push(pe);return le}queryRenderedFeatureset(f,w,I){let R;w&&!Array.isArray(w)&&w.filter&&(this._validate(mm,"queryRenderedFeatures.filter",w.filter,null,w),R=o.dj(w.filter));const q="mock",V=[];if(w&&w.target)V.push(Object.assign({},w,{targetId:q,filter:R}));else{const pe=this.getFeaturesetDescriptors();for(const Ae of pe)V.push({targetId:q,filter:R,target:Ae});for(const{style:Ae}of this.fragments){const _e=Ae.getFeaturesetDescriptors();for(const Le of _e)V.push({targetId:q,filter:R,target:Le})}}const Z=this.queryRenderedTargets(f,V,I),te=[],le=new Set;for(const pe of Z)for(const Ae of pe.variants[q])Uz(Ae,pe,le)||te.push(new o.dl(pe,Ae));return te}queryRenderedTargets(f,w,I){const R={},q=(Z,te,le,pe)=>{const Ae=R[te.id]=R[te.id]||{sourceCache:te,layers:{},has3DLayers:!1};if(Ae.layers[Z.fqid]=Ae.layers[Z.fqid]||{styleLayer:Z,targets:[]},Z.is3D(!!this.terrain)&&(Ae.has3DLayers=!0),!pe)return le.uniqueFeatureID=!1,void Ae.layers[Z.fqid].targets.push(le);Ae.layers[Z.fqid].targets.push(Object.assign({},le,{namespace:pe.namespace,properties:pe.properties,uniqueFeatureID:pe.uniqueFeatureID}))};for(const Z of w)if("featuresetId"in Z.target){const{featuresetId:te,importId:le}=Z.target,pe=this.getFragmentStyle(le);if(!pe||!pe._featuresetSelectors)continue;const Ae=pe._featuresetSelectors[te];if(!Ae){this.fire(new o.y(new Error(`The featureset '${te}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const _e of Ae){const Le=pe.getOwnLayer(_e.layerId);Le&&!kN.has(Le.type)&&q(Le,pe.getOwnLayerSourceCache(Le),Z,_e)}}else if("layerId"in Z.target){const{layerId:te}=Z.target,le=this.getLayer(te);if(!le||kN.has(le.type))continue;q(le,this.getLayerSourceCache(le),Z)}const V=this._queryRenderedFeatures(f,R,I);return this._flattenAndSortRenderedFeatures(V)}_queryRenderedFeatures(f,w,I){const R=[],q=!!this.map._showQueryGeometry,V=Gs.createFromScreenPoints(f,I);for(const Z in w){const te=qz(V,w[Z],this._availableImages,I,q,this.getActualScope());Object.keys(te).length&&R.push(te)}if(this.placement)for(const Z in w){if(w[Z].sourceCache._renderSourceType!==o.b7.Symbol)continue;const te=dT(V.screenGeometry,w[Z],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(te).length&&R.push(te)}return R}querySourceFeatures(f,w){const I=w&&w.filter;I&&this._validate(mm,"querySourceFeatures.filter",I,null,w);let R=[];const q=this.getOwnSourceCaches(f);for(const V of q)R=R.concat(Ep(V,w));return R}addSourceType(f,w,I){return pm.getSourceType(f)?I(new Error(`A source type called "${f}" already exists.`)):(pm.setSourceType(f,w),I(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(f,w,I={}){this._checkLoaded();const R=this.light.getLight();let q=!1;for(const Z in f)if(!o.b9(f[Z],R[Z])){q=!0;break}if(!q)return;const V=this._getTransitionParameters();this.light.setLight(f,w,I),this.light.updateTransitions(V)}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(f,w=1){if(this._checkLoaded(),!f)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),w===0&&delete this.terrain,f===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let I=f;const R=!("source"in f)||f.source==null;if(w===1){if(this.disableElevatedTerrain)return;if("source"in I&&typeof I.source=="object"){const Z="terrain-dem-src";this.addSource(Z,I.source),I=o.db(I),I=Object.assign(I,{source:Z})}const q=Object.assign({},I),V={};if(this.terrain&&R){q.source=this.terrain.get().source;const Z=this.terrain?this.getFragmentStyle(this.terrain.scope):null;Z&&(V.style=Z.serialize())}if(this._validate(A1,"terrain",q,V))return}if(!this.terrain||this.terrain.scope!==this.scope&&!R||this.terrain&&w!==this.terrain.drapeRenderMode){if(!I)return;this._createTerrain(I,w),this.fire(new o.z("data",{dataType:"style"}))}else{const q=this.terrain,V=q.get();for(const Z of Object.keys(o.a6.terrain))!Object.hasOwn(I,Z)&&o.a6.terrain[Z].default&&(I[Z]=o.a6.terrain[Z].default);for(const Z in f)if(!o.b9(f[Z],V[Z])){q.set(f,this.options),this.stylesheet.terrain=f;const te=this._getTransitionParameters({duration:0});q.updateTransitions(te),this.fire(new o.z("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(f){const w=this.fog=new S0(f,this.map.transform,this.scope,this.options);this.stylesheet.fog=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}_createSnow(f){const w=this.snow=new yL(f,this.map.transform,this.scope,this.options);this.stylesheet.snow=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}_createRain(f){const w=this.rain=new B_(f,this.map.transform,this.scope,this.options);this.stylesheet.rain=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const f of this.map._markers)f._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(f){if(this._checkLoaded(),f)if(this.fog){const w=this.fog;if(!o.b9(w.get(),f)){w.set(f,this.options),this.stylesheet.fog=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}}else this._createFog(f);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(f){if(this._checkLoaded(),!f)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const w=this.snow;if(!o.b9(w.get(),f)){w.set(f,this.options),this.stylesheet.snow=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}}else this._createSnow(f);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(f){if(this._checkLoaded(),!f)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const w=this.rain;if(!o.b9(w.get(),f)){w.set(f,this.options),this.stylesheet.rain=w.get();const I=this._getTransitionParameters({duration:0});w.updateTransitions(I)}}else this._createRain(f);this._markersNeedUpdate=!0}_reloadColorTheme(){const f=()=>{for(const R in this._layers)this._layers[R].lut=this._styleColorTheme.lut;for(const R in this._sourceCaches)this._sourceCaches[R].clearTiles()},w=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!w)return this._styleColorTheme.lut=null,void f();const I=this._evaluateColorThemeData(w);this._loadColorTheme(I).then(()=>{this.fire(new o.z("colorthemeset")),f()}).catch(R=>{o.w(`Couldn't set color theme: ${R}`)})}setColorTheme(f){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=f,this._reloadColorTheme()}setImportColorTheme(f,w){const I=this.getFragmentStyle(f);I&&(I._styleColorTheme.colorThemeOverride=w,I._reloadColorTheme())}_getTransitionParameters(f){return{now:o.o.now(),transition:Object.assign(this.transition,f)}}updateDrapeFirstLayers(){if(!this.terrain)return;const f=[],w=[];for(const I of this._mergedOrder)this.isLayerDraped(this._mergedLayers[I])?f.push(I):w.push(I);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...f),this._drapedFirstOrder.push(...w)}_createTerrain(f,w){const I=this.terrain=new kp(f,w,this.scope,this.options,this.map.getWorldview());w===1&&(this.stylesheet.terrain=f),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const R=this._getTransitionParameters({duration:0});I.updateTransitions(R)}_force3DLayerUpdate(){for(const f in this._layers){const w=this._layers[f];w.type==="fill-extrusion"&&this._updateLayer(w)}}_forceSymbolLayerUpdate(){for(const f in this._layers){const w=this._layers[f];w.type==="symbol"&&this._updateLayer(w)}}_validate(f,w,I,R,q={}){if(q&&q.validate===!1)return!1;const V=Object.assign({},this.serialize());return Bf(this,f.call(Df,Object.assign({key:w,style:V,value:I,styleSpec:o.a6},R)))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dm.off("pluginStateChange",this._rtlTextPluginCallback);for(const f in this._mergedLayers)this._mergedLayers[f].setEventedParent(null);for(const f in this._mergedSourceCaches){const w=this._mergedSourceCaches[f];w.clearTiles(),w.setEventedParent(null);const I=w.getSource();I&&I.onRemove&&I.onRemove(this.map)}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.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(f){const w=this.getSourceCaches(f);for(const I of w)I.clearTiles()}clearSources(){for(const f in this._mergedSourceCaches)this._mergedSourceCaches[f].clearTiles()}clearLayers(){for(const f in this._mergedLayers){const w=this._mergedLayers[f];w._clear&&w._clear()}}reloadSource(f){const w=this.getSourceCaches(f);for(const I of w)I.resume(),I.reload()}reloadSources(){for(const f of this.getSources())f.reload&&f.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(f=>{f.modelManager.reloadModels(f.scope)})}updateSources(f){let w;this.directionalLight&&(w=yT(this.directionalLight));const I=new Set,R=new Set,q=new Set;for(const V in this._mergedLayers){const Z=this._mergedLayers[V];Z.type==="building"?I.add(Z.source):Z.type==="raster"&&Z.paint&&Z.paint.get("raster-elevation-reference")==="ground"&&q.add(Z.source),Z.hasElevation()&&!R.has(Z.source)&&R.add(Z.source)}for(const V in this._mergedSourceCaches){const Z=this._mergedSourceCaches[V],te=R.has(Z._source.id);Z._isRasterElevatedOverTerrain=q.has(Z._source.id),I.has(Z._source.id)&&(Z._source.reparseOverscaled=!1),Z.update(f,void 0,void 0,w,te)}}_reloadSources(){for(const f in this._sourceCaches){const w=this._sourceCaches[f];w.resume(),w.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.z("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Xz),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(f,w,I,R,q){this.pauseablePlacement||(this.pauseablePlacement=new Xz);let V=!1,Z=!1;const te={},le={};for(const qe of this._mergedOrder){const Ze=this._mergedLayers[qe];if(Ze.type!=="symbol")continue;const Xe=o.t(Ze.source,Ze.scope);let ht=te[Xe];if(!ht){const st=this.getLayerSourceCache(Ze);if(!st)continue;const Ut=st.getRenderableIds(!0).map(Pt=>st.getTileByID(Pt));le[Xe]=Ut.slice(),ht=te[Xe]=Ut.sort((Pt,Vt)=>Vt.tileID.overscaledZ-Pt.tileID.overscaledZ||(Pt.tileID.isLessThan(Vt.tileID)?-1:1))}const vt=this.crossTileSymbolIndex.addLayer(Ze,ht,f.center.lng,f.projection);V=V||vt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const pe=!!(this.placement&&!f.equals(this.placement.transform)),Ae=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!q||this.placement.lastReplacementSourceUpdateTime!==q.updateTime)),_e=pe||Ae||V,Le=(_e||this.pauseablePlacement.isStale())&&I===0,Ve=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),f.zoom)&&I!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Le||Ve)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(f,this._mergedOrder,w,I,R,this.placement,this.fog&&f.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const qe=this.map.painter.maxFrontCutoffRawStart;if(qe>0){const Ze=180*f.pitch/Math.PI;if(Ze>=15){const Xe=Math.min(1,Math.max(0,(Ze-15)/5)),ht=Xe*Xe*(3-2*Xe);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-ht)+qe*ht}}}if(this.pauseablePlacement.isDone()?_e&&I!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,te,le,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),Z=!0),V&&this.pauseablePlacement.setStale()),Z||V){this._buildingIndex.onNewFrame(f.zoom);for(let qe=0;qeq===f.id)!==-1)return void this.fire(new o.y(new Error(`Import with id '${f.id}' already exists in the map's style.`)));if(!w)return I.push(f),this._loadImports([f],!0);const R=I.findIndex(({id:q})=>q===w);return R===-1&&this.fire(new o.y(new Error(`Import with id "${w}" does not exist on this map.`))),this.stylesheet.imports=I.slice(0,R).concat(f).concat(I.slice(R)),this._loadImports([f],!0,w)}updateImport(f,w){this._checkLoaded();const I=this.stylesheet.imports||[],R=this.getImportIndex(f);return R===-1?this:typeof w=="string"?(this.setImportUrl(f,w),this):(w.url&&w.url!==I[R].url&&this.setImportUrl(f,w.url),o.b9(w.config,I[R].config)||this.setImportConfig(f,w.config,w.data.schema),o.b9(w.data,I[R].data)||this.setImportData(f,w.data),this)}moveImport(f,w){this._checkLoaded();let I=this.stylesheet.imports||[];const R=this.getImportIndex(f);if(R===-1)return this;const q=this.getImportIndex(w);if(q===-1)return this;const V=I[R],Z=this.fragments[R];return I=I.filter(({id:te})=>te!==f),this.fragments=this.fragments.filter(({id:te})=>te!==f),this.stylesheet.imports=I.slice(0,q).concat(V).concat(I.slice(q)),this.fragments=this.fragments.slice(0,q).concat(Z).concat(this.fragments.slice(q)),this.mergeLayers(),this}setImportUrl(f,w){this._checkLoaded();const I=this.stylesheet.imports||[],R=this.getImportIndex(f);if(R===-1)return this;I[R].url=w;const q=this.fragments[R];return q.style=this._createFragmentStyle(I[R]),q.style.on("style.import.load",()=>this.mergeAll()),q.style.loadURL(w),this}setImportData(f,w){this._checkLoaded();const I=this.getImportIndex(f),R=this.stylesheet.imports||[];return I===-1?this:w?(this.fragments[I].style.setState(w),this._reloadImports(),this):(delete R[I].data,this.setImportUrl(f,R[I].url))}setImportConfig(f,w,I){this._checkLoaded();const R=this.getImportIndex(f),q=this.stylesheet.imports||[];if(R===-1)return this;w?q[R].config=w:delete q[R].config;const V=this.fragments[R];I&&V.style.stylesheet&&(V.style.stylesheet.schema=I);const Z=V.style.stylesheet&&V.style.stylesheet.schema;return V.config=w,V.style.updateConfig(w,Z),this.updateConfigDependencies(),this}removeImport(f){this._checkLoaded();const w=this.stylesheet.imports||[],I=this.getImportIndex(f);I!==-1&&(w.splice(I,1),this.fragments[I].style._remove(),this.fragments.splice(I,1),this._reloadImports())}getImportIndex(f){const w=(this.stylesheet.imports||[]).findIndex(I=>I.id===f);return w===-1&&this.fire(new o.y(new Error(`Import '${f}' does not exist in the map's style and cannot be updated.`))),w}getLayer(f){return this._mergedLayers[f]}getSources(){const f=[];for(const w in this._mergedOtherSourceCaches){const I=this._mergedOtherSourceCaches[w];I&&f.push(I.getSource())}return f}getSource(f,w){const I=this.getSourceCache(f,w);return I&&I.getSource()}getLayerSource(f){const w=this.getLayerSourceCache(f);return w&&w.getSource()}getSourceCache(f,w){const I=o.t(f,w);return this._mergedOtherSourceCaches[I]}getLayerSourceCache(f){const w=o.t(f.source,f.scope);return f.type==="symbol"?this._mergedSymbolSourceCaches[w]:f.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[w]||this._mergedOtherSourceCaches[w]}getSourceCaches(f){if(f==null)return Object.values(this._mergedSourceCaches);const w=[];return this._mergedOtherSourceCaches[f]&&w.push(this._mergedOtherSourceCaches[f]),this._mergedSymbolSourceCaches[f]&&w.push(this._mergedSymbolSourceCaches[f]),this._mergedFillExtrusionSourceCaches[f]&&w.push(this._mergedFillExtrusionSourceCaches[f]),w}updateSourceCaches(){const f=this._changes.getUpdatedSourceCaches();for(const w in f){const I=f[w];I==="reload"?this.reloadSource(w):I==="clear"&&this.clearSource(w)}}updateLayers(f){const w=this._changes.getUpdatedPaintProperties();for(const I of w){const R=this.getLayer(I);R&&R.updateTransitions(f)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(f){this.stylesheet.glyphs=f,this.glyphManager.setURL(f)}getImages(f,w,I){this.imageManager.getImages(w.icons.concat(w.patterns),w.scope,I),this._updateTilesForChangedImages();const R=w.icons.map(te=>o.I.toString(te)),q=w.patterns.map(te=>o.I.toString(te)),V=te=>{te&&(te.setDependencies(w.tileID.key,"icons",R),te.setDependencies(w.tileID.key,"patterns",q))},Z=o.t(w.source,w.scope);V(this._mergedOtherSourceCaches[Z]),V(this._mergedSymbolSourceCaches[Z]),(w.icons.some(te=>te.iconsetId)||w.patterns.some(te=>te.iconsetId))&&this.fire(new o.z("data",{dataType:"style"}))}rasterizeImages(f,w,I){this.imageManager.rasterizeImages(w,I)}checkAtlasCache(f,w,I){const R=this.imageManager.imageAtlasCache.findCachedAtlas(w.descriptor);I(null,R&&R.contentDescriptor?{iconPositions:R.iconPositions,patternPositions:R.patternPositions,sourceHash:R.contentDescriptor.hash}:null)}getGlyphs(f,w,I){this.glyphManager.getGlyphs(w.stacks,I)}getOwnSourceCache(f){return this._otherSourceCaches[f]}getOwnLayerSourceCache(f){return f.type==="symbol"?this._symbolSourceCaches[f.source]:f.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[f.source]||this._otherSourceCaches[f.source]}getOwnSourceCaches(f){const w=[];return this._otherSourceCaches[f]&&w.push(this._otherSourceCaches[f]),this._symbolSourceCaches[f]&&w.push(this._symbolSourceCaches[f]),this._fillExtrusionSourceCaches[f]&&w.push(this._fillExtrusionSourceCaches[f]),w}_isSourceCacheLoaded(f){const w=this.getOwnSourceCaches(f);return w.length===0?(this.fire(new o.y(new Error(`There is no source with ID '${f}'`))),!1):w.every(I=>I.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(f,w){if(!this._clipLayerPresent&&f.type!=="fill-extrusion"&&f.type!=="building")return!1;const I=f.type==="fill-extrusion"&&(f.sourceLayer==="building"||f.sourceLayer==="procedural_buildings"),R=f.type==="building";if(f.is3D(!!this.terrain)){if(I||R||w&&w.type==="batched-model"||f.type==="model")return!0}else if(f.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(f=>{f.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}pm.getSourceType=function(E){return Wa[E]},pm.setSourceType=function(E,f){Wa[E]=f},pm.registerForPluginStateChange=o.dn;var CN=` #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`,TN=` #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 premultiplyColor(vec3 nonPremultipliedColor,float a) {return vec4(nonPremultipliedColor*a,a);}vec3 unpremultiplyColor(vec4 premultipliedColor) {if (premultipliedColor.a > 0.0) {return premultipliedColor.rgb/premultipliedColor.a;}return premultipliedColor.rgb;}vec3 applyLUT(highp sampler3D lut,vec3 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return texture(lut,uvw).rgb;}vec4 applyLUT(highp sampler3D lut,vec4 premultipliedColor) {return premultiplyColor(applyLUT(lut,unpremultiplyColor(premultipliedColor)),premultipliedColor.a);}`,Q_=` #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`,AL="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;}",ML=` #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`,IL=`#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`,H1=`#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`,bT=` #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`,c7=`#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`,d7=`#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`,u7=`#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 _T=/#include\s+"([^"]+)"/g,wT=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,PL=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,LL=new Set(["ifdef","ifndef","elif","if","defined"]),EN=new Set;hy(CN,EN),hy(Q_,EN),hy(TN,EN);const J_={"_prelude_fog.vertex.glsl":IL,"_prelude_terrain.vertex.glsl":ML,"_prelude_shadow.vertex.glsl":d7,"_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":H1,"_prelude_shadow.fragment.glsl":u7,"_prelude_lighting.glsl":bT,"_prelude_raster_array.glsl":c7},jT={},ew="precision highp float;",tw="precision mediump float;",DL=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,xm={preludeTerrain:ka("",ML),preludeFog:ka(H1,IL),preludeShadow:ka(u7,d7),preludeRasterArray:ka(c7,""),preludeLighting:ka(bT,bT),preludePrecisionQualifiers:ka(tw,ew),prelude:ka(TN,Q_),preludeExtensions:ka(DL,"")},RL=[DL,tw,CN,xm.prelude.fragmentSource].join(` `),NT=[ew,CN,xm.prelude.vertexSource].join(` `);var yye={background:ka(`#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:ka(`#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 }`),circle:ka(`#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:ka("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:ka(`#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:ka(`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:ka("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:ka("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:ka("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:ka("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:ka(`#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:ka(`#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:ka(`#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:ka(`#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:ka(`#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:ka(`#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:ka(`uniform highp sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;uniform highp float u_max_density;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;}highp float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);highp float n=density/max(u_max_density,0.001);highp float t=sqrt(n/(n+1.0));glFragColor=vec4(avgColor*t,t);} 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;}"),lineBlendReduce:ka("uniform highp sampler2D u_image;uniform vec2 u_texel_size;uniform bool u_first_pass;in vec2 v_pos;void main() {vec2 o=u_texel_size*0.5;vec4 s0=texture(u_image,v_pos+vec2(-o.x,-o.y));vec4 s1=texture(u_image,v_pos+vec2( o.x,-o.y));vec4 s2=texture(u_image,v_pos+vec2(-o.x, o.y));vec4 s3=texture(u_image,v_pos+vec2( o.x, o.y));float r0; float g0;float r1; float g1;float r2; float g2;float r3; float g3;if (u_first_pass) {float a0=s0.a;float a1=s1.a;float a2=s2.a;float a3=s3.a;r0=a0; g0=a0 > 0.0 ? 1.0 : 0.0;r1=a1; g1=a1 > 0.0 ? 1.0 : 0.0;r2=a2; g2=a2 > 0.0 ? 1.0 : 0.0;r3=a3; g3=a3 > 0.0 ? 1.0 : 0.0;} else {r0=s0.r; g0=s0.g;r1=s1.r; g1=s1.g;r2=s2.r; g2=s2.g;r3=s3.r; g3=s3.g;}glFragColor=vec4((r0+r1+r2+r3)*0.25,(g0+g1+g2+g3)*0.25,0.0,0.0);}","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:ka(`#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:ka("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:ka(`#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:ka(`#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:ka(`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:ka(`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:ka(`#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:ka(`#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;uniform bool u_clip_to_tile_borders;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv;in vec2 v_tile_pos; #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 DEBUG_ELEVATION_ID in vec3 v_elevation_id_col; #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 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 #ifdef LINE_BLEND_ADDITIVE {float cov=alpha*diluted_opacity;glFragColor=vec4(cov > 0.0 ? out_color.rgb/cov : vec3(0.0),cov);} #else #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0); #else glFragColor=out_color; #endif #endif #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 #ifdef DEBUG_ELEVATION_ID glFragColor=vec4(v_elevation_id_col,1.0); #endif if (u_clip_to_tile_borders) {if (v_tile_pos.x > 1.0 || v_tile_pos.y > 1.0 || v_tile_pos.x < 0.0 || v_tile_pos.y < 0.0) {discard;}}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 DEBUG_ELEVATION_ID in vec3 a_elevation_id_col; #endif #ifdef DEBUG_ELEVATION_ID out vec3 v_elevation_id_col; #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 float u_z_offset;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;out vec2 v_tile_pos; #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=u_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset+=a_z_offset_width.x; #endif #ifdef DEBUG_ELEVATION_ID v_elevation_id_col=a_elevation_id_col; #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;v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,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 v_tile_pos=offset_pos;gl_Position=u_matrix*vec4(v_tile_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 v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,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 if (gapwidth > 0.0) {float visible_ratio=(halfwidth+ANTIALIASING)/outset;vec2 visible_screen_width=screen_width*visible_ratio;float max_visible_component=max(visible_screen_width.x,visible_screen_width.y);dilute_scale=min(1.0,max_visible_component/min_pixel);}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 v_tile_pos=(v_tile_pos+extrude)/EXTENT; #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:ka(`#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:ka(`#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 }`),symbol:ka(`#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 highp 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 highp 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;highp 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 highp 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:ka(`#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:ka("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:ka(`#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 }`,AL),skyboxGradient:ka(`#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 }`,AL),skyboxCapture:ka(` 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:ka(`#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:ka(`#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:ka(`#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 texColor=vec4(unpremultiplyColor(texColor),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:ka("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:ka(`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);}`),occlusion:ka("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 hy(E,f){const w=E.split(` `);for(let I of w){if(I=I.trimStart(),I[0]!=="#"||!I.includes("if")||I.startsWith("#endif"))continue;const R=I.match(PL);if(R)for(const q of R)LL.has(q)||f.add(q)}}function kT(E){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(E)}function ka(E,f){const w=new Set,I=[],R=[];E=E.replace(_T,(V,Z)=>(R.push(Z),"")),f=f.replace(_T,(V,Z)=>(I.push(Z),""));let q=new Set(EN);hy(E,q),hy(f,q);for(const V of[...I,...R])jT[V]||(jT[V]=new Set,hy(J_[V],jT[V])),q=new Set([...q,...jT[V]]);return{fragmentSource:E=E.replace(wT,(V,Z,te,le,pe)=>(w.add(pe),Z==="define"?` #ifndef HAS_UNIFORM_u_${pe} ${kT(le)?"flat ":""}in ${te} ${le} ${pe}; #else uniform ${te} ${le} u_${pe}; #endif `:Z==="initialize"?` #ifdef HAS_UNIFORM_u_${pe} ${te} ${le} ${pe} = u_${pe}; #endif `:Z==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${le} ${pe}; #endif `:Z==="initialize-attribute"?"":void 0)),vertexSource:f=f.replace(wT,(V,Z,te,le,pe)=>{const Ae=`MATERIAL_ATTRIBUTE_OFFSET_${pe}`,_e=le==="float"?"vec2":le,Le=`GET_ATTRIBUTE_${_e}(a_${pe}, materialInfo, ${Ae})`,Ve=pe.includes("color")?"color":_e;return Z==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${le} a_${pe}; #endif `:w.has(pe)?Z==="define"?` #ifndef HAS_UNIFORM_u_${pe} uniform lowp float u_${pe}_t; #if !defined(${Ae}) in ${te} ${_e} a_${pe}; #endif ${kT(le)?"flat ":""}out ${te} ${le} ${pe}; #else uniform ${te} ${le} u_${pe}; #endif `:Z==="initialize"?Ve==="vec4"||Ve==="uvec4"?` #ifndef HAS_UNIFORM_u_${pe} ${pe} = a_${pe}; #else ${te} ${le} ${pe} = u_${pe}; #endif `:` #if !defined(HAS_UNIFORM_u_${pe}) #ifdef ${Ae} ${pe} = unpack_mix_${Ve}(${Le}, u_${pe}_t); #else ${pe} = unpack_mix_${Ve}(a_${pe}, u_${pe}_t); #endif #else ${te} ${le} ${pe} = u_${pe}; #endif `:Z==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${le} a_${pe}; out ${te} ${le} ${pe}; #endif `:Z==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} ${pe} = a_${pe}; #endif `:void 0:Z==="define"?` #ifndef HAS_UNIFORM_u_${pe} uniform lowp float u_${pe}_t; #if !defined(${Ae}) in ${te} ${_e} a_${pe}; #endif #else uniform ${te} ${le} u_${pe}; #endif `:Z==="define-instanced"?Ve==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${pe}0; in vec4 a_${pe}1; in vec4 a_${pe}2; in vec4 a_${pe}3; #else uniform ${te} ${le} u_${pe}; #endif `:` #ifdef INSTANCED_ARRAYS in ${te} ${_e} a_${pe}; #else uniform ${te} ${le} u_${pe}; #endif `:Z==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${pe} ${te} ${le} ${pe} = a_${pe}; #endif `:Ve==="vec4"||Ve==="uvec4"?` #ifndef HAS_UNIFORM_u_${pe} #ifdef ${Ae} ${te} ${le} ${pe} = ${Le}; #else ${te} ${le} ${pe} = a_${pe}; #endif #else ${te} ${le} ${pe} = u_${pe}; #endif `:` #ifndef HAS_UNIFORM_u_${pe} #ifdef ${Ae} ${te} ${le} ${pe} = unpack_mix_${Ve}(${Le}, u_${pe}_t); #else ${te} ${le} ${pe} = unpack_mix_${Ve}(a_${pe}, u_${pe}_t); #endif #else ${te} ${le} ${pe} = u_${pe}; #endif `}),usedDefines:q,vertexIncludes:I,fragmentIncludes:R}}class OL{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(f,w,I,R,q,V,Z,te){this.context=f;let le=this.boundPaintVertexBuffers.length!==R.length;for(let Ae=0;!le&&Ae{const Ut=vt.paint.get("hillshade-shadow-color"),Pt=vt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Vt=vt.paint.get("hillshade-highlight-color"),St=vt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Ct=vt.paint.get("hillshade-accent-color"),qt=vt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Zt=vt.paint.get("hillshade-emissive-strength");let Wt=o.am(vt.paint.get("hillshade-illumination-direction"));if(vt.paint.get("hillshade-illumination-anchor")==="viewport")Wt-=Xe.transform.angle;else if(Xe.style&&Xe.style.enable3dLights()&&Xe.style.directionalLight){const ms=Xe.style.directionalLight.properties.get("direction"),Zs=o.cT(ms.x,ms.y,ms.z);Wt=o.am(Zs[1])}const hs=!Xe.options.moving;return{u_matrix:st||Xe.transform.calculateProjMatrix(ht.tileID.toUnwrapped(),hs),u_image:0,u_latrange:ST(0,ht.tileID),u_light:[vt.paint.get("hillshade-exaggeration"),Wt],u_shadow:Ut.toPremultipliedRenderColor(Pt?null:vt.lut),u_highlight:Vt.toPremultipliedRenderColor(St?null:vt.lut),u_emissive_strength:Zt,u_accent:Ct.toPremultipliedRenderColor(qt?null:vt.lut)}})(E,w,I,E.terrain?f.projMatrix:null);E.uploadCommonUniforms(Z,_e,f.toUnwrapped());const{tileBoundsBuffer:Ve,tileBoundsIndexBuffer:qe,tileBoundsSegments:Ze}=E.getTileBoundsBuffers(w);_e.draw(E,te.TRIANGLES,R,q,V,en.disabled,Le,I.id,Ve,qe,Ze)}function CT(E,f,w){if(!f.needsDEMTextureUpload)return;const I=E.context,R=I.gl;I.pixelStoreUnpackPremultiplyAlpha.set(!1),f.demTexture=f.demTexture||E.getTileTexture(w.stride);const q=w.getPixels();f.demTexture?f.demTexture.update(q,{premultiply:!1}):f.demTexture=new o.T(I,q,R.R32F,{premultiply:!1}),f.needsDEMTextureUpload=!1}function TT(E,f,w){const I=E.context,R=I.gl;if(!f.dem)return;const q=f.dem;if(I.activeTexture.set(R.TEXTURE1),CT(E,f,q),!f.demTexture)return;f.demTexture.bind(R.NEAREST,R.CLAMP_TO_EDGE);const V=q.dim;I.activeTexture.set(R.TEXTURE0);let Z=f.hillshadeFBO;if(!Z){const _e=new o.T(I,{width:V,height:V,data:null},R.RGBA8);_e.bind(R.LINEAR,R.CLAMP_TO_EDGE),Z=f.hillshadeFBO=I.createFramebuffer(V,V,1,"renderbuffer"),Z.colorAttachment0.set(_e.texture)}I.bindFramebuffer.set(Z.framebuffer),I.viewport.set([0,0,V,V]);const{tileBoundsBuffer:te,tileBoundsIndexBuffer:le,tileBoundsSegments:pe}=E.getMercatorTileBoundsBuffers(),Ae=[];E.linearFloatFilteringSupported()&&Ae.push("TERRAIN_DEM_FLOAT_FORMAT"),E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback"&&Ae.push("USE_MRT1"),E.getOrCreateProgram("hillshadePrepare",{defines:Ae}).draw(E,R.TRIANGLES,Br.disabled,kn.disabled,En.unblended,en.disabled,((_e,Le)=>{const Ve=Le.stride,qe=o.bd();return o.bX(qe,0,o.ak,-o.ak,0,0,1),o.bB(qe,qe,[0,-o.ak,0]),{u_matrix:qe,u_image:1,u_dimension:[Ve,Ve],u_zoom:_e.overscaledZ}})(f.tileID,q),w.id,te,le,pe),f.needsHillshadePrepare=!1}class vo{constructor(f){this.gl=f.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(f){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class h7 extends vo{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(f){const w=this.current;(f.r!==w.r||f.g!==w.g||f.b!==w.b||f.a!==w.a||this.dirty)&&(this.gl.clearColor(f.r,f.g,f.b,f.a),this.current=f,this.dirty=!1)}}class m7 extends vo{getDefault(){return 1}set(f){(f!==this.current||this.dirty)&&(this.gl.clearDepth(f),this.current=f,this.dirty=!1)}}class sw extends vo{getDefault(){return 0}set(f){(f!==this.current||this.dirty)&&(this.gl.clearStencil(f),this.current=f,this.dirty=!1)}}class vye extends vo{getDefault(){return[!0,!0,!0,!0]}set(f){const w=this.current;(f[0]!==w[0]||f[1]!==w[1]||f[2]!==w[2]||f[3]!==w[3]||this.dirty)&&(this.gl.colorMask(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class bye extends vo{getDefault(){return!0}set(f){(f!==this.current||this.dirty)&&(this.gl.depthMask(f),this.current=f,this.dirty=!1)}}class _ye extends vo{getDefault(){return 255}set(f){(f!==this.current||this.dirty)&&(this.gl.stencilMask(f),this.current=f,this.dirty=!1)}}class wye extends vo{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(f){const w=this.current;(f.func!==w.func||f.ref!==w.ref||f.mask!==w.mask||this.dirty)&&(this.gl.stencilFunc(f.func,f.ref,f.mask),this.current=f,this.dirty=!1)}}class jye extends vo{getDefault(){const f=this.gl;return[f.KEEP,f.KEEP,f.KEEP]}set(f){const w=this.current;(f[0]!==w[0]||f[1]!==w[1]||f[2]!==w[2]||this.dirty)&&(this.gl.stencilOp(f[0],f[1],f[2]),this.current=f,this.dirty=!1)}}class Nye extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;f?w.enable(w.STENCIL_TEST):w.disable(w.STENCIL_TEST),this.current=f,this.dirty=!1}}class BL extends vo{getDefault(){return[0,1]}set(f){const w=this.current;(f[0]!==w[0]||f[1]!==w[1]||this.dirty)&&(this.gl.depthRange(f[0],f[1]),this.current=f,this.dirty=!1)}}class zL extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;f?w.enable(w.DEPTH_TEST):w.disable(w.DEPTH_TEST),this.current=f,this.dirty=!1}}class $L extends vo{getDefault(){return this.gl.LESS}set(f){(f!==this.current||this.dirty)&&(this.gl.depthFunc(f),this.current=f,this.dirty=!1)}}class rw extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;f?w.enable(w.BLEND):w.disable(w.BLEND),this.current=f,this.dirty=!1}}class f7 extends vo{getDefault(){const f=this.gl;return[f.ONE,f.ZERO,f.ONE,f.ZERO]}set(f){const w=this.current;(f[0]!==w[0]||f[1]!==w[1]||f[2]!==w[2]||f[3]!==w[3]||this.dirty)&&(this.gl.blendFuncSeparate(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class p7 extends vo{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(f){const w=this.current;(f.r!==w.r||f.g!==w.g||f.b!==w.b||f.a!==w.a||this.dirty)&&(this.gl.blendColor(f.r,f.g,f.b,f.a),this.current=f,this.dirty=!1)}}class x7 extends vo{getDefault(){return this.gl.FUNC_ADD}set(f){(f!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(f,f),this.current=f,this.dirty=!1)}}class UL extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;f?w.enable(w.CULL_FACE):w.disable(w.CULL_FACE),this.current=f,this.dirty=!1}}class I0 extends vo{getDefault(){return this.gl.BACK}set(f){(f!==this.current||this.dirty)&&(this.gl.cullFace(f),this.current=f,this.dirty=!1)}}class ET extends vo{getDefault(){return this.gl.CCW}set(f){(f!==this.current||this.dirty)&&(this.gl.frontFace(f),this.current=f,this.dirty=!1)}}let AT=class extends vo{getDefault(){return null}set(E){(E!==this.current||this.dirty)&&(this.gl.useProgram(E),this.current=E,this.dirty=!1)}};class g7 extends vo{getDefault(){return this.gl.TEXTURE0}set(f){(f!==this.current||this.dirty)&&(this.gl.activeTexture(f),this.current=f,this.dirty=!1)}}class P0 extends vo{getDefault(){const f=this.gl;return[0,0,f.drawingBufferWidth,f.drawingBufferHeight]}set(f){const w=this.current;(f[0]!==w[0]||f[1]!==w[1]||f[2]!==w[2]||f[3]!==w[3]||this.dirty)&&(this.gl.viewport(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class qL extends vo{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.bindFramebuffer(w.FRAMEBUFFER,f),this.current=f,this.dirty=!1}}class MT extends vo{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.bindRenderbuffer(w.RENDERBUFFER,f),this.current=f,this.dirty=!1}}class y7 extends vo{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.bindTexture(w.TEXTURE_2D,f),this.current=f,this.dirty=!1}}class v7 extends vo{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.bindBuffer(w.ARRAY_BUFFER,f),this.current=f,this.dirty=!1}}class VL extends vo{getDefault(){return null}set(f){const w=this.gl;w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,f),this.current=f,this.dirty=!1}}class HL extends vo{getDefault(){return null}set(f){this.gl&&(f!==this.current||this.dirty)&&(this.gl.bindVertexArray(f),this.current=f,this.dirty=!1)}}class kye extends vo{getDefault(){return 4}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.pixelStorei(w.UNPACK_ALIGNMENT,f),this.current=f,this.dirty=!1}}class b7 extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.pixelStorei(w.UNPACK_PREMULTIPLY_ALPHA_WEBGL,f),this.current=f,this.dirty=!1}}class AN extends vo{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const w=this.gl;w.pixelStorei(w.UNPACK_FLIP_Y_WEBGL,f),this.current=f,this.dirty=!1}}class GL extends vo{constructor(f,w){super(f),this.context=f,this.parent=w}getDefault(){return null}}class IT extends GL{constructor(f,w,I=0){super(f,w),this.attachmentPoint=f.gl.COLOR_ATTACHMENT0+I}setDirty(){this.dirty=!0}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const w=this.gl;w.framebufferTexture2D(w.FRAMEBUFFER,this.attachmentPoint,w.TEXTURE_2D,f,0),this.current=f,this.dirty=!1}}class WL extends GL{attachment(){return this.gl.DEPTH_ATTACHMENT}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const w=this.gl;w.framebufferRenderbuffer(w.FRAMEBUFFER,this.attachment(),w.RENDERBUFFER,f),this.current=f,this.dirty=!1}}class Sye extends GL{attachment(){return this.gl.DEPTH_ATTACHMENT}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const w=this.gl;w.framebufferTexture2D(w.FRAMEBUFFER,this.attachment(),w.TEXTURE_2D,f,0),this.current=f,this.dirty=!1}}class KL extends WL{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const PT=(E,f,w,I)=>({u_matrix:E,u_image0:0,u_image1:1,u_skirt_height:f,u_ground_shadow_factor:w,u_emissive_texture_available:I}),L0=(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze)=>({u_proj_matrix:Float32Array.from(E),u_globe_matrix:f,u_normalize_matrix:Float32Array.from(I),u_merc_matrix:w,u_zoom_transition:R,u_merc_center:q,u_image0:0,u_image1:1,u_frustum_tl:V,u_frustum_tr:Z,u_frustum_br:te,u_frustum_bl:le,u_globe_pos:pe,u_globe_radius:Ae,u_viewport:_e,u_grid_matrix:Ze?Float32Array.from(Ze):new Float32Array(9),u_skirt_height:Le,u_far_z_cutoff:Ve,u_emissive_texture_available:qe});function MN(E,f){return E!=null&&f!=null&&!(!E.hasData()||!f.hasData())&&E.demTexture!=null&&f.demTexture!=null&&E.tileID.key!==f.tileID.key}const eg=new class{constructor(){this.operations={}}newMorphing(E,f,w,I,R){if(E in this.operations){const q=this.operations[E];q.to.tileID.key!==w.tileID.key&&(q.queued=w)}else this.operations[E]={startTime:I,phase:0,duration:R,from:f,to:w,queued:null}}getMorphValuesForProxy(E){if(!(E in this.operations))return null;const f=this.operations[E];return{from:f.from,to:f.to,phase:f.phase}}update(E){for(const f in this.operations){const w=this.operations[f];for(w.phase=(E-w.startTime)/w.duration;w.phase>=1||!this._validOp(w);)if(!this._nextOp(w,E)){delete this.operations[f];break}}}_nextOp(E,f){return!!E.queued&&(E.from=E.to,E.to=E.queued,E.queued=null,E.phase=0,E.startTime=f,!0)}_validOp(E){return E.from.hasData()&&E.to.hasData()}};function YL(E,f,w){if(f===0)return 0;const I=f<1&&w===514?.25/f:1;return 6*Math.pow(1.5,22-E)*Math.max(f,1)*I}function LT(E,f){const w=1<({u_matrix:E});function aw(E,f,w,I,R){if(R>0){const q=o.o.now(),V=(q-E.timeAdded)/R,Z=f?(q-f.timeAdded)/R:-1,te=w.getSource(),le=I.coveringZoomLevel({tileSize:te.tileSize,roundZoom:te.roundZoom}),pe=!f||Math.abs(f.tileID.overscaledZ-le)>Math.abs(E.tileID.overscaledZ-le),Ae=pe&&E.refreshedUponExpiration?1:o.aB(pe?V:1-Z,0,1);return f?{opacity:1,mix:1-Ae,isFading:V<1}:{opacity:Ae,mix:0,isFading:V<1}}return{opacity:1,mix:0,isFading:!1}}class Mr extends $a{constructor(f){const w={type:"raster-dem",maxzoom:Math.ceil(f.transform.maxZoom)},I=U_("mock-dem",w,f.style.dispatcher,f.style);super("mock-dem",I,null),I.setEventedParent(this),this._sourceLoaded=!0}_loadTile(f,w){f.state="loaded",w(null)}}class _7 extends $a{constructor(f){const w=U_("proxy",{type:"geojson",maxzoom:Math.ceil(f.transform.maxZoom)},f.style.dispatcher,f.style);super("proxy",w,null),w.setEventedParent(this),this.map=this.getSource().map=f,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(f,w,I){if(f.freezeTileCoverage)return;this.transform=f;const R=f.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((q,V)=>{if(q[V.key]="",!this._tiles[V.key]){const Z=new o.b3(V,this._source.tileSize*V.overscaleFactor(),f.tileZoom,void 0,void 0,this._source.worldview);Z.state="loaded",this._tiles[V.key]=Z}return q},{});for(const q in this._tiles)q in R||(this.freeFBO(q),this._tiles[q].unloadVectorData(),delete this._tiles[q])}freeFBO(f){const w=this.proxyCachedFBO[f];if(w!==void 0){const I=Object.values(w);this.renderCachePool.push(...I),delete this.proxyCachedFBO[f]}}deallocRenderCache(){this.renderCache.forEach(f=>f.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class my extends o.aU{constructor(f,w,I){super(f.overscaledZ,f.wrap,f.canonical.z,f.canonical.x,f.canonical.y),this.proxyTileKey=w,this.projMatrix=I}}class fy extends o.bx{constructor(f,w){super(),this.painter=f,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[I,R,q]=function(){const te=new o.dE,le=new o.dF,pe=131;te.reserve(17161),le.reserve(33800);const Ae=o.ak/128,_e=o.ak+Ae/2,Le=_e+Ae;for(let qe=-Ae;qe_e||qe<0||qe>_e?24575:0,ht=o.aB(Math.round(Ze),0,o.ak),vt=o.aB(Math.round(qe),0,o.ak);te.emplaceBack(ht+Xe,vt)}const Ve=(qe,Ze)=>{const Xe=Ze*pe+qe;le.emplaceBack(Xe+1,Xe,Xe+pe),le.emplaceBack(Xe+pe,Xe+pe+1,Xe+1)};for(let qe=1;qe<129;qe++)for(let Ze=1;Ze<129;Ze++)Ve(Ze,qe);return[0,129].forEach(qe=>{for(let Ze=0;Ze<130;Ze++)Ve(Ze,qe),Ve(qe,Ze)}),[te,le,32768]}(),V=f.context;this.gridBuffer=V.createVertexBuffer(I,o.dA.members),this.gridIndexBuffer=V.createIndexBuffer(R),this.gridSegments=o.dB.simpleSegment(0,0,I.length,R.length),this.gridNoSkirtSegments=o.dB.simpleSegment(0,0,I.length,q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new _7(w.map),this.orthoMatrix=o.bd(),o.bX(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.ak,0,o.ak,0,1);const Z=V.gl;this._overlapStencilMode=new kn({func:Z.GEQUAL,mask:255},0,255,Z.KEEP,Z.KEEP,Z.REPLACE),this._previousZoom=f.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=w,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Mr(w.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1,this._devtoolsFolder=null}set style(f){f.on("data",this._onStyleDataEvent.bind(this)),this._style=f,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(f,w,I){if(f&&f.terrain){this._style!==f&&(this.style=f,this._evaluationZoom=void 0);const R=f.terrain.properties,q=f.terrain.drapeRenderMode===0,V=f.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const Z=f.terrain&&f.terrain.scope,te=R.get("source"),le=q?this._mockSourceCache:f.getSourceCache(te,Z);if(!le)return void o.w(`Couldn't find terrain source "${te}".`);if(this.sourceCache=le,this._attenuationRange=f.terrain.getAttenuationRange(),this._exaggeration=V?this.calculateExaggeration(w):R.get("exaggeration"),!w.projection.requiresDraping&&V&&this._exaggeration===0)return void this._disable();this.enabled=!0;const pe=()=>{this.sourceCache.used&&o.w(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source. This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);const Ae=this.getScaledDemTileSize();this.sourceCache.update(w,Ae,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,pe(),this._initializing=!0),pe(),w.updateElevation(!0,I),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(w),this._emptyDEMTextureDirty=!0,this._previousZoom=w.zoom}else this._disable()}calculateExaggeration(f){if(this._attenuationRange&&f.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(f.zoom);const w=this._previousCameraAltitude,I=f.getFreeCameraOptions().position.z/f.pixelsPerMeter*f.worldSize;this._previousCameraAltitude=I;const R=w!=null?I-w:Number.MAX_VALUE;if(Math.abs(R)<2)return this._exaggeration;const q=f.zoom,V=this._style.terrain;if(!this._previousUpdateTimestamp)return V.getExaggeration(q);let Z=q-this._previousZoom;const te=this._previousUpdateTimestamp;let le=q;this._evaluationZoom!=null&&(le=this._evaluationZoom,Math.abs(q-le)>.5&&(Z=.5*(q-le+Z)),Z*R<0&&(le+=Z)),this._evaluationZoom=le;const pe=V.getExaggeration(le),Ae=pe===V.getExaggeration(Math.max(0,le-.1));if(Ae&&Math.abs(pe-this._exaggeration)<.01)return pe;let _e=Math.min(.1,.00375*(this._updateTimestamp-te));return(Ae||pe<.1||Math.abs(Z)<1e-4)&&(_e=Math.min(.2,4*_e)),o.aj(this._exaggeration,pe,_e)}resetTileLookupCache(f){this._findCoveringTileCache[f]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(f){f.dataType==="source"&&f.coord?this._clearRenderCacheForTile(f.sourceCacheId,f.coord):f.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 f in this._style._mergedSourceCaches)this._style._mergedSourceCaches[f].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(f=>f.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 f=2*this.proxySourceCache.getSource().tileSize;return[f,f]}set useVertexMorphing(f){this._useVertexMorphing=f}updateTileBinding(f){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const w=this.proxySourceCache,I=this.painter.transform;this._initializing&&(this._initializing=I._centerAltitude===0&&this.getAtPointOrZero(o.ad.fromLngLat(I.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const R=this.proxyCoords=w.getIds().map(te=>{const le=w.getTileByID(te).tileID;return le.projMatrix=I.calculateProjMatrix(le.toUnwrapped()),le});(function(te,le){const pe=le.transform.pointCoordinate(le.transform.getCameraPoint()),Ae=new o.P(pe.x,pe.y);te.sort((_e,Le)=>{if(Le.overscaledZ-_e.overscaledZ)return Le.overscaledZ-_e.overscaledZ;const Ve=new o.P(_e.canonical.x+(1<<_e.canonical.z)*_e.wrap,_e.canonical.y),qe=new o.P(Le.canonical.x+(1<{this.proxyToSource[te.key]={}}),this.terrainTileForTile={};const V=this._style._mergedSourceCaches;for(const te in V){const le=V[te];if(!le.used||(le!==this.sourceCache&&this.resetTileLookupCache(le.id),this._setupProxiedCoordsForOrtho(le,f[te],q),le.usedForTerrain))continue;const pe=f[te];(le.getSource().reparseOverscaled||le._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(pe)}this.proxiedCoords[w.id]=R.map(te=>new my(te,te.key,this.orthoMatrix)),this._assignTerrainTiles(R),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(q),this.renderingToTexture=!1;const Z={};this._visibleDemTiles=[];for(const te of this.proxyCoords){const le=this.terrainTileForTile[te.key];if(!le)continue;const pe=le.tileID.key;pe in Z||(this._visibleDemTiles.push(le),Z[pe]=pe)}}_assignTerrainTiles(f){this._initializing||f.forEach(w=>{if(this.terrainTileForTile[w.key])return;const I=this._findTileCoveringTileID(w,this.sourceCache);I&&(this.terrainTileForTile[w.key]=I)})}_prepareDEMTextures(){const f=this.painter.context,w=f.gl;for(const I in this.terrainTileForTile){const R=this.terrainTileForTile[I],q=R.dem;!q||R.demTexture&&!R.needsDEMTextureUpload||(f.activeTexture.set(w.TEXTURE1),CT(this.painter,R,q))}}_prepareDemTileUniforms(f,w,I,R){if(!w||w.demTexture==null)return!1;const q=f.tileID.canonical,V=Math.pow(2,w.tileID.canonical.z-q.z),Z=R||"";return I[`u_dem_tl${Z}`]=[q.x*V%1,q.y*V%1],I[`u_dem_scale${Z}`]=V,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let f=0;const w=this._visibleDemTiles.reduce((I,R)=>{if(!R.dem)return I;const q=R.dem.tree.minimums[0];return q>0&&f++,I+q},0);return f?w/f:0}_updateEmptyDEMTexture(){const f=this.painter.context,w=f.gl;f.activeTexture.set(w.TEXTURE2);const I=this._getLoadedAreaMinimum(),R=new o.dC({width:1,height:1},new Float32Array([I]));this._emptyDEMTextureDirty=!1;let q=this._emptyDEMTexture;return q?q.update(R,{premultiply:!1}):q=this._emptyDEMTexture=new o.T(f,R,w.R32F,{premultiply:!1}),q}setupElevationDraw(f,w,I){const R=this.painter.context,q=R.gl,V={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};V.u_exaggeration=this.exaggeration();let Z=null,te=null,le=1;if(I&&I.morphing&&this._useVertexMorphing){const Le=I.morphing.srcDemTile,Ve=I.morphing.dstDemTile;le=I.morphing.phase,Le&&Ve&&(this._prepareDemTileUniforms(f,Le,V,"_prev")&&(te=Le),this._prepareDemTileUniforms(f,Ve,V)&&(Z=Ve))}const pe=Le=>Le&&Le.demTexture&&this.painter.linearFloatFilteringSupported()?q.LINEAR:q.NEAREST;let Ae=null;var _e;if(this.enabled?te&&Z?(Ae=Z.demTexture,R.activeTexture.set(q.TEXTURE4),te.demTexture.bind(pe(te),q.CLAMP_TO_EDGE),V.u_dem_lerp=le):(Z=this.terrainTileForTile[f.tileID.key],Ae=this._prepareDemTileUniforms(f,Z,V)?Z.demTexture:this.emptyDEMTexture):Ae=this.emptyDEMTexture,R.activeTexture.set(q.TEXTURE2),Ae&&(V.u_dem_size=(_e=Ae).size[0]===1?1:_e.size[0]-2,Ae.bind(pe(Z),q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(I&&I.useDepthForOcclusion,w,V),I&&I.useMeterToDem&&Z){const Le=(1<{if(Xe===ms)return;const Zs=[];ms===1&&Zs.push("TERRAIN_VERTEX_MORPHING"),Zs.push("PROJECTION_GLOBE_VIEW"),vt&&Zs.push("CUSTOM_ANTIALIASING");const ts=le.isTileAffectedByFog(hs);Ze=le.getOrCreateProgram("globeRaster",{defines:Zs,overrideFog:ts}),Xe=ms},Ut=le.colorModeForRenderPass(),Pt=new Br(qe.LEQUAL,Br.ReadWrite,le.depthRangeFor3D);eg.update(Le);const Vt=o.dt(ht),St=[o.aG(ht.center.lng),o.aJ(ht.center.lat)],Ct=le.globeSharedBuffers,qt=[ht.width*o.o.devicePixelRatio,ht.height*o.o.devicePixelRatio],Zt=Float32Array.from(ht.globeMatrix),Wt={useDenormalizedUpVectorScale:!0};{const hs=le.transform,ms=YL(hs.zoom,pe.exaggeration(),pe.sourceCache._source.tileSize);Xe=-1;const Zs=qe.TRIANGLES;for(const ts of _e){const Ns=Ae.getTile(ts),rs=kn.disabled,Ps=pe.prevTerrainTileForTile[ts.key],Ms=pe.terrainTileForTile[ts.key];MN(Ps,Ms)&&eg.newMorphing(ts.key,Ps,Ms,Le,250),nw(le,Ns.emissiveTexture),Ve.activeTexture.set(qe.TEXTURE0),Ns.texture&&Ns.texture.bind(qe.LINEAR,qe.CLAMP_TO_EDGE);const Rs=eg.getMorphValuesForProxy(ts.key),xr=Rs?1:0;Rs&&Object.assign(Wt,{morphing:{srcDemTile:Rs.from,dstDemTile:Rs.to,phase:o.dr(Rs.phase)}});const or=o.du(ts.canonical),Js=o.dv(or.getCenter().lat),Ys=o.dw(ts.canonical,or,Js,hs.worldSize/hs._pixelsPerMercatorPixel),Wr=o.dx(o.dy(ts.canonical)),Vr=le.emissiveMode==="mrt-fallback"?1:0,Ir=L0(hs.expandedFarZProjMatrix,Zt,Vt,Wr,o.ai(hs.zoom),St,hs.frustumCorners.TL,hs.frustumCorners.TR,hs.frustumCorners.BR,hs.frustumCorners.BL,hs.globeCenterInViewSpace,hs.globeRadius,qt,ms,hs._farZ,Vr,Ys);if(st(ts,xr),Ze&&(pe.setupElevationDraw(Ns,Ze,Wt),le.uploadCommonUniforms(Ve,Ze,ts.toUnwrapped()),Ct)){const[Rr,mn,Ln]=Ct.getGridBuffers(Js,ms!==0);Ze.draw(le,Zs,Pt,rs,Ut,en.backCCW,Ir,"globe_raster",Rr,mn,Ln)}}}if(Ct&&(le.renderDefaultNorthPole||le.renderDefaultSouthPole)){const hs=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];vt&&hs.push("CUSTOM_ANTIALIASING"),Ze=le.getOrCreateProgram("globeRaster",{defines:hs});for(const ms of _e){const{x:Zs,y:ts,z:Ns}=ms.canonical,rs=ts===0,Ps=ts===(1<Rr.draw(le,qe.TRIANGLES,Pt,kn.disabled,Ut,en.disabled,L0(ht.expandedFarZProjMatrix,Ys,Ys,Wr,0,St,ht.frustumCorners.TL,ht.frustumCorners.TR,ht.frustumCorners.BR,ht.frustumCorners.BL,ht.globeCenterInViewSpace,ht.globeRadius,qt,0,ht._farZ,Vr),"globe_pole_raster",mn,xr,or);pe.setupElevationDraw(Js,Ze,Wt),le.uploadCommonUniforms(Ve,Ze,ms.toUnwrapped()),rs&&le.renderDefaultNorthPole&&Ir(Ze,Ms),Ps&&le.renderDefaultSouthPole&&(Ys=o.cE(o.bd(),Ys,[1,-1,1]),Ir(Ze,Rs))}}}})(R,q,V,Z,te);else{const le=R.context,pe=le.gl;let Ae,_e;const Le=R.shadowRenderer,Ve=Ym(R,R.longestCutoffRange),qe=Ut=>{if(_e===Ut)return;const Pt=[];Ut===1&&Pt.push("TERRAIN_VERTEX_MORPHING"),Ve.shouldRenderCutoff&&Pt.push("RENDER_CUTOFF"),Le&&(Pt.push("RENDER_SHADOWS"),Le.useNormalOffset&&Pt.push("NORMAL_OFFSET")),Ae=R.getOrCreateProgram("terrainRaster",{defines:Pt}),_e=Ut},Ze=R.colorModeForRenderPass(),Xe=new Br(pe.LEQUAL,Br.ReadWrite,R.depthRangeFor3D);eg.update(te);const ht=R.transform,vt=YL(ht.zoom,q.exaggeration(),q.sourceCache._source.tileSize);let st=[0,0,0];if(Le){const Ut=R.style.directionalLight,Pt=R.style.ambientLight;Ut&&Pt&&(st=$1(R.style,Ut,Pt))}{_e=-1;const Ut=pe.TRIANGLES,[Pt,Vt]=[q.gridIndexBuffer,q.gridSegments];for(const St of Z){const Ct=V.getTile(St),qt=kn.disabled,Zt=q.prevTerrainTileForTile[St.key],Wt=q.terrainTileForTile[St.key];MN(Zt,Wt)&&eg.newMorphing(St.key,Zt,Wt,te,250),nw(R,Ct.emissiveTexture),le.activeTexture.set(pe.TEXTURE0),Ct.texture&&Ct.texture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE);const hs=eg.getMorphValuesForProxy(St.key),ms=hs?1:0;let Zs;hs&&(Zs={morphing:{srcDemTile:hs.from,dstDemTile:hs.to,phase:o.dr(hs.phase)}});const ts=R.emissiveMode==="mrt-fallback"?1:0,Ns=PT(St.projMatrix,LT(St.canonical,ht.renderWorldCopies)?vt/10:vt,st,ts);if(qe(ms),!Ae)continue;q.setupElevationDraw(Ct,Ae,Zs);const rs=St.toUnwrapped();Le&&Le.setupShadows(rs,Ae),R.uploadCommonUniforms(le,Ae,rs,null,Ve),Ae.draw(R,Ut,Xe,qt,Ze,en.backCCW,Ns,"terrain_raster",q.gridBuffer,Pt,Vt)}}}}(w,this,this.proxySourceCache,f,this._updateTimestamp),this.renderingToTexture=!0,w.gpuTimingDeferredRenderEnd(),f.splice(0,f.length))}renderBatch(f){if(this._drapedRenderBatches.length===0)return f+1;this.renderingToTexture=!0;const w=this.painter,I=this.painter.context,R=this.proxySourceCache,q=this.proxiedCoords[R.id],V=this._drapedRenderBatches.shift(),Z=w.style.order,te=[];this._updateFBOs(w.emissiveMode==="mrt-fallback");let le=0;for(const pe of q){const Ae=R.getTileByID(pe.proxyTileKey),_e=R.proxyCachedFBO[pe.key]?R.proxyCachedFBO[pe.key][f]:void 0,Le=_e!==void 0?R.renderCache[_e]:this.pool[le++],Ve=_e!==void 0;if(Ae.texture=Le.tex,Ae.emissiveTexture=Le.emissiveTex,Ve&&!Le.dirty){te.push(Ae.tileID);continue}I.bindFramebuffer.set(Le.fb.framebuffer);const qe=I.gl;let Ze;qe.drawBuffers(w.emissiveMode==="mrt-fallback"?[qe.COLOR_ATTACHMENT0,qe.COLOR_ATTACHMENT1]:[qe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Le.dirty&&(I.clear({color:o.C.transparent,stencil:0}),Le.dirty=!1);for(let Xe=V.start;Xe<=V.end;++Xe){const ht=w.style._mergedLayers[Z[Xe]];if(ht.isHidden(w.transform.zoom))continue;const vt=w.style.getLayerSourceCache(ht),st=vt?this.proxyToSource[pe.key][vt.id]:[pe];if(!st)continue;const Ut=st;I.viewport.set([0,0,Le.fb.width,Le.fb.height]),Ze!==(vt?vt.id:null)&&(this._setupStencil(Le,st,ht,vt),Ze=vt?vt.id:null),w.renderLayer(w,vt,ht,Ut)}if(qe.drawBuffers([qe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const Xe of this._pendingGroundEffectLayers){const ht=w.style._mergedLayers[Z[Xe]];if(ht.isHidden(w.transform.zoom))continue;const vt=w.style.getLayerSourceCache(ht),st=vt?this.proxyToSource[pe.key][vt.id]:[pe];if(!st)continue;const Ut=st;I.viewport.set([0,0,Le.fb.width,Le.fb.height]),Ze!==(vt?vt.id:null)&&(this._setupStencil(Le,st,ht,vt),Ze=vt?vt.id:null),w.renderLayer(w,vt,ht,Ut)}this.renderedToTile?(Le.dirty=!0,te.push(Ae.tileID)):Ve||--le,le===5&&(le=0,this.renderToBackBuffer(te))}return this.renderToBackBuffer(te),this.renderingToTexture=!1,I.bindFramebuffer.set(null),I.viewport.set([0,0,w.width,w.height]),V.end+1}postRender(){}isLayerOrderingCorrect(f){const w=f.order.length;let I=-1,R=w;for(let q=0;qI}getMinElevationBelowMSL(){let f=0;return this._visibleDemTiles.filter(w=>w.dem).forEach(w=>{f=Math.min(f,w.dem.tree.minimums[0])}),f===0?f:(f-30)*this._exaggeration}raycast(f,w,I){if(!this._visibleDemTiles)return null;const R=this._visibleDemTiles.filter(q=>q.dem).map(q=>{const V=q.tileID,Z=1<(q.t!==null?q.t:Number.MAX_VALUE)-(V.t!==null?V.t:Number.MAX_VALUE));for(const q of R){if(q.t==null)return null;const V=q.tile.dem.tree.raycast(q.minx,q.miny,q.maxx,q.maxy,f,w,I);if(V!=null)return V}return null}_createFBO(){const f=this.painter.context,w=f.gl,I=this.drapeBufferSize;f.activeTexture.set(w.TEXTURE0);const R=new o.T(f,{width:I[0],height:I[1],data:null},w.RGBA8);R.bind(w.LINEAR,w.CLAMP_TO_EDGE);const q=f.createFramebuffer(I[0],I[1],1,null);let V;return q.colorAttachment0.set(R.texture),this._emissiveTexture&&(V=new o.T(f,{width:I[0],height:I[1],data:null},w.R8),V.bind(w.LINEAR,w.CLAMP_TO_EDGE),q.createColorAttachment(f,1),q.colorAttachment1.set(V.texture)),q.depthAttachment=new KL(f,q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=f.createRenderbuffer(f.gl.DEPTH_STENCIL,I[0],I[1]),this._stencilRef=0,q.depthAttachment.set(this._sharedDepthStencil),f.clear({stencil:0})):q.depthAttachment.set(this._sharedDepthStencil),f.extTextureFilterAnisotropic&&w.texParameterf(w.TEXTURE_2D,f.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,f.extTextureFilterAnisotropicMax),{fb:q,tex:R,emissiveTex:V,dirty:!1}}_updateFBOs(f){if(this._emissiveTexture!==f){for(const w of this.pool)this._updateFBO(w,f);for(const w of this.proxySourceCache.renderCache)this._updateFBO(w,f);this._emissiveTexture=f}}_updateFBO(f,w){const I=f.fb,R=this.painter.context,q=R.gl,V=this.drapeBufferSize;if(w){const Z=new o.T(R,{width:V[0],height:V[1],data:null},q.R8);Z.bind(q.LINEAR,q.CLAMP_TO_EDGE),f.emissiveTex=Z,I.createColorAttachment(R,1),I.colorAttachment1.set(Z.texture)}else f.emissiveTex=void 0,I.removeColorAttachment(R,1);f.dirty=!0}_initFBOPool(){for(;this.pool.length{const w=this._style._mergedLayers[f],I=w.isHidden(this.painter.transform.zoom);return w.type==="hillshade"||w.type==="custom"?!I&&w.shouldRedrape():!I&&w.hasTransition()})}_clearLineLayersFromRenderCache(){let f=!1;for(const I of this._style.getSources())if(I instanceof yi){f=!0;break}if(!f)return;const w={};for(let I=0;Ite>Z.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=I}_setupRenderCache(f){const w=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,w.renderCache.length>w.renderCachePool.length){const V=Object.values(w.proxyCachedFBO);w.proxyCachedFBO={};for(let Z=0;Z=0;V--){const Z=I[V];if(w.getTileByID(Z.key),w.proxyCachedFBO[Z.key]!==void 0){const te=f[Z.key],le=this.proxyToSource[Z.key];let pe=0;for(const Ae in le){const _e=le[Ae],Le=te[Ae];if(!Le||Le.length!==_e.length||_e.some((Ve,qe)=>Ve!==Le[qe]||R[Ae]&&Object.hasOwn(R[Ae],Ve.key))){pe=-1;break}++pe}for(const Ae in w.proxyCachedFBO[Z.key])w.renderCache[w.proxyCachedFBO[Z.key][Ae]].dirty=pe<0||pe!==Object.values(te).length}}const q=[...this._drapedRenderBatches];q.sort((V,Z)=>Z.end-Z.start-(V.end-V.start));for(const V of q)for(const Z of I){if(w.proxyCachedFBO[Z.key])continue;let te=w.renderCachePool.pop();te===void 0&&w.renderCache.length<50&&(te=w.renderCache.length,w.renderCache.push(this._createFBO())),te!==void 0&&(w.proxyCachedFBO[Z.key]={},w.proxyCachedFBO[Z.key][V.start]=te,w.renderCache[te].dirty=!0)}this._tilesDirty={}}_setupStencil(f,w,I,R){if(!R||!this._sourceTilesOverlap[R.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const q=this.painter.context,V=q.gl;if(w.length<=1)return void(this._overlapStencilType=!1);let Z;if(I.isTileClipped())Z=w.length,this._overlapStencilMode.test={func:V.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(w[0].overscaledZ>w.at(-1).overscaledZ))return void(this._overlapStencilType=!1);Z=1,this._overlapStencilMode.test={func:V.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+Z>255&&(q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=Z,this._overlapStencilMode.ref=this._stencilRef,I.isTileClipped()&&this._renderTileClippingMasks(w,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(f){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[f.key]),this._overlapStencilMode):kn.disabled}_renderTileClippingMasks(f,w){const I=this.painter,R=this.painter.context,q=R.gl;I._tileClippingMaskIDs={},R.setColorMode(En.disabled),R.setDepthMode(Br.disabled);const V=I.getOrCreateProgram("clippingMask");for(const Z of f){const te=I._tileClippingMaskIDs[Z.key]=--w;V.draw(I,q.TRIANGLES,Br.disabled,new kn({func:q.ALWAYS,mask:0},te,255,q.KEEP,q.KEEP,q.REPLACE),En.disabled,en.disabled,G1(Z.projMatrix),"$clipping",I.tileExtentBuffer,I.quadTriangleIndexBuffer,I.tileExtentSegments)}}pointCoordinate(f){const w=this.painter.transform;if(f.x<0||f.x>w.width||f.y<0||f.y>w.height)return null;const I=[f.x,f.y,1,1];o.aD(I,I,w.pixelMatrixInverse),o.cw(I,I,1/I[3]),I[0]/=w.worldSize,I[1]/=w.worldSize;const R=w._camera.position,q=o.bY(1,w.center.lat),V=[R[0],R[1],R[2]/q,0],Z=o.cZ([],I.slice(0,3),V);o.ax(Z,Z);const te=this.raycast(V,Z,this._exaggeration);return te!==null&&te?(o.bi(V,V,Z,te),V[3]=V[2],V[2]*=q,V):null}_setupProxiedCoordsForOrtho(f,w,I){if(f.getSource()instanceof o.aY)return this._setupProxiedCoordsForImageSource(f,w,I);this._findCoveringTileCache[f.id]=this._findCoveringTileCache[f.id]||{};const R=this.proxiedCoords[f.id]=[],q=this.proxyCoords;for(let te=0;tepe.overscaledZ-le.overscaledZ)}_setupProxiedCoordsForImageSource(f,w,I){if(!f.getSource().loaded())return;const R=this.proxiedCoords[f.id]=[],q=this.proxyCoords,V=f.getSource(),Z=V.tileID;if(!Z)return;const te=new o.P(Z.x,Z.y)._div(1<(Ae.min.x=Math.min(Ae.min.x,_e.x-te.x),Ae.min.y=Math.min(Ae.min.y,_e.y-te.y),Ae.max.x=Math.max(Ae.max.x,_e.x-te.x),Ae.max.y=Math.max(Ae.max.y,_e.y-te.y),Ae),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),pe=(Ae,_e)=>{const Le=Ae.wrap+Ae.canonical.x/(1<Ze+le.max.x||Ve+qeXe+le.max.y};for(let Ae=0;AeV.key===w.tileID.key);if(q)return q}if(w.tileID.key!==f.key){const q=f.canonical.z-w.tileID.canonical.z;let V,Z,te;R=o.bd();const le=w.tileID.wrap-f.wrap<0?(V=o.ak>>q,Z=V*((w.tileID.canonical.x<=Ae){const _e=f.canonical.z-Ae;w.getSource().reparseOverscaled?(Z=Math.max(f.canonical.z+2,w.transform.tileZoom),V=new o.aU(Z,f.wrap,Ae,f.canonical.x>>_e,f.canonical.y>>_e)):_e!==0&&(Z=Ae,V=new o.aU(Z,f.wrap,Ae,f.canonical.x>>_e,f.canonical.y>>_e))}V.key!==f.key&&(le.push(V.key),I=w.getTile(V))}const pe=Ae=>{le.forEach(_e=>{R[_e]=Ae}),le.length=0};for(Z-=1;Z>=te&&(!I||!I.hasData());Z--){I&&pe(I.tileID.key);const Ae=V.calculateScaledKey(Z);if(I=w.getTileByID(Ae),I&&I.hasData())break;const _e=R[Ae];if(_e===null)break;_e===void 0?le.push(Ae):I=w.getTileByID(_e)}return pe(I?I.tileID.key:null),I&&I.hasData()?I:null}findDEMTileFor(f){return this.enabled?this._findTileCoveringTileID(f,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(f,w){let I=this._tilesDirty[f];I||(I=this._tilesDirty[f]={}),I[w.key]=!0}}function w7(E,f,w){const I=function(Z,te,le){const pe=o.bk(te,Z),Ae=o.bk(le,[.2126,.7152,.0722]),_e=(Ve,qe,Ze)=>(1-Ze)*Ve+Ze*qe,Le=_e(1-.3*Math.min(Ae,1),1,Math.min(pe+1,1));return _e(.92,1,Math.asin(o.aB(te[2],-1,1))/Math.PI+.5)*Le}(E,[0,0,1],f),R=[0,0,0];o.bN(R,w.slice(0,3),I);const q=[0,0,0];o.bN(q,f.slice(0,3),E[2]);const V=[0,0,0];return o.cX(V,R,q),o.c_(V)}const j7=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],N7=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class ZL{static cacheKey(f,w,I,R){const q=[w];R&&q.push(R.cacheKey);for(const V of I)(typeof V=="string"&&V.includes(" ")||f.usedDefines.has(V))&&q.push(V);return q.join("/")}constructor(f,w,I,R,q,V,Z=!1){const te=f.gl;this.program=te.createProgram(),this._context=f,this._fixedUniformsFn=q,this._pending=!0,this._precompiled=Z,this.attributes={},this.configuration=R,this.name=w,this.fixedDefines=[...V],Z?f._compileStats.precompiled++:f._compileStats.onDemand++;const le=`#version 300 es ${(R?R.defines():[]).concat(V.map(Ze=>`#define ${Ze}`)).join(` `)}`,pe=[le,RL];for(const Ze of I.fragmentIncludes)pe.push(J_[Ze]);pe.push(I.fragmentSource);const Ae=pe.join(` `),_e=[le,NT];for(const Ze of I.vertexIncludes)_e.push(J_[Ze]);this.forceManualRenderingForInstanceIDShaders=f.forceManualRenderingForInstanceIDShaders&&I.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&_e.push("uniform int u_instanceID;"),_e.push(I.vertexSource);let Le=_e.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Le=Le.replaceAll("gl_InstanceID","u_instanceID"));const Ve=te.createShader(te.FRAGMENT_SHADER);if(te.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);te.shaderSource(Ve,Ae),te.compileShader(Ve),te.attachShader(this.program,Ve);const qe=te.createShader(te.VERTEX_SHADER);if(te.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);te.shaderSource(qe,Le),te.compileShader(qe),te.attachShader(this.program,qe),te.linkProgram(this.program),this._fragmentShader=Ve,this._vertexShader=qe,f.extParallelShaderCompile?f._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const f=this._context,w=f.gl;f._pendingPrograms.delete(this);const I=o.o.now(),R=w.getProgramParameter(this.program,w.LINK_STATUS),q=o.o.now()-I,V=f._compileStats;if(V.totalStallMs+=q,q>V.maxStallMs&&(V.maxStallMs=q),q>1){V.framesMissed+=Math.floor(60*q/1e3);const le=this.fixedDefines.join(",");V.stalls.push({name:`${this.name}${le?"/":""}${le}`,ms:q,timestamp:I})}if(this._fragmentShader&&(R||o.w(`Fragment shader '${this.name}': ${w.getShaderInfoLog(this._fragmentShader)}`),w.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(R||o.w(`Vertex shader '${this.name}': ${w.getShaderInfoLog(this._vertexShader)}`),w.deleteShader(this._vertexShader),this._vertexShader=null),!R)return o.w(`Failed to link program '${this.name}': ${w.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(f),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=this.configuration?this.configuration.getUniforms(f):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(le=>({u_instanceID:new o.b$(le)}))(f));const Z=this.fixedDefines,te=this.name;(Z.includes("TERRAIN")||Z.includes("ELEVATED")||te.includes("symbol")||te.includes("circle"))&&(this.terrainUniforms=(le=>({u_dem:new o.b$(le),u_dem_prev:new o.b$(le),u_dem_tl:new o.c2(le),u_dem_scale:new o.c1(le),u_dem_tl_prev:new o.c2(le),u_dem_scale_prev:new o.c1(le),u_dem_size:new o.c1(le),u_dem_lerp:new o.c1(le),u_exaggeration:new o.c1(le),u_depth:new o.b$(le),u_depth_size_inv:new o.c2(le),u_depth_range_unpack:new o.c2(le),u_occluder_half_size:new o.c1(le),u_occlusion_depth_offset:new o.c1(le),u_meter_to_dem:new o.c1(le),u_label_plane_matrix_inv:new o.c3(le)}))(f)),Z.includes("GLOBE")&&(this.globeUniforms=(le=>({u_tile_tl_up:new o.c0(le),u_tile_tr_up:new o.c0(le),u_tile_br_up:new o.c0(le),u_tile_bl_up:new o.c0(le),u_tile_up_scale:new o.c1(le)}))(f)),Z.includes("FOG")&&(this.fogUniforms=(le=>({u_fog_matrix:new o.c3(le),u_fog_range:new o.c2(le),u_fog_color:new o.cS(le),u_fog_horizon_blend:new o.c1(le),u_fog_vertical_limit:new o.c2(le),u_fog_temporal_offset:new o.c1(le),u_frustum_tl:new o.c0(le),u_frustum_tr:new o.c0(le),u_frustum_br:new o.c0(le),u_frustum_bl:new o.c0(le),u_globe_pos:new o.c0(le),u_globe_radius:new o.c1(le),u_globe_transition:new o.c1(le),u_is_globe:new o.b$(le),u_viewport:new o.c2(le)}))(f)),Z.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(le=>({u_cutoff_params:new o.cS(le)}))(f)),Z.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(le=>({u_lighting_ambient_color:new o.c0(le),u_lighting_directional_dir:new o.c0(le),u_lighting_directional_color:new o.c0(le),u_ground_radiance:new o.c0(le)}))(f)),Z.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(le=>({u_light_matrix_0:new o.c3(le),u_light_matrix_1:new o.c3(le),u_fade_range:new o.c2(le),u_shadow_normal_offset:new o.c0(le),u_shadow_intensity:new o.c1(le),u_shadow_texel_size:new o.c1(le),u_shadow_map_resolution:new o.c1(le),u_shadow_direction:new o.c0(le),u_shadow_bias:new o.c0(le),u_shadowmap_0:new o.b$(le),u_shadowmap_1:new o.b$(le)}))(f))}maybeFinalize(){if(!this._pending)return;const f=this._context.extParallelShaderCompile;f&&!this._context.gl.getProgramParameter(this.program,f.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(f,w){this._ensureReady();let I=this.attributes[w];return I===void 0&&(I=this.attributes[w]=f.getAttribLocation(this.program,w)),I}setTerrainUniformValues(f,w){if(this._ensureReady(),!this.terrainUniforms)return;const I=this.terrainUniforms;if(!this.failedToCreate){f.program.set(this.program);for(const R in w)I[R]&&I[R].set(this.program,R,w[R])}}setGlobeUniformValues(f,w){if(this._ensureReady(),!this.globeUniforms)return;const I=this.globeUniforms;if(!this.failedToCreate){f.program.set(this.program);for(const R in w)I[R]&&I[R].set(this.program,R,w[R])}}setFogUniformValues(f,w){if(this._ensureReady(),!this.fogUniforms)return;const I=this.fogUniforms;if(!this.failedToCreate){f.program.set(this.program);for(const R in w)I[R].set(this.program,R,w[R])}}setCutoffUniformValues(f,w){if(this._ensureReady(),!this.cutoffUniforms)return;const I=this.cutoffUniforms;if(!this.failedToCreate){f.program.set(this.program);for(const R in w)I[R].set(this.program,R,w[R])}}setLightsUniformValues(f,w){if(this._ensureReady(),!this.lightsUniforms)return;const I=this.lightsUniforms;if(!this.failedToCreate){f.program.set(this.program);for(const R in w)I[R].set(this.program,R,w[R])}}setShadowUniformValues(f,w){if(this._ensureReady(),this.failedToCreate||!this.shadowUniforms)return;const I=this.shadowUniforms;f.program.set(this.program);for(const R in w)I[R].set(this.program,R,w[R])}_drawDebugWireframe(f,w,I,R,q,V,Z,te,le,pe){const Ae=f.options.wireframe;if(Ae.terrain===!1&&Ae.layers2D===!1&&Ae.layers3D===!1)return;const _e=f.context;if(!(!(!Ae.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ae.layers2D||f._terrain&&f._terrain.renderingToTexture||!j7.includes(this.name))||!(!Ae.layers3D||!N7.includes(this.name))))return;const Le=_e.gl,Ve=f.wireframeDebugCache.getLinesFromTrianglesBuffer(f.frameCounter,q,_e);if(!Ve)return;const qe=[...this.fixedDefines,"DEBUG_WIREFRAME"],Ze=f.getOrCreateProgram(this.name,{config:this.configuration,defines:qe});Ze._ensureReady(),_e.program.set(Ze.program);const Xe=(st,Ut,Pt)=>{if(Ut[st]&&Pt[st])for(const Vt in Ut[st])Pt[st][Vt]&&Pt[st][Vt].set(Pt.program,Vt,Ut[st][Vt].current)};le&&le.setUniforms(Ze.program,_e,Ze.binderUniforms,Z,{zoom:te}),Xe("fixedUniforms",this,Ze),Xe("terrainUniforms",this,Ze),Xe("globeUniforms",this,Ze),Xe("fogUniforms",this,Ze),Xe("lightsUniforms",this,Ze),Xe("shadowUniforms",this,Ze),Ve.bind(),_e.setColorMode(new En([Le.ONE,Le.ONE_MINUS_SRC_ALPHA,Le.ZERO,Le.ONE],o.C.transparent,[!0,!0,!0,!1])),_e.setDepthMode(new Br(w.func===Le.LESS?Le.LEQUAL:w.func,Br.ReadOnly,w.range)),_e.setStencilMode(kn.disabled);const ht=3*V.primitiveLength*2,vt=3*V.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const st=pe||1;for(let Ut=0;Ut1?Le.drawElementsInstanced(Le.LINES,ht,Le.UNSIGNED_SHORT,vt,pe):Le.drawElements(Le.LINES,ht,Le.UNSIGNED_SHORT,vt);q.bind(),_e.program.set(this.program),_e.setDepthMode(w),_e.setStencilMode(I),_e.setColorMode(R)}checkUniforms(f,w,I){if(this.fixedDefines.includes(w)){for(const R of Object.keys(I))if(!I[R].initialized)throw new Error(`Program '${this.name}', from draw '${f}': uniform ${R} not set but required by ${w} being defined`)}}draw(f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze){const Xe=f.context,ht=Xe.gl;if(this._ensureReady(),this.failedToCreate)return;Xe.program.set(this.program),Xe.setDepthMode(I),Xe.setStencilMode(R),Xe.setColorMode(q),Xe.setCullFace(V);for(const[St,Ct]of this.fixedUniformsEntries)Ct.set(this.program,St,Z[St]);Ve&&Ve.setUniforms(this.program,Xe,this.binderUniforms,_e,{zoom:Le});const vt={[ht.POINTS]:1,[ht.LINES]:2,[ht.TRIANGLES]:3,[ht.LINE_STRIP]:1}[w];this.checkUniforms(te,"RENDER_SHADOWS",this.shadowUniforms);const st=qe||[],Ut=Ve?Ve.getPaintVertexBuffers():[],Pt=w===ht.TRIANGLES&&pe,Vt=Ze&&Ze>0?1:void 0;for(const St of Ae.get()){const Ct=St.vaos||(St.vaos={});if((Ct[te]||(Ct[te]=new OL)).bind(Xe,this,le,Ut,pe,St.vertexOffset,st,Vt),this.forceManualRenderingForInstanceIDShaders){const qt=Ze||1;for(let Zt=0;Zt1?ht.drawElementsInstanced(w,St.primitiveLength*vt,ht.UNSIGNED_SHORT,St.primitiveOffset*vt*2,Ze):pe?ht.drawElements(w,St.primitiveLength*vt,ht.UNSIGNED_SHORT,St.primitiveOffset*vt*2):ht.drawArrays(w,St.vertexOffset,St.vertexLength);Pt&&this._drawDebugWireframe(f,I,R,q,pe,St,_e,Le,Ve,Ze)}}}function XL(E,f,w=0){const I=Math.pow(2,f.tileID.overscaledZ),R=f.tileSize*Math.pow(2,E.transform.tileZoom)/I,q=R*(f.tileID.canonical.x+f.tileID.wrap*I),V=R*f.tileID.canonical.y;return{u_image:0,u_texsize:f.imageAtlasTexture?f.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.az(f,1,E.transform.tileZoom),u_pixel_coord_upper:[q>>16,V>>16],u_pixel_coord_lower:[65535&q,65535&V],u_pattern_transition:w}}const IN={terrain:0,flat:1},DT=o.bd(),RT=(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht=[0,0,1])=>{const vt=f.style.light,st=vt.properties.get("position"),Ut=[st.x,st.y,st.z],Pt=o.dH();vt.properties.get("anchor")==="viewport"&&(o.dI(Pt,-f.transform.angle),o.dJ(Ut,Ut,Pt));const Vt=vt.properties.get("color").toPremultipliedRenderColor(null),St=f.transform,Ct={u_matrix:E,u_lightpos:Ut,u_lightintensity:vt.properties.get("intensity"),u_lightcolor:[Vt.r,Vt.g,Vt.b],u_vertical_gradient:+w,u_opacity:I,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:DT,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:IN[le],u_base_type:IN[pe],u_ao:R,u_edge_radius:q,u_width_scale:V,u_flood_light_color:Ve,u_vertical_scale:qe,u_flood_light_intensity:Ze,u_ground_shadow_factor:Xe,u_front_cutoff_params:ht};return St.projection.name==="globe"&&(Ct.u_tile_id=[Z.canonical.x,Z.canonical.y,1<({u_matrix:E,u_edge_radius:f,u_width_scale:w,u_vertical_scale:I,u_height_type:IN[R],u_base_type:IN[q]}),k7=(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe)=>{const ht=RT(E,f,w,I,R,q,V,Z,le,pe,Ae,_e,Le,Ve,qe,Ze,1,[0,0,0]),vt={u_height_factor:-Math.pow(2,Z.overscaledZ)/te.tileSize/8};return Object.assign(ht,XL(f,te,Xe),vt)},QL=(E,f,w)=>({u_matrix:E,u_emissive_strength:f,u_ground_shadow_factor:w}),JL=(E,f,w,I,R,q=0)=>Object.assign(QL(E,f,R),XL(w,I,q)),S7=(E,f,w,I)=>({u_matrix:E,u_world:w,u_emissive_strength:f,u_ground_shadow_factor:I}),C7=(E,f,w,I,R,q,V=0)=>Object.assign(JL(E,f,w,I,q,V),{u_world:R}),T7=(E,f)=>({u_matrix:E,u_depth_bias:f}),e6=(E,f)=>({u_matrix:E,u_ground_shadow_factor:f}),iw=(E,f,w,I,R)=>({u_matrix:E,u_camera_pos:[f[0],f[1],f[2]],u_depth_bias:w,u_height_scale:I,u_reset_depth:R}),E7=(E,f,w)=>({u_image:E,u_texel_size:f,u_first_pass:w?1:0}),A7=(E,f,w,I,R,q,V,Z)=>{const te=o.ak/q.tileSize;return{u_matrix:E,u_inv_rot_matrix:f,u_camera_to_center_distance:w.getCameraToCenterDistance(Z),u_extrude_scale:[w.pixelsToGLUnits[0]/te,w.pixelsToGLUnits[1]/te],u_zoom_transition:I,u_tile_id:V,u_merc_center:R}},M7=(E,f,w,I)=>({u_matrix:E,u_inv_matrix:f,u_camera_to_center_distance:w.getCameraToCenterDistance(I),u_viewport_size:[w.width,w.height]}),FT=(E,f,w=1)=>({u_matrix:E,u_color:f,u_overlay:0,u_overlay_scale:w}),t6=o.bd(),I7=(E,f,w,I,R,q,V)=>{const Z=E.transform,te=Z.projection.name==="globe",le=te?o.dK(Z.zoom,f.canonical)*Z._pixelsPerMercatorPixel:o.az(w,1,q),pe={u_matrix:f.projMatrix,u_extrude_scale:le,u_intensity:V,u_inv_rot_matrix:t6,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(te){pe.u_inv_rot_matrix=I,pe.u_merc_center=R,pe.u_tile_id=[f.canonical.x,f.canonical.y,1<({u_matrix:f,u_normalize_matrix:w,u_globe_matrix:I,u_merc_matrix:R,u_grid_matrix:q,u_tl_parent:V,u_scale_parent:pe,u_fade_t:Ae.mix,u_opacity:Ae.opacity*_e.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:_e.paint.get("raster-brightness-min"),u_brightness_high:_e.paint.get("raster-brightness-max"),u_saturation_factor:o.dM(_e.paint.get("raster-saturation")),u_contrast_factor:o.dL(_e.paint.get("raster-contrast")),u_spin_weights:n6(_e.paint.get("raster-hue-rotate")),u_perspective_transform:Le,u_raster_elevation:Ve,u_zoom_transition:Z,u_merc_center:te,u_cutoff_params:le,u_colorization_mix:BT(o.dN,Ze,ht),u_colorization_offset:s6(o.dN,Xe,ht),u_color_ramp:qe,u_texture_offset:[st/(vt+2*st),vt/(vt+2*st)],u_texture_res:[vt+2*st,vt+2*st],u_emissive_strength:Ut,u_zbias_factor:r6(E)});function n6(E){E*=Math.PI/180;const f=Math.sin(E),w=Math.cos(E);return[(2*w+1)/3,(-Math.sqrt(3)*f-w+1)/3,(Math.sqrt(3)*f-w+1)/3]}const P7=o.bd(),L7=(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht,vt,st,Ut,Pt,Vt)=>{const St=R.transform,Ct={u_is_size_zoom_constant:+(E==="constant"||E==="source"),u_is_size_feature_constant:+(E==="constant"||E==="camera"),u_size_t:f?f.uSizeT:0,u_size:f?f.uSize:0,u_camera_to_center_distance:St.getCameraToCenterDistance(ht),u_rotate_symbol:+w,u_aspect_ratio:St.width/St.height,u_fade_change:R.options.fadeDuration?R.symbolFadeChange:1,u_matrix:q,u_label_plane_matrix:V,u_coord_matrix:Z,u_is_text:+le,u_elevation_from_sea:te?1:0,u_pitch_with_map:+I,u_texsize:pe,u_texsize_icon:Ae,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:P7,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:P7,u_up_vector:[0,-1,0],u_color_adj_mat:Ut,u_icon_transition:Pt||0,u_gamma_scale:I?R.transform.getCameraToCenterDistance(ht)*Math.cos(R.terrain?0:R.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Vt||1,u_ground_shadow_factor:vt,u_inv_matrix:o.ba(o.bd(),V),u_normal_scale:st,u_lutTexture:10,u_zoom:St.zoom-Math.floor(St.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 ht.name==="globe"&&(Ct.u_tile_id=[Le.canonical.x,Le.canonical.y,1<({u_matrix:E,u_emissive_strength:f,u_opacity:w,u_color:I}),$T=(E,f,w,I,R,q,V,Z,te)=>Object.assign(function(le,pe,Ae,_e,Le,Ve){const{width:qe,height:Ze}=_e.imageManager.getPixelSize(pe),Xe=Math.pow(2,Ve.tileID.overscaledZ),ht=Ve.tileSize*Math.pow(2,_e.transform.tileZoom)/Xe,vt=ht*(Ve.tileID.canonical.x+Ve.tileID.wrap*Xe),st=ht*Ve.tileID.canonical.y;return{u_image:0,u_pattern_tl:Ae.tl,u_pattern_br:Ae.br,u_texsize:[qe,Ze],u_pattern_size:Ae.displaySize,u_pattern_units_to_pixels:Le?[_e.transform.width,-1*_e.transform.height]:[1/o.az(Ve,1,_e.transform.tileZoom),1/o.az(Ve,1,_e.transform.tileZoom)],u_pixel_coord_upper:[vt>>16,st>>16],u_pixel_coord_lower:[65535&vt,65535&st]}}(0,q,V,I,Z,te),{u_matrix:E,u_emissive_strength:f,u_opacity:w}),a6=new Float32Array(o.bA([])),UT=(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le=[0,0,0],Ve,qe,Ze,Xe=1)=>{const ht=R.style.light,vt=ht.properties.get("position"),st=[-vt.x,-vt.y,vt.z],Ut=o.dH();ht.properties.get("anchor")==="viewport"&&(o.dI(Ut,-R.transform.angle),o.dJ(st,st,Ut));const Pt=pe.alphaMode==="MASK",Vt=ht.properties.get("color").toNonPremultipliedRenderColor(null),St=_e.paint.get("model-ambient-occlusion-intensity"),Ct=_e.paint.get("model-color").constantOr(o.C.white).toNonPremultipliedRenderColor(null);return Ct.a=_e.paint.get("model-color-mix-intensity").constantOr(0),Ze&&(Ct.r=Ze[0],Ct.g=Ze[1],Ct.b=Ze[2],Ct.a=Ze[3]),qe&&(Ct.r=qe.color.r,Ct.g=qe.color.g,Ct.b=qe.color.b,Ct.a=qe.colorMix,Ae=qe.emissionStrength,q*=qe.opacity),{u_matrix:E,u_lighting_matrix:f,u_normal_matrix:w,u_node_matrix:I||a6,u_lightpos:st,u_lightintensity:ht.properties.get("intensity"),u_lightcolor:[Vt.r,Vt.g,Vt.b],u_camera_pos:Le,u_opacity:q,u_baseTextureIsAlpha:0,u_alphaMask:+Pt,u_alphaCutoff:pe.alphaCutoff,u_baseColorFactor:V.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:Z.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:te,u_roughnessFactor:le,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Ct.toArray01(),u_aoIntensity:St,u_emissive_strength:Ae,u_occlusionTextureTransform:Ve||[0,0,0,0],u_dithered_discard_threshold:Xe}},R7=(E,f=a6,w=a6)=>({u_matrix:E,u_instance:f,u_node_matrix:w}),O7={fillExtrusion:E=>({u_matrix:new o.c3(E),u_lightpos:new o.c0(E),u_lightintensity:new o.c1(E),u_lightcolor:new o.c0(E),u_vertical_gradient:new o.c1(E),u_opacity:new o.c1(E),u_edge_radius:new o.c1(E),u_width_scale:new o.c1(E),u_ao:new o.c2(E),u_height_type:new o.b$(E),u_base_type:new o.b$(E),u_tile_id:new o.c0(E),u_zoom_transition:new o.c1(E),u_inv_rot_matrix:new o.c3(E),u_merc_center:new o.c2(E),u_up_dir:new o.c0(E),u_height_lift:new o.c1(E),u_flood_light_color:new o.c0(E),u_vertical_scale:new o.c1(E),u_flood_light_intensity:new o.c1(E),u_ground_shadow_factor:new o.c0(E),u_front_cutoff_params:new o.c0(E)}),fillExtrusionDepth:E=>({u_matrix:new o.c3(E),u_edge_radius:new o.c1(E),u_width_scale:new o.c1(E),u_vertical_scale:new o.c1(E),u_height_type:new o.b$(E),u_base_type:new o.b$(E)}),fillExtrusionPattern:E=>({u_matrix:new o.c3(E),u_lightpos:new o.c0(E),u_lightintensity:new o.c1(E),u_lightcolor:new o.c0(E),u_vertical_gradient:new o.c1(E),u_height_factor:new o.c1(E),u_edge_radius:new o.c1(E),u_width_scale:new o.c1(E),u_ao:new o.c2(E),u_height_type:new o.b$(E),u_base_type:new o.b$(E),u_tile_id:new o.c0(E),u_zoom_transition:new o.c1(E),u_inv_rot_matrix:new o.c3(E),u_merc_center:new o.c2(E),u_up_dir:new o.c0(E),u_height_lift:new o.c1(E),u_image:new o.b$(E),u_texsize:new o.c2(E),u_pixel_coord_upper:new o.c2(E),u_pixel_coord_lower:new o.c2(E),u_tile_units_to_pixels:new o.c1(E),u_opacity:new o.c1(E),u_pattern_transition:new o.c1(E)}),fillExtrusionGroundEffect:E=>({u_matrix:new o.c3(E),u_opacity:new o.c1(E),u_ao_pass:new o.c1(E),u_meter_to_tile:new o.c1(E),u_ao:new o.c2(E),u_flood_light_intensity:new o.c1(E),u_flood_light_color:new o.c0(E),u_attenuation:new o.c1(E),u_edge_radius:new o.c1(E),u_fb:new o.b$(E),u_fb_size:new o.c1(E),u_dynamic_offset:new o.c1(E)}),fill:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_ground_shadow_factor:new o.c0(E)}),fillPattern:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_image:new o.b$(E),u_texsize:new o.c2(E),u_pixel_coord_upper:new o.c2(E),u_pixel_coord_lower:new o.c2(E),u_tile_units_to_pixels:new o.c1(E),u_ground_shadow_factor:new o.c0(E),u_pattern_transition:new o.c1(E)}),fillOutline:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_world:new o.c2(E),u_ground_shadow_factor:new o.c0(E)}),fillOutlinePattern:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_world:new o.c2(E),u_image:new o.b$(E),u_texsize:new o.c2(E),u_pixel_coord_upper:new o.c2(E),u_pixel_coord_lower:new o.c2(E),u_tile_units_to_pixels:new o.c1(E),u_ground_shadow_factor:new o.c0(E),u_pattern_transition:new o.c1(E)}),lineBlendComposite:E=>({u_image:new o.b$(E),u_opacity:new o.c1(E),u_blend_mode:new o.b$(E),u_max_density:new o.c1(E)}),lineBlendReduce:E=>({u_image:new o.b$(E),u_texel_size:new o.c2(E),u_first_pass:new o.b$(E)}),elevatedStructuresDepth:E=>({u_matrix:new o.c3(E),u_depth_bias:new o.c1(E)}),elevatedStructures:E=>({u_matrix:new o.c3(E),u_ground_shadow_factor:new o.c0(E)}),elevatedStructuresDepthReconstruct:E=>({u_matrix:new o.c3(E),u_camera_pos:new o.c0(E),u_depth_bias:new o.c1(E),u_height_scale:new o.c1(E),u_reset_depth:new o.c1(E)}),circle:o.dR,collisionBox:E=>({u_matrix:new o.c3(E),u_inv_rot_matrix:new o.c3(E),u_camera_to_center_distance:new o.c1(E),u_extrude_scale:new o.c2(E),u_zoom_transition:new o.c1(E),u_merc_center:new o.c2(E),u_tile_id:new o.c0(E)}),collisionCircle:E=>({u_matrix:new o.c3(E),u_inv_matrix:new o.c3(E),u_camera_to_center_distance:new o.c1(E),u_viewport_size:new o.c2(E)}),debug:E=>({u_color:new o.dp(E),u_matrix:new o.c3(E),u_overlay:new o.b$(E),u_overlay_scale:new o.c1(E)}),clippingMask:E=>({u_matrix:new o.c3(E)}),heatmap:E=>({u_extrude_scale:new o.c1(E),u_intensity:new o.c1(E),u_matrix:new o.c3(E),u_inv_rot_matrix:new o.c3(E),u_merc_center:new o.c2(E),u_tile_id:new o.c0(E),u_zoom_transition:new o.c1(E),u_up_dir:new o.c0(E)}),heatmapTexture:E=>({u_image:new o.b$(E),u_color_ramp:new o.b$(E),u_opacity:new o.c1(E)}),hillshade:E=>({u_matrix:new o.c3(E),u_image:new o.b$(E),u_latrange:new o.c2(E),u_light:new o.c2(E),u_shadow:new o.dp(E),u_highlight:new o.dp(E),u_emissive_strength:new o.c1(E),u_accent:new o.dp(E)}),hillshadePrepare:E=>({u_matrix:new o.c3(E),u_image:new o.b$(E),u_dimension:new o.c2(E),u_zoom:new o.c1(E)}),line:o.dQ,linePattern:o.dP,raster:E=>({u_matrix:new o.c3(E),u_normalize_matrix:new o.c3(E),u_globe_matrix:new o.c3(E),u_merc_matrix:new o.c3(E),u_grid_matrix:new o.dq(E),u_tl_parent:new o.c2(E),u_scale_parent:new o.c1(E),u_fade_t:new o.c1(E),u_opacity:new o.c1(E),u_image0:new o.b$(E),u_image1:new o.b$(E),u_brightness_low:new o.c1(E),u_brightness_high:new o.c1(E),u_saturation_factor:new o.c1(E),u_contrast_factor:new o.c1(E),u_spin_weights:new o.c0(E),u_perspective_transform:new o.c2(E),u_raster_elevation:new o.c1(E),u_zoom_transition:new o.c1(E),u_merc_center:new o.c2(E),u_cutoff_params:new o.cS(E),u_colorization_mix:new o.cS(E),u_colorization_offset:new o.c1(E),u_color_ramp:new o.b$(E),u_texture_offset:new o.c2(E),u_texture_res:new o.c2(E),u_emissive_strength:new o.c1(E),u_zbias_factor:new o.c1(E)}),symbol:E=>({u_is_size_zoom_constant:new o.b$(E),u_is_size_feature_constant:new o.b$(E),u_size_t:new o.c1(E),u_size:new o.c1(E),u_camera_to_center_distance:new o.c1(E),u_rotate_symbol:new o.b$(E),u_aspect_ratio:new o.c1(E),u_fade_change:new o.c1(E),u_matrix:new o.c3(E),u_label_plane_matrix:new o.c3(E),u_coord_matrix:new o.c3(E),u_is_text:new o.b$(E),u_elevation_from_sea:new o.b$(E),u_pitch_with_map:new o.b$(E),u_texsize:new o.c2(E),u_texsize_icon:new o.c2(E),u_texture:new o.b$(E),u_texture_icon:new o.b$(E),u_gamma_scale:new o.c1(E),u_device_pixel_ratio:new o.c1(E),u_tile_id:new o.c0(E),u_zoom_transition:new o.c1(E),u_inv_rot_matrix:new o.c3(E),u_merc_center:new o.c2(E),u_camera_forward:new o.c0(E),u_tile_matrix:new o.c3(E),u_up_vector:new o.c0(E),u_ecef_origin:new o.c0(E),u_is_halo:new o.b$(E),u_icon_transition:new o.c1(E),u_color_adj_mat:new o.c3(E),u_scale_factor:new o.c1(E),u_ground_shadow_factor:new o.c0(E),u_inv_matrix:new o.c3(E),u_normal_scale:new o.c1(E),u_lutTexture:new o.b$(E),u_zoom:new o.c1(E),u_spp_fill_np_color:new o.cS(E),u_spp_halo_np_color:new o.cS(E),u_spp_opacity:new o.c1(E),u_spp_halo_width:new o.c1(E),u_spp_halo_blur:new o.c1(E),u_spp_emissive_strength:new o.c1(E),u_spp_occlusion_opacity:new o.c1(E),u_spp_z_offset:new o.c1(E),u_spp_translate_rotation:new o.c2(E)}),background:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_opacity:new o.c1(E),u_color:new o.dp(E)}),backgroundPattern:E=>({u_matrix:new o.c3(E),u_emissive_strength:new o.c1(E),u_opacity:new o.c1(E),u_image:new o.b$(E),u_pattern_tl:new o.c2(E),u_pattern_br:new o.c2(E),u_texsize:new o.c2(E),u_pattern_size:new o.c2(E),u_pixel_coord_upper:new o.c2(E),u_pixel_coord_lower:new o.c2(E),u_pattern_units_to_pixels:new o.c2(E)}),terrainRaster:E=>({u_matrix:new o.c3(E),u_image0:new o.b$(E),u_image1:new o.b$(E),u_skirt_height:new o.c1(E),u_ground_shadow_factor:new o.c0(E),u_emissive_texture_available:new o.c1(E)}),skybox:E=>({u_matrix:new o.c3(E),u_sun_direction:new o.c0(E),u_cubemap:new o.b$(E),u_opacity:new o.c1(E),u_temporal_offset:new o.c1(E)}),skyboxGradient:E=>({u_matrix:new o.c3(E),u_color_ramp:new o.b$(E),u_center_direction:new o.c0(E),u_radius:new o.c1(E),u_opacity:new o.c1(E),u_temporal_offset:new o.c1(E)}),skyboxCapture:E=>({u_matrix_3f:new o.dq(E),u_sun_direction:new o.c0(E),u_sun_intensity:new o.c1(E),u_color_tint_r:new o.cS(E),u_color_tint_m:new o.cS(E),u_luminance:new o.c1(E)}),globeRaster:E=>({u_proj_matrix:new o.c3(E),u_globe_matrix:new o.c3(E),u_normalize_matrix:new o.c3(E),u_merc_matrix:new o.c3(E),u_zoom_transition:new o.c1(E),u_merc_center:new o.c2(E),u_image0:new o.b$(E),u_image1:new o.b$(E),u_grid_matrix:new o.dq(E),u_skirt_height:new o.c1(E),u_far_z_cutoff:new o.c1(E),u_frustum_tl:new o.c0(E),u_frustum_tr:new o.c0(E),u_frustum_br:new o.c0(E),u_frustum_bl:new o.c0(E),u_globe_pos:new o.c0(E),u_globe_radius:new o.c1(E),u_viewport:new o.c2(E),u_emissive_texture_available:new o.c1(E)}),globeAtmosphere:E=>({u_frustum_tl:new o.c0(E),u_frustum_tr:new o.c0(E),u_frustum_br:new o.c0(E),u_frustum_bl:new o.c0(E),u_horizon:new o.c1(E),u_transition:new o.c1(E),u_fadeout_range:new o.c1(E),u_atmosphere_fog_color:new o.cS(E),u_high_color:new o.cS(E),u_space_color:new o.cS(E),u_temporal_offset:new o.c1(E),u_horizon_angle:new o.c1(E)}),model:E=>({u_matrix:new o.c3(E),u_lighting_matrix:new o.c3(E),u_normal_matrix:new o.c3(E),u_node_matrix:new o.c3(E),u_lightpos:new o.c0(E),u_lightintensity:new o.c1(E),u_lightcolor:new o.c0(E),u_camera_pos:new o.c0(E),u_opacity:new o.c1(E),u_baseColorFactor:new o.cS(E),u_emissiveFactor:new o.cS(E),u_metallicFactor:new o.c1(E),u_roughnessFactor:new o.c1(E),u_baseTextureIsAlpha:new o.b$(E),u_alphaMask:new o.b$(E),u_alphaCutoff:new o.c1(E),u_baseColorTexture:new o.b$(E),u_metallicRoughnessTexture:new o.b$(E),u_normalTexture:new o.b$(E),u_occlusionTexture:new o.b$(E),u_emissionTexture:new o.b$(E),u_lutTexture:new o.b$(E),u_color_mix:new o.cS(E),u_aoIntensity:new o.c1(E),u_emissive_strength:new o.c1(E),u_occlusionTextureTransform:new o.cS(E),u_dithered_discard_threshold:new o.c1(E)}),modelDepth:E=>({u_matrix:new o.c3(E),u_instance:new o.c3(E),u_node_matrix:new o.c3(E)}),groundShadow:E=>({u_matrix:new o.c3(E),u_ground_shadow_factor:new o.c0(E)}),stars:E=>({u_matrix:new o.c3(E),u_up:new o.c0(E),u_right:new o.c0(E),u_intensity_multiplier:new o.c1(E)}),occlusion:E=>({u_matrix:new o.c3(E),u_anchorPos:new o.c0(E),u_screenSizePx:new o.c2(E),u_occluderSizePx:new o.c2(E),u_color:new o.cS(E)})};class D0{constructor(f,w,I,R){this.id=D0.uniqueIdxCounter,D0.uniqueIdxCounter++,this.context=f;const q=f.gl;this.buffer=q.createBuffer(),this.dynamicDraw=!!I,this.context.unbindVAO(),f.bindElementBuffer.set(this.buffer),q.bufferData(q.ELEMENT_ARRAY_BUFFER,w.arrayBuffer,this.dynamicDraw?q.DYNAMIC_DRAW:q.STATIC_DRAW),this.dynamicDraw||R||w.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(f){this.id=D0.uniqueIdxCounter,D0.uniqueIdxCounter++;const w=this.context.gl;this.context.unbindVAO(),this.bind(),w.bufferSubData(w.ELEMENT_ARRAY_BUFFER,0,f.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}D0.uniqueIdxCounter=0;const Cye={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class gm{constructor(f,w,I,R,q,V){this.length=w.length,this.attributes=I,this.itemSize=w.bytesPerElement,this.dynamicDraw=R,this.instanceCount=V,this.context=f;const Z=f.gl;this.buffer=Z.createBuffer(),f.bindVertexBuffer.set(this.buffer),Z.bufferData(Z.ARRAY_BUFFER,w.arrayBuffer,this.dynamicDraw?Z.DYNAMIC_DRAW:Z.STATIC_DRAW),this.dynamicDraw||q||w.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(f){const w=this.context.gl;this.bind(),w.bufferSubData(w.ARRAY_BUFFER,0,f.arrayBuffer)}enableAttributes(f,w){for(const I of this.attributes){const R=w.getAttributeLocation(f,I.name);R!==-1&&f.enableVertexAttribArray(R)}}setVertexAttribPointers(f,w,I){for(const R of this.attributes){const q=w.getAttributeLocation(f,R.name);if(q!==-1){const V=R.offset+this.itemSize*(I||0);R.type==="Float32"?f.vertexAttribPointer(q,R.components,f.FLOAT,!1,this.itemSize,V):f.vertexAttribIPointer(q,R.components,f[Cye[R.type]],this.itemSize,V)}}}setVertexAttribDivisor(f,w,I){for(let R=0;R0&&f.vertexAttribDivisor(q,I)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class R0{constructor(f,w,I,R,q){this.context=f,this.width=w,this.height=I;const V=this.framebuffer=f.gl.createFramebuffer();R>0&&(this.colorAttachment0=new IT(f,V,0)),R>1&&(this.colorAttachment1=new IT(f,V,1)),q&&(this.depthAttachmentType=q,this.depthAttachment=q==="renderbuffer"?new WL(f,V):new Sye(f,V))}static createWithTexture(f,w,I,R,q){const V=f.gl;if(f.activeTexture.set(V.TEXTURE1),f.viewport.set([0,0,I,R]),w&&w.width===I&&w.height===R)return V.bindTexture(V.TEXTURE_2D,w.colorAttachment0.get()),f.bindFramebuffer.set(w.framebuffer),w;w&&w.destroy();const Z=f.extRenderToTextureHalfFloat||f.extColorBufferFloat?f.gl.RGBA16F:f.gl.RGBA8,te=new o.T(f,{width:I,height:R,data:null},Z);te.bind(V.LINEAR,V.CLAMP_TO_EDGE);const le=f.createFramebuffer(I,R,1,null);if(le.format=Z,le.colorAttachment0.set(te.texture),q){const pe=f.createRenderbuffer(V.DEPTH24_STENCIL8,I,R);f.bindFramebuffer.set(le.framebuffer),V.framebufferRenderbuffer(V.FRAMEBUFFER,V.DEPTH_STENCIL_ATTACHMENT,V.RENDERBUFFER,pe),le._stencilRbo=pe}return le}createColorAttachment(f,w){w===0?this.colorAttachment0=new IT(f,this.framebuffer,0):w===1&&(this.colorAttachment1=new IT(f,this.framebuffer,1))}removeColorAttachment(f,w){const I=this.context.gl;let R;w===0?(R=this.colorAttachment0.get(),this.colorAttachment0=void 0):w===1&&(R=this.colorAttachment1.get(),this.colorAttachment1=void 0),R&&I.deleteTexture(R)}destroy(){const f=this.context.gl;if(this.colorAttachment0){const w=this.colorAttachment0.get();w&&f.deleteTexture(w)}if(this.colorAttachment1){const w=this.colorAttachment1.get();w&&f.deleteTexture(w)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const w=this.depthAttachment.get();w&&f.deleteRenderbuffer(w)}else{const w=this.depthAttachment.get();w&&f.deleteTexture(w)}this._stencilRbo&&(f.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),f.deleteFramebuffer(this.framebuffer)}}class oh{constructor(f,w){this.gl=f,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new h7(this),this.clearDepth=new m7(this),this.clearStencil=new sw(this),this.colorMask=new vye(this),this.depthMask=new bye(this),this.stencilMask=new _ye(this),this.stencilFunc=new wye(this),this.stencilOp=new jye(this),this.stencilTest=new Nye(this),this.depthRange=new BL(this),this.depthTest=new zL(this),this.depthFunc=new $L(this),this.blend=new rw(this),this.blendFunc=new f7(this),this.blendColor=new p7(this),this.blendEquation=new x7(this),this.cullFace=new UL(this),this.cullFaceSide=new I0(this),this.frontFace=new ET(this),this.program=new AT(this),this.activeTexture=new g7(this),this.viewport=new P0(this),this.bindFramebuffer=new qL(this),this.bindRenderbuffer=new MT(this),this.bindTexture=new y7(this),this.bindVertexBuffer=new v7(this),this.bindElementBuffer=new VL(this),this.bindVertexArrayOES=new HL(this),this.pixelStoreUnpack=new kye(this),this.pixelStoreUnpackPremultiplyAlpha=new b7(this),this.pixelStoreUnpackFlipY=new AN(this),this.options=w?Object.assign({},w):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=f.getExtension("EXT_texture_filter_anisotropic")||f.getExtension("MOZ_EXT_texture_filter_anisotropic")||f.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=f.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=f.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=f.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=f.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=w&&!!w.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.disableSymbolUBO=w&&!!w.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=f.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=f.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=f.getExtension("EXT_color_buffer_float"),this.extTimerQuery=f.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=f.getParameter(f.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(f.getParameter(f.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=f.getParameter(f.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=f.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=f.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(this._pendingPrograms.size!==0)for(const f of this._pendingPrograms)f.maybeFinalize()}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(f,w,I){return new D0(this,f,w,I)}createVertexBuffer(f,w,I,R,q){return new gm(this,f,w,I,R,q)}createRenderbuffer(f,w,I){const R=this.gl,q=R.createRenderbuffer();return this.bindRenderbuffer.set(q),R.renderbufferStorage(R.RENDERBUFFER,f,w,I),this.bindRenderbuffer.set(null),q}createFramebuffer(f,w,I,R){return new R0(this,f,w,I,R)}clear({color:f,depth:w,stencil:I,colorMask:R}){const q=this.gl;let V=0;f&&(V|=q.COLOR_BUFFER_BIT,this.clearColor.set(f.toNonPremultipliedRenderColor(null)),this.colorMask.set(R||[!0,!0,!0,!0])),w!==void 0&&(V|=q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(w),this.depthMask.set(!0)),I!==void 0&&(V|=q.STENCIL_BUFFER_BIT,this.clearStencil.set(I),this.stencilMask.set(255)),q.clear(V)}setCullFace(f){f.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(f.mode),this.frontFace.set(f.frontFace))}setDepthMode(f){f.func!==this.gl.ALWAYS||f.mask?(this.depthTest.set(!0),this.depthFunc.set(f.func),this.depthMask.set(f.mask),this.depthRange.set(f.range)):this.depthTest.set(!1)}setStencilMode(f){f.test.func!==this.gl.ALWAYS||f.mask?(this.stencilTest.set(!0),this.stencilMask.set(f.mask),this.stencilOp.set([f.fail,f.depthFail,f.pass]),this.stencilFunc.set({func:f.test.func,ref:f.ref,mask:f.test.mask})):this.stencilTest.set(!1)}setColorMode(f){o.b9(f.blendFunction,En.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(f.blendFunction),this.blendColor.set(f.blendColor),f.blendEquation?this.blendEquation.set(f.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(f.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let Ip;function i6(E,f,w,I,R,q,V){const Z=E.context,te=Z.gl,le=E.transform,pe=[o.aG(le.center.lng),o.aJ(le.center.lat)],Ae=w.layout.get("symbol-placement"),_e=w.layout.get("text-variable-anchor"),Le=w.layout.get("icon-rotation-alignment")==="map",Ve=w.layout.get("text-rotation-alignment")==="map",qe=Ae!=="point",Ze=[];let Xe=0,ht=0;for(let St=0;St0){const Vr=o.bd(),Ir=or;o.cB(Vr,Zt.placementInvProjMatrix,le.glCoordMatrix),o.cB(Vr,Vr,Zt.placementViewportMatrix),Ze.push({circleArray:Ys,circleOffset:ht,transform:Ir,invTransform:Vr,projection:Zt.getProjection()}),Xe+=Ys.length/4,ht=Xe}if(!Js)continue;E.terrain&&E.terrain.setupElevationDraw(qt,xr);const Wr=Ms?[Ct.canonical.x,Ct.canonical.y,1<=0&&(Le[vt.associatedIconIndex]={x:Wt,y:hs,z:ms,angle:Ps})}else K_(Pt,Ae)}if(le){_e.clear();const ht=E.icon.placedSymbolArray;for(let vt=0;vt{let $n=[0,0,0];if(wi){const ho=E.style.directionalLight,qi=E.style.ambientLight;ho&&qi&&($n=$1(E.style,ho,qi))}return $n},Ia=wi=>{if(E.context.disableSymbolUBO)return;wi.push("USE_PAINT_PROPERTIES_UBO");const $n=Math.floor(E.context.maxUniformBlockSize/4),ho=Math.floor($n/4);wi.push(`MAX_UBO_SIZE_VEC4 ${ho}u`)},qn=wi=>{Ct.depthOcclusionForSymbolsAndCircles&&(w.hasOcclusionOpacityProperties||E.terrain)&&(wi.push("DEPTH_D24"),wi.push("DEPTH_OCCLUSION"))},Ha=wi=>{w.lut&&!Pt&&(w.lut.texture||(w.lut.texture=new o.dU(E.context,w.lut.image,[w.lut.image.height,w.lut.image.height,w.lut.image.height],Vt.gl.RGBA8)),Vt.activeTexture.set(Vt.gl.TEXTURE0+10),w.lut.texture&&w.lut.texture.bind(Vt.gl.LINEAR,Vt.gl.CLAMP_TO_EDGE),wi.push("APPLY_LUT_ON_GPU"))},Ai=()=>{const wi=qt&&w.layout.get("symbol-placement")!=="point",$n=[];qn($n),Ha($n);const ho=wi||Ln,qi=Ys.elevationType==="road",cl=E.shadowRenderer,Oa=qi&&Wt&&!!cl&&cl.enabled,jl=Tn(Oa),Kd=qi&&Wt&&!E.terrain?Ns:ts,bc=w.paint.get("icon-image-cross-fade");E.terrainRenderModeElevated()&&Wt&&$n.push("PITCH_WITH_MAP_TERRAIN"),Wr&&($n.push("PROJECTION_GLOBE_VIEW"),ho&&$n.push("PROJECTED_POS_ON_VIEWPORT")),bc>0&&Ys.hasAnySecondaryIcon&&$n.push("ICON_TRANSITION"),!Ys.icon.zOffsetVertexBuffer||qi&&E.terrain||$n.push("Z_OFFSET"),Xe===0&&ht===0&&vt===0&&st===1||$n.push("COLOR_ADJUSTMENT"),Ys.sdfIcons&&$n.push("RENDER_SDF"),Oa&&$n.push("RENDER_SHADOWS","NORMAL_OFFSET"),qi&&Wt&&!E.terrain&&Ys.icon.orientationVertexBuffer&&$n.push("ELEVATED_ROADS"),Ia($n);const Qc=Vt.disableSymbolUBO?Ys.icon.programConfigurations.get(w.id):null,nc=E.getOrCreateProgram("symbol",{config:Qc,defines:$n}),dh=Js.imageAtlasTexture?Js.imageAtlasTexture.size:[0,0],uh=Ys.iconSizeData,Ol=o.bl(uh,Ct.zoom),pu=Wt||!Ct.isOrthographic,ii=Rl(Ir,Js.tileID.canonical,Wt,qt,Ct,Ys.getProjection(),Rr),Mi=Ap(Ir,Js.tileID.canonical,Wt,qt,Ct,Ys.getProjection(),Rr),pi=Ys.icon.uboBinder&&Ys.icon.uboBinder.cachedHeader&&256&Ys.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:Z,Nl=E.translatePosMatrix(Mi,Js,pi,le,!0),Rc=E.translatePosMatrix(Ir,Js,pi,le),Jo=ho?ow:ii,Mu=qt&&!Wt&&!wi;let Iu=xr;!Ms&&!Ct.mercatorFromTransition||qt||(Iu=qT(Ct));const Rp=Wr?Iu:xr,_m=w.getColorAdjustmentMatrix(Xe,ht,vt,st),ef=L7(uh.kind,Ol,Mu,Wt,E,Rc,Jo,Nl,Ut,!1,dh,[0,0],0,or,Vr,rs,An,Rp,Ys.getProjection(),jl,ta,_m,bc,null),_y=Js.imageAtlasTexture?Js.imageAtlasTexture:null,Op=w.layout.get("icon-size").constantOr(0)!==1||Ys.iconsNeedLinear,WN=Ys.sdfIcons||E.options.rotating||E.options.zooming||Op||pu?St.LINEAR:St.NEAREST,H0=Ys.sdfIcons&&w.paint.get("icon-halo-width").constantOr(1)!==0,nb=E.terrain&&Wt&&wi?o.ba(o.bd(),ii):ow;if(wi&&Ys.icon){const z6=o.bx.getAtTileOffsetFunc(or,Ct.center.lat,Ct.worldSize,Ys.getProjection()),$6=Ff(Ir,Js.tileID.canonical,Wt,qt,Ct,Ys.getProjection(),Rr),oE=w.layout.get("icon-size-scale-range"),Kye=o.aB(E.scaleFactor,oE[0],oE[1]);W_(Ys,Ir,E,!1,$6,Mi,Wt,qe,z6,or,Kye)}return{program:nc,buffers:Ys.icon,uniformValues:ef,atlasTexture:_y,atlasTextureIcon:null,atlasInterpolation:WN,atlasInterpolationIcon:null,isSDF:Ys.sdfIcons,hasHalo:H0,depthMode:Kd,tile:Js,renderWithShadows:Oa,labelPlaneMatrixInv:nb}},Li=()=>{const wi=Zt&&w.layout.get("symbol-placement")!=="point",$n=[],ho=wi||Ps||Ln,qi=Ys.elevationType==="road",cl=E.shadowRenderer,Oa=qi&&hs&&!!cl&&cl.enabled,jl=Tn(Oa),Kd=qi&&hs&&!E.terrain?Ns:ts;E.terrainRenderModeElevated()&&hs&&$n.push("PITCH_WITH_MAP_TERRAIN"),Wr&&($n.push("PROJECTION_GLOBE_VIEW"),ho&&$n.push("PROJECTED_POS_ON_VIEWPORT")),!Ys.text.zOffsetVertexBuffer||qi&&E.terrain||$n.push("Z_OFFSET"),Ys.iconsInText&&$n.push("RENDER_TEXT_AND_SYMBOL"),$n.push("RENDER_SDF"),Oa&&$n.push("RENDER_SHADOWS","NORMAL_OFFSET"),qi&&hs&&!E.terrain&&Ys.text.orientationVertexBuffer&&$n.push("ELEVATED_ROADS"),qn($n),Ia($n);const bc=Vt.disableSymbolUBO?Ys.text.programConfigurations.get(w.id):null,Qc=E.getOrCreateProgram("symbol",{config:bc,defines:$n});let nc,dh=[0,0],uh=null;const Ol=Ys.textSizeData;Ys.iconsInText&&(dh=Js.imageAtlasTexture?Js.imageAtlasTexture.size:[0,0],uh=Js.imageAtlasTexture?Js.imageAtlasTexture:null,nc=hs||!Ct.isOrthographic||E.options.rotating||E.options.zooming||Ol.kind==="composite"||Ol.kind==="camera"?St.LINEAR:St.NEAREST);const pu=Js.glyphAtlasTexture?Js.glyphAtlasTexture.size:[0,0],ii=w.layout.get("text-size-scale-range"),Mi=o.aB(E.scaleFactor,ii[0],ii[1]),pi=o.bl(Ol,Ct.zoom,Mi),Nl=Rl(Ir,Js.tileID.canonical,hs,Zt,Ct,Ys.getProjection(),Rr),Rc=Ap(Ir,Js.tileID.canonical,hs,Zt,Ct,Ys.getProjection(),Rr),Jo=Ys.text.uboBinder&&Ys.text.uboBinder.cachedHeader&&256&Ys.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:te,Mu=E.translatePosMatrix(Rc,Js,Jo,pe,!0),Iu=E.translatePosMatrix(Ir,Js,Jo,pe),Rp=ho?ow:Nl,_m=Zt&&!hs&&!wi;let ef=xr;!Ms&&!Ct.mercatorFromTransition||Zt||(ef=qT(Ct));const _y=L7(Ol.kind,pi,_m,hs,E,Iu,Rp,Mu,Ut,!0,pu,dh,0,or,Vr,rs,An,Wr?ef:xr,Ys.getProjection(),jl,ta,null,null,Mi),Op=Js.glyphAtlasTexture?Js.glyphAtlasTexture:null,WN=St.LINEAR,H0=w.paint.get("text-halo-width").constantOr(1)!==0,nb=E.terrain&&hs&&wi?o.ba(o.bd(),Nl):ow;if(wi&&Ys.text){const z6=o.bx.getAtTileOffsetFunc(or,Ct.center.lat,Ct.worldSize,Ys.getProjection()),$6=Ff(Ir,Js.tileID.canonical,hs,Zt,Ct,Ys.getProjection(),Rr);W_(Ys,Ir,E,!0,$6,Rc,hs,Ze,z6,or,Mi)}return{program:Qc,buffers:Ys.text,uniformValues:_y,atlasTexture:Op,atlasTextureIcon:uh,atlasInterpolation:WN,atlasInterpolationIcon:nc,isSDF:!0,hasHalo:H0,depthMode:Kd,tile:Js,renderWithShadows:Oa,labelPlaneMatrixInv:nb}},zi=Ys.icon.segments.get().length,ai=Ys.text.segments.get().length,sa=zi&&!V.onlyText?Ai():null,la=ai&&!V.onlyIcons?Li():null,$i=w.paint.get("icon-opacity").constantOr(1),Qo=w.paint.get("text-opacity").constantOr(1);if(ms&&Ys.canOverlap){Zs=!0;const wi=$i&&!V.onlyText?Ys.icon.segments.get():[],$n=Qo&&!V.onlyIcons?Ys.text.segments.get():[];for(const ho of wi)Rs.push({segments:new o.dB([ho]),sortKey:ho.sortKey,state:sa});for(const ho of $n)Rs.push({segments:new o.dB([ho]),sortKey:ho.sortKey,state:la})}else V.onlyText||Rs.push({segments:$i?Ys.icon.segments:new o.dB([]),sortKey:0,state:sa}),V.onlyIcons||Rs.push({segments:Qo?Ys.text.segments:new o.dB([]),sortKey:0,state:la})}Zs&&Rs.sort((or,Js)=>or.sortKey-Js.sortKey);for(const or of Rs){const Js=or.state;if(Js)if(E.terrain?E.terrain.setupElevationDraw(Js.tile,Js.program,{useDepthForOcclusion:Ct.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Js.labelPlaneMatrixInv}):E.setupDepthForOcclusion(Ct.depthOcclusionForSymbolsAndCircles,Js.program),Vt.activeTexture.set(St.TEXTURE0),Js.atlasTexture&&Js.atlasTexture.bind(Js.atlasInterpolation,St.CLAMP_TO_EDGE,!0),Js.atlasTextureIcon&&(Vt.activeTexture.set(St.TEXTURE1),Js.atlasTextureIcon&&Js.atlasTextureIcon.bind(Js.atlasInterpolationIcon,St.CLAMP_TO_EDGE,!0)),Js.renderWithShadows&&E.shadowRenderer.setupShadows(Js.tile.tileID.toUnwrapped(),Js.program,"vector-tile"),E.uploadCommonLightUniforms(E.context,Js.program),Js.hasHalo){const Ys=Js.uniformValues;Ys.u_is_halo=1,l6(Js.buffers,or.segments,w,E,Js.program,Js.depthMode,R,q,Ys,2),Ys.u_is_halo=0}else{if(Js.isSDF){const Ys=Js.uniformValues;Js.hasHalo&&(Ys.u_is_halo=1,l6(Js.buffers,or.segments,w,E,Js.program,Js.depthMode,R,q,Ys,1)),Ys.u_is_halo=0}l6(Js.buffers,or.segments,w,E,Js.program,Js.depthMode,R,q,Js.uniformValues,1)}}}function l6(E,f,w,I,R,q,V,Z,te,le){const pe=I.context,Ae=pe.gl,_e=[E.dynamicLayoutVertexBuffer,E.opacityVertexBuffer,E.iconTransitioningVertexBuffer,E.globeExtVertexBuffer,E.zOffsetVertexBuffer,E.orientationVertexBuffer];E.featureIdBuffer&&_e.push(E.featureIdBuffer);const Le=E.uboBinder?null:E.programConfigurations.get(w.id);if(E.uboBinder){E.uboBinder.layer=w;const Ze=I.transform.zoom,Xe=I.style.getBrightness?I.style.getBrightness():null,ht=E.uboBinder.getConstantUniformValues(Ze,Xe);te.u_spp_fill_np_color=ht.fill_np_color,te.u_spp_halo_np_color=ht.halo_np_color,te.u_spp_opacity=ht.opacity,te.u_spp_halo_width=ht.halo_width,te.u_spp_halo_blur=ht.halo_blur,te.u_spp_emissive_strength=ht.emissive_strength,te.u_spp_occlusion_opacity=ht.occlusion_opacity,te.u_spp_z_offset=ht.z_offset;const vt=w.paint.get(E.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),st=E.uboBinder.cachedHeader&&256&E.uboBinder.cachedHeader.dataDrivenMask&&vt==="map"?I.transform.angle:0;te.u_spp_translate_rotation=[Math.cos(st),Math.sin(st)]}const{batchIndices:Ve,batchSegments:qe}=E.getBatchGrouping(f);for(const Ze of Ve){const Xe=qe.get(Ze);E.uboBinder&&E.uboBinder.bind(pe,R.program,Ze),R.draw(I,Ae.TRIANGLES,q,V,Z,en.disabled,te,w.id,E.layoutVertexBuffer,E.indexBuffer,Xe,w.paint,I.transform.zoom,Le,_e,le)}}function fi(E,f,w,I,R,q){const V=w.paint.get("line-width"),Z=w.paint.get("line-emissive-strength").isConstant(),te=w.paint.get("line-emissive-strength").constantOr(0),le=w.paint.get("line-occlusion-opacity"),pe=w.layout.get("line-elevation-reference"),Ae=w.layout.get("line-width-unit")==="meters",_e=pe==="sea",Le=!(!E.terrain||!E.terrain.enabled),Ve=E.context,qe=Ve.gl;if(w.hasElevatedBuckets&&E.transform.projection.name==="globe")return;const Ze=w.layout.get("line-cross-slope"),Xe=Ze!==void 0,ht=Ze<1,vt=R||E.colorModeForDrapableLayerRenderPass(Z?te:null),st=E.terrain&&E.terrain.renderingToTexture||q,Ut=st?1:o.o.devicePixelRatio,Pt=w.paint.get("line-dasharray"),Vt=Pt.constantOr(1),St=w.layout.get("line-cap"),Ct=Pt.constantOr(null),qt=St.constantOr(null),Zt=w.paint.get("line-pattern"),Wt=Zt.constantOr(1),hs=w.paint.get("line-pattern-cross-fade"),ms=Zt.constantOr(null),Zs=w.paint.get("line-opacity").constantOr(1);let ts=!Wt&&Zs!==1||E.depthOcclusion&&le>0&&le<1;const Ns=w.paint.get("line-gradient"),rs=Wt?"linePattern":"line",Ps=o.dX(w);let Ms;if(st&&E.terrain&&E.terrain.clipOrMaskOverlapStencilType()&&(ts=!1),le!==0&&E.depthOcclusion){const Ys=w.paint._values["line-opacity"];Ys&&Ys.value&&Ys.value.kind==="constant"?Ms=Ys.value:o.w(`Occlusion opacity for layer ${w.id} is supported only when line-opacity isn't data-driven.`)}V.value.kind!=="constant"&&V.value.isLineProgressConstant===!1&&Ps.push("VARIABLE_LINE_WIDTH"),E._debugParams.showElevationIdDebug&&Ps.push("DEBUG_ELEVATION_ID"),st&&(E.emissiveMode!=="dual-source-blending"||Z?E.emissiveMode==="mrt-fallback"&&Ps.push("USE_MRT1"):Ps.push("DUAL_SOURCE_BLENDING"));const Rs={},xr=(Ys,Wr,Vr,Ir,Rr,mn)=>{for(const Ln of Ys){const An=f.getTile(Ln);if(Wt&&!An.patternsLoaded())continue;const ta=An.getBucket(w);if(!ta||ta.elevationType!=="none"&&!Rr||ta.elevationType==="none"&&Rr)continue;E.prepareDrawTile();const Tn=[...Wr],Ia=E.shadowRenderer,qn=ta.elevationType==="road"&&!!Ia&&Ia.enabled;let Ha=[0,0,0];if(qn){const Oa=E.style.directionalLight,jl=E.style.ambientLight;Oa&&jl&&(Ha=$1(E.style,Oa,jl)),Tn.push("RENDER_SHADOWS","NORMAL_OFFSET")}const Ai=ta.programConfigurations.get(w.id);let Li=!1;if(ms&&An.imageAtlas){const Oa=o.dY.from(ms),jl=Oa.getPrimary().scaleSelf(Ut).toString(),Kd=An.imageAtlas.patternPositions.get(jl),bc=Oa.getSecondary(),Qc=bc?An.imageAtlas.patternPositions.get(bc.scaleSelf(Ut).toString()):null;Li=!!Kd&&!!Qc,Kd&&Ai.setConstantPatternPositions(Kd,Qc)}hs>0&&(Li||Ai.getPatternTransitionVertexBuffer("line-pattern"))&&Tn.push("LINE_PATTERN_TRANSITION"),ta.elevationGroundScaleVertexBuffer&&Tn.push("ELEVATION_GROUND_SCALE");const zi=E.isTileAffectedByFog(Ln),ai=E.getOrCreateProgram(rs,{config:Ai,defines:Tn,overrideFog:zi});if(!Wt&&Ct&&qt&&An.lineAtlas){const Oa=An.lineAtlas.getDash(Ct,qt);Oa&&Ai.setConstantPatternPositions(Oa)}qn&&Ia.setupShadows(An.tileID.toUnwrapped(),ai,"vector-tile");let[sa,la]=w.paint.get("line-trim-offset");(qt==="round"||qt==="square")&&sa!==la&&(sa===0&&(sa-=1),la===1&&(la+=1));const $i=st?Ln.projMatrix:null,Qo=Ae?1/ta.tileToMeter/o.az(An,1,E.transform.zoom):1,wi=Ae?1/ta.tileToMeter/o.az(An,1,Math.floor(E.transform.zoom)):1,$n=Vt?w.paint._values["line-floorwidth"]:null;let ho;if($n&&$n.value.kind==="constant"){const Oa=ta.zoom;Oa in Rs||(Rs[Oa]=Math.max(.01,w.widthExpression().evaluate({zoom:Oa}))),ho=$n.value.value;const jl=Math.floor(E.transform.zoom);$n.value.value=Rs[Oa]*Math.pow(2,jl-An.tileID.overscaledZ)}const qi=Wt?o.dZ(E,An,w,$i,Ut,Qo,wi,[sa,la],Ha,hs):o.d_(E,An,w,$i,ta.lineClipsArray.length,Ut,Qo,wi,[sa,la],Ha);if(Ns){const Oa=ta.gradients[w.id];let jl=Oa.texture;if(w.gradientVersion!==Oa.version){let Kd=256;if(w.stepInterpolant){const bc=f.getSource().maxzoom,Qc=Ln.canonical.z===bc?Math.ceil(1<{Ms!=null&&(Ms.value=Zs*le),ai.draw(E,qe.TRIANGLES,Vr,Oa,vt,en.disabled,qi,w.id,ta.layoutVertexBuffer,ta.indexBuffer,ta.segments,w.paint,E.transform.zoom,Ai,[ta.layoutVertexBuffer2,ta.patternVertexBuffer,ta.zOffsetVertexBuffer,ta.elevationIdColVertexBuffer,ta.elevationGroundScaleVertexBuffer]),Ms!=null&&(Ms.value=Zs)};if(ts&&!Rr){const Oa=E.stencilModeForClipping(Ln).ref;Oa===0&&st&&Ve.clear({stencil:0});const jl={func:qe.EQUAL,mask:255};qi.u_alpha_discard_threshold=.8,cl(new kn(jl,Oa,255,qe.KEEP,qe.KEEP,qe.INVERT)),qi.u_alpha_discard_threshold=0,cl(new kn(jl,Oa,255,qe.KEEP,qe.KEEP,qe.KEEP))}else qi.u_alpha_discard_threshold=ts&&Rr&&mn?.8:0,cl(Rr?Ir:E.stencilModeForClipping(Ln));ho!==void 0&&($n.value.value=ho)}};let or=E.depthModeForSublayer(0,Br.ReadOnly);const Js=new Br(E.depthOcclusion?qe.GREATER:qe.LEQUAL,Br.ReadOnly,E.depthRangeFor3D);if(w.hasNonElevatedBuckets){const Ys=!st&&E.terrain;le!==0&&Ys?o.w(`Occlusion opacity for layer ${w.id} is supported on terrain only if the layer has line-z-offset enabled.`):Ys?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${w.id}.`):xr(I,Ps,or,kn.disabled,!1,!0)}if(w.hasElevatedBuckets){pe==="hd-road-markup"?Le||(or=Js,Ps.push("ELEVATED_ROADS")):(Ps.push("ELEVATED"),or=Js,Xe&&Ps.push(ht?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),_e&&Ps.push("ELEVATION_REFERENCE_SEA"));const Ys=ts?E.stencilModeFor3D():kn.disabled;E.forceTerrainMode=!0,xr(I,Ps,or,Ys,!0,!0),ts&&xr(I,Ps,or,Ys,!0,!1),E.forceTerrainMode=!1}ts&&(E.resetStencilClippingMasks(),st&&Ve.clear({stencil:0})),le===0||E.depthOcclusion||st||E.layersWithOcclusionOpacity.push(E.currentLayer)}class PN{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class c6{constructor(f){this.pbo=f.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(f){this.sync&&(f.deleteSync(this.sync),this.sync=null),f.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const LN={additive:{clearColor:new o.C(0,0,0,0),colorMode:En.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new o.C(1,1,1,1),colorMode:En.multiply,compositeUniformValue:0}};function DN(E){return!(!E.extRenderToTextureHalfFloat&&!E.extColorBufferFloat)}function VT(E,f){return E==="additive"&&DN(f)?En.additiveAlphaWeightedUnboundedAlpha:LN[E].colorMode}function HT(E,f,w){const I=E.context,R=I.gl;let q=w.width,V=w.height,Z=w.colorAttachment0.get();f.lineBlendDensityReadback||(f.lineBlendDensityReadback=new c6(R));const te=f.lineBlendDensityReadback;let le=0,pe=!0;for(;q>1||V>1;){const Le=Math.max(1,Math.floor(q/2)),Ve=Math.max(1,Math.floor(V/2)),qe=le===0?"fboA":"fboB";te[qe]=R0.createWithTexture(I,te[qe],Le,Ve,!1);const Ze=te[qe];I.bindFramebuffer.set(Ze.framebuffer),I.viewport.set([0,0,Le,Ve]),I.activeTexture.set(R.TEXTURE0),R.bindTexture(R.TEXTURE_2D,Z),E.getOrCreateProgram("lineBlendReduce").draw(E,R.TRIANGLES,Br.disabled,kn.disabled,En.unblended,en.disabled,E7(0,[1/q,1/V],pe),f.id,E.viewportBuffer,E.quadTriangleIndexBuffer,E.viewportSegments,f.paint,E.transform.zoom),q=Le,V=Ve,Z=Ze.colorAttachment0.get(),le=1-le,pe=!1}const Ae=DN(I),_e=Ae?16:4;te.sync&&(R.deleteSync(te.sync),te.sync=null),R.bindBuffer(R.PIXEL_PACK_BUFFER,te.pbo),R.bufferData(R.PIXEL_PACK_BUFFER,_e,R.STREAM_READ),R.readPixels(0,0,1,1,R.RGBA,Ae?R.FLOAT:R.UNSIGNED_BYTE,0),R.bindBuffer(R.PIXEL_PACK_BUFFER,null),te.sync=R.fenceSync(R.SYNC_GPU_COMMANDS_COMPLETE,0),I.viewport.set([0,0,E.width,E.height])}function O0(E,f,w){if(!DN(E.context))return;const I=f.lineBlendDensityReadback;I&&I.sync?(function(R,q,V){if(R.sync&&q.getSyncParameter(R.sync,q.SYNC_STATUS)===q.SIGNALED){if(q.deleteSync(R.sync),R.sync=null,q.bindBuffer(q.PIXEL_PACK_BUFFER,R.pbo),DN(V)){const Z=new Float32Array(4);q.getBufferSubData(q.PIXEL_PACK_BUFFER,0,Z);const te=Z[1];R.maxDensity=Math.max(2*(te>0?Z[0]/te:0),1)}else R.maxDensity=1;q.bindBuffer(q.PIXEL_PACK_BUFFER,null)}}(I,E.context.gl,E.context),I.sync||(HT(E,f,w),E.style.map.triggerRepaint())):(HT(E,f,w),E.style.map.triggerRepaint())}function py(E,f,w,I,R,q){const V=E.context,Z=V.gl,te=w==="additive"?1:f.paint.get("line-opacity").constantOr(1),le=w==="additive"?function(Ae,_e){const Le=_e.paint.get("line-blend-additive-clamp");if(Le>0)return Le;const Ve=_e.lineBlendDensityReadback;return Ve&&Ve.maxDensity!==0?Ve.maxDensity:null}(0,f):1;if(le===null)return;V.bindFramebuffer.set(R),q&&V.viewport.set([0,0,q[0],q[1]]),V.activeTexture.set(Z.TEXTURE0),Z.bindTexture(Z.TEXTURE_2D,I.colorAttachment0.get());const pe=VT(w,E.context);E.getOrCreateProgram("lineBlendComposite").draw(E,Z.TRIANGLES,Br.disabled,kn.disabled,pe,en.disabled,((Ae,_e,Le,Ve)=>({u_image:0,u_opacity:_e,u_blend_mode:Le,u_max_density:Ve}))(0,te,LN[w].compositeUniformValue,le),f.id,E.viewportBuffer,E.quadTriangleIndexBuffer,E.viewportSegments,f.paint,E.transform.zoom)}function rr(E,f){const w=1<=Km?1:Le.pitch/Km))),2*Ve}(E.transform),le=E.transform.getFreeCameraOptions().position,pe="elevatedStructuresDepthReconstruct",Ae=E.getOrCreateProgram(pe,{defines:["DEPTH_RECONSTRUCTION"]}),_e=E.getOrCreateProgram(pe);for(const Le of I){const Ve=f.getTile(Le),qe=Ve.getBucket(w);if(!qe)continue;const Ze=qe.elevatedStructures;if(!Ze||!Ze.depthSegments)continue;const Xe=qe.elevationBufferData.heightRange,ht=rr(Le.toUnwrapped(),le),vt=E.translatePosMatrix(Le.projMatrix,Ve,w.paint.get("fill-translate"),w.paint.get("fill-translate-anchor"));let st,Ut,Pt,Vt;if(R==="initialize"){if(!Xe||Xe.min>=1||Ze.depthSegments.segments[0].primitiveLength===0)continue;st=iw(vt,ht,te,1,0),Ut=V,Pt=Ze.depthSegments,Vt=Ae}else if(R==="reset"){if(!Xe||Xe.min>=0||Ze.maskSegments.segments[0].primitiveLength===0)continue;st=iw(vt,ht,0,0,1),Ut=Z,Pt=Ze.maskSegments,Vt=Ae}else if(R==="geometry"){if(Ze.depthSegments.segments[0].primitiveLength===0)continue;st=iw(vt,ht,te,1,0),Ut=V,Pt=Ze.depthSegments,Vt=_e}Vt.draw(E,q.TRIANGLES,Ut,kn.disabled,En.disabled,en.disabled,st,w.id,Ze.vertexBuffer,Ze.indexBuffer,Pt,w.paint,E.transform.zoom)}}function F0(E,f,w,I){const{painter:R,sourceCache:q,layer:V,coords:Z,colorMode:te,elevationType:le,terrainEnabled:pe,pass:Ae}=E,_e=R.context.gl,Le=V.paint.get("fill-pattern"),Ve=V.paint.get("fill-pattern-cross-fade"),qe=Le.constantOr(null);let Ze=le;le!=="road"||f&&!pe||(Ze="none");const Xe=Ze==="road",ht=E.painter.shadowRenderer,vt=Xe&&!!ht&&ht.enabled,st=new Br(R.context.gl.LEQUAL,Br.ReadOnly,R.depthRangeFor3D);let Ut=[0,0,0];if(vt){const Ct=R.style.directionalLight,qt=R.style.ambientLight;Ct&&qt&&(Ut=$1(R.style,Ct,qt))}const Pt=Le&&Le.constantOr(1),Vt=R.terrain&&R.terrain.renderingToTexture,St=(Ct,qt)=>{let Zt,Wt,hs,ms,Zs;qt?(Zt=Pt&&!V.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",hs=_e.LINES):(Zt=Pt?"fillPattern":"fill",hs=_e.TRIANGLES);for(const ts of Z){const Ns=q.getTile(ts);if(Pt&&!Ns.patternsLoaded())continue;const rs=Ns.getBucket(V);if(!rs)continue;const Ps=f?rs.elevationBufferData:rs.bufferData;if(Ps.isEmpty())continue;R.prepareDrawTile();const Ms=Ps.programConfigurations.get(V.id),Rs=R.isTileAffectedByFog(ts),xr=[],or=[];Xe&&(xr.push("ELEVATED_ROADS"),or.push(Ps.elevatedLayoutVertexBuffer)),vt&&xr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Vt&&w&&xr.push("USE_MRT1"),Pt&&(R.context.activeTexture.set(_e.TEXTURE0),Ns.imageAtlasTexture&&Ns.imageAtlasTexture.bind(_e.LINEAR,_e.CLAMP_TO_EDGE),Ms.updatePaintBuffers());let Js=!1;if(qe&&Ns.imageAtlas){const Rr=Ns.imageAtlas,mn=o.dY.from(qe),Ln=mn.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),An=mn.getSecondary(),ta=Rr.patternPositions.get(Ln),Tn=An?Rr.patternPositions.get(An.scaleSelf(o.o.devicePixelRatio).toString()):null;Js=!!ta&&!!Tn,ta&&Ms.setConstantPatternPositions(ta,Tn)}Ve>0&&(Js||Ms.getPatternTransitionVertexBuffer("fill-pattern"))&&xr.push("FILL_PATTERN_TRANSITION");const Ys=R.getOrCreateProgram(Zt,{config:Ms,overrideFog:Rs,defines:xr}),Wr=R.translatePosMatrix(ts.projMatrix,Ns,V.paint.get("fill-translate"),V.paint.get("fill-translate-anchor"));vt&&ht.setupShadows(Ns.tileID.toUnwrapped(),Ys,"vector-tile");const Vr=V.paint.get("fill-emissive-strength");if(qt){ms=Ps.lineIndexBuffer,Zs=Ps.lineSegments;const Rr=R.terrain&&R.terrain.renderingToTexture?R.terrain.drapeBufferSize:[_e.drawingBufferWidth,_e.drawingBufferHeight];Wt=Zt==="fillOutlinePattern"&&Pt?C7(Wr,Vr,R,Ns,Rr,Ut,Ve):S7(Wr,Vr,Rr,Ut)}else ms=Ps.indexBuffer,Zs=Ps.triangleSegments,Wt=Pt?JL(Wr,Vr,R,Ns,Ut,Ve):QL(Wr,Vr,Ut);R.uploadCommonUniforms(R.context,Ys,ts.toUnwrapped());let Ir=Ct;(le==="road"&&!pe||le==="offset")&&(Ir=st),Ys.draw(R,hs,Ir,I||R.stencilModeForClipping(ts),te,en.disabled,Wt,V.id,Ps.layoutVertexBuffer,ms,Zs,V.paint,R.transform.zoom,Ms,or)}};R.renderPass===Ae&&St(R.depthModeForSublayer(1,R.renderPass==="opaque"?Br.ReadWrite:Br.ReadOnly),!1),Ze==="none"&&R.renderPass==="translucent"&&V.paint.get("fill-antialias")&&St(R.depthModeForSublayer(V.getPaintProperty("fill-outline-color")?2:0,Br.ReadOnly),!0)}const ko=new Float32Array(16);function Yt(E,f,w,I,R,q,V,Z){w.resetLayerRenderingStats(E);const te=E.context,le=te.gl,pe=E.transform,Ae=w.paint.get("fill-extrusion-pattern"),_e=w.paint.get("fill-extrusion-pattern-cross-fade"),Le=Ae.constantOr(null),Ve=Ae.constantOr(1),qe=w.paint.get("fill-extrusion-opacity"),Ze=E.style.enable3dLights(),Xe=w.paint.get(Ze&&!Ve?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),ht=[w.paint.get("fill-extrusion-ambient-occlusion-intensity"),Xe],vt=w.layout.get("fill-extrusion-edge-radius"),st=vt>0&&!w.paint.get("fill-extrusion-rounded-roof"),Ut=st?0:vt,Pt=pe.projection.name==="globe"?o.e4():0,Vt=pe.projection.name==="globe",St=Vt?o.ai(pe.zoom):0,Ct=[o.aG(pe.center.lng),o.aJ(pe.center.lat)],qt=w.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Zt=w.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(qt?null:w.lut).toArray01().slice(0,3),Wt=w.paint.get("fill-extrusion-flood-light-intensity"),hs=w.paint.get("fill-extrusion-vertical-scale"),ms=w.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Zs=w.paint.get("fill-extrusion-height-alignment"),ts=w.paint.get("fill-extrusion-base-alignment"),Ns=Ym(E,w.paint.get("fill-extrusion-cutoff-fade-range")),rs=w.paint.get("fill-extrusion-front-cutoff"),Ps=lw(pe.pitch,rs,!!E.terrain),Ms=Ps[2]<1;Ms&&(E.maxFrontCutoffRawStart=Math.max(E.maxFrontCutoffRawStart,rs[0]));const Rs=[];let xr;Vt&&Rs.push("PROJECTION_GLOBE_VIEW"),ht[0]>0&&Rs.push("FAUX_AO"),st&&Rs.push("ZERO_ROOF_RADIUS"),Z&&Rs.push("HAS_CENTROID"),Wt>0&&Rs.push("FLOOD_LIGHT"),Ns.shouldRenderCutoff&&Rs.push("RENDER_CUTOFF"),Ms&&Rs.push("RENDER_FRONT_CUTOFF"),ms&&Rs.push("RENDER_WALL_MODE");const or=E.renderPass==="shadow",Js=E.shadowRenderer,Ys=or&&!!Js,Wr=or?en.disabled:en.backCCW;E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!0);let Vr=[0,0,0];if(Js){const mn=E.style.directionalLight,Ln=E.style.ambientLight;mn&&Ln&&(Vr=$1(E.style,mn,Ln)),or||(Rs.push("RENDER_SHADOWS"),Js.useNormalOffset&&Rs.push("NORMAL_OFFSET")),xr=Rs.concat(["SHADOWS_SINGLE_CASCADE"])}const Ir=Ys?"fillExtrusionDepth":Ve?"fillExtrusionPattern":"fillExtrusion",Rr=w.getLayerRenderingStats();for(const mn of I){const Ln=f.getTile(mn),An=Ln.getBucket(w);if(!An||An.projection.name!==pe.projection.name)continue;let ta=!1;Js&&(ta=Js.getMaxCascadeForTile(mn.toUnwrapped())===0);const Tn=E.isTileAffectedByFog(mn),Ia=An.programConfigurations.get(w.id);let qn=!1;if(Le&&Ln.imageAtlas){const la=Ln.imageAtlas,$i=o.dY.from(Le),Qo=$i.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),wi=$i.getSecondary(),$n=la.patternPositions.get(Qo),ho=wi?la.patternPositions.get(wi.scaleSelf(o.o.devicePixelRatio).toString()):null;qn=!!$n&&!!ho,$n&&Ia.setConstantPatternPositions($n,ho)}_e>0&&(qn||Ia.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Rs.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Ha=E.getOrCreateProgram(Ir,{config:Ia,defines:ta?xr:Rs,overrideFog:Tn});if(E.terrain&&E.terrain.setupElevationDraw(Ln,Ha,{useMeterToDem:!0}),!An.centroidVertexBuffer){const la=Ha.getAttributeLocation(le,"a_centroid_pos");la!==-1&&le.vertexAttribI4ui(la,0,0,0,0)}!or&&Js&&Js.setupShadows(Ln.tileID.toUnwrapped(),Ha,"vector-tile"),Ve&&(E.context.activeTexture.set(le.TEXTURE0),Ln.imageAtlasTexture&&Ln.imageAtlasTexture.bind(le.LINEAR,le.CLAMP_TO_EDGE),Ia.updatePaintBuffers());const Ai=w.paint.get("fill-extrusion-vertical-gradient"),Li=1/An.tileToMeter;let zi;if(or&&Js){if($7(Ln.tileID,An.maxHeight,E))continue;const la=Js.calculateShadowPassMatrixFromTile(Ln.tileID.toUnwrapped());zi=OT(la,Ut,Li,hs,Zs,ts)}else{const la=E.translatePosMatrix(mn.expandedProjMatrix,Ln,w.paint.get("fill-extrusion-translate"),w.paint.get("fill-extrusion-translate-anchor")),$i=pe.projection.createInversionMatrix(pe,mn.canonical);zi=Ve?k7(la,E,Ai,qe,ht,Ut,Li,mn,Ln,Pt,Zs,ts,St,Ct,$i,Zt,hs,_e):RT(la,E,Ai,qe,ht,Ut,Li,mn,Pt,Zs,ts,St,Ct,$i,Zt,hs,Wt,Vr,Ps)}E.uploadCommonUniforms(te,Ha,mn.toUnwrapped(),null,Ns);let ai=An.segments;if(pe.projection.name==="mercator"&&!or&&(ai=An.getVisibleSegments(Ln.tileID,E.terrain,E.transform.getFrustum(0)),!ai.get().length))continue;if(Rr)if(or)for(const la of ai.get())Rr.numRenderedVerticesInShadowPass+=la.primitiveLength;else for(const la of ai.get())Rr.numRenderedVerticesInTransparentPass+=la.primitiveLength;const sa=[];(E.terrain||Z)&&sa.push(An.centroidVertexBuffer),Vt&&sa.push(An.layoutVertexExtBuffer),ms&&sa.push(An.wallVertexBuffer),Ha.draw(E,te.gl.TRIANGLES,R,q,V,Wr,zi,w.id,An.layoutVertexBuffer,An.indexBuffer,ai,w.paint,E.transform.zoom,Ia,sa)}E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!1)}class d6{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function lw(E,f,w){if(!(f[2]<1)||w)return[0,0,1];const I=180*E/Math.PI;if(I<15)return[-.5,f[1],f[2]];const R=Math.min(1,Math.max(0,(I-15)/5)),q=R*R*(3-2*R);return[-.5*(1-q)+f[0]*q,f[1],f[2]]}function Lp(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht,vt,st){const Ut=f.context,Pt=Ut.gl,Vt=f.transform,St=f.transform.zoom,Ct=[],qt=E.translate,Zt=E.translateAnchor,Wt=E.edgeRadius,hs=Ym(f,E.cutoffFadeRange);pe==="clear"?(Ct.push("CLEAR_SUBPASS"),vt&&(Ct.push("CLEAR_FROM_TEXTURE"),Ut.activeTexture.set(Pt.TEXTURE0),vt.bind(Pt.LINEAR,Pt.CLAMP_TO_EDGE))):pe==="sdf"?Ct.push("SDF_SUBPASS"):pe==="emissive"&&(Ct.push("USE_MRT1"),Ut.activeTexture.set(Pt.TEXTURE0),vt.bind(Pt.LINEAR,Pt.CLAMP_TO_EDGE)),Xe&&Ct.push("HAS_CENTROID"),hs.shouldRenderCutoff&&Ct.push("RENDER_CUTOFF");const ms=(Zs,ts,Ns,rs,Ps)=>{let Ms=Ct;ts.groundRadiusBuffer!=null&&(Ms=Ct.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Rs=ts.programConfigurations.get(I.id),xr=f.isTileAffectedByFog(Zs),or=f.getOrCreateProgram("fillExtrusionGroundEffect",{config:Rs,defines:Ms,overrideFog:xr}),Js=((Wr,Vr,Ir,Rr,mn,Ln,An,ta,Tn,Ia,qn)=>({u_matrix:Vr,u_opacity:Ir,u_ao_pass:Rr?1:0,u_meter_to_tile:mn,u_ao:Ln,u_flood_light_intensity:An,u_flood_light_color:ta,u_attenuation:Tn,u_edge_radius:Ia,u_fb:0,u_fb_size:qn,u_dynamic_offset:1}))(0,rs,Ae,le,Ps,[_e,Le*Ps],Ve,qe,Ze,St>=17?0:Wt*Ps,vt?vt.size[0]:0),Ys=[];Xe&&Ys.push(ts.hiddenByLandmarkVertexBuffer),ts.groundRadiusBuffer!=null&&Ys.push(ts.groundRadiusBuffer),f.uploadCommonUniforms(Ut,or,Zs.toUnwrapped(),null,hs),or.draw(f,Ut.gl.TRIANGLES,q,V,Z,te,Js,I.id,ts.vertexBuffer,ts.indexBuffer,Ns,I.paint,St,Rs,Ys)};for(const Zs of R){const ts=w.getTile(Zs),Ns=ts.getBucket(I);if(!Ns||Ns.projection.name!==Vt.projection.name||!Ns.groundEffect||Ns.groundEffect&&!Ns.groundEffect.hasData())continue;const rs=Ns.groundEffect,Ps=1/Ns.tileToMeter;{const Ms=f.translatePosMatrix(Zs.projMatrix,ts,qt,Zt),Rs=rs.getDefaultSegment();ms(Zs,rs,Rs,Ms,Ps)}if(ht)for(let Ms=0;Ms<4;Ms++){const Rs=o.e2[Ms](Zs),xr=w.getTile(Rs);if(!xr)continue;const or=xr.getBucket(I);if(!or||or.projection.name!==Vt.projection.name||!or.groundEffect||or.groundEffect&&!or.groundEffect.hasData())continue;const Js=or.groundEffect;let Ys,Wr;Ms===0?(Ys=[-o.ak,0,0],Wr=1):Ms===1?(Ys=[o.ak,0,0],Wr=0):Ms===2?(Ys=[0,-o.ak,0],Wr=3):(Ys=[0,o.ak,0],Wr=2);const Vr=Js.regionSegments[Wr];Vr&&(o.bB(ko,Zs.projMatrix,Ys),ms(Zs,Js,Vr,f.translatePosMatrix(ko,ts,qt,Zt),Ps))}}}function GT(E,f,w,I,R,q,V){I.centroidVertexArray.length===0&&I.createCentroidsBuffer();const Z=q?q.findDEMTileFor(w):null;if(!(Z&&Z.dem||V))return;q&&Z&&Z.dem&&I.selfDEMTileTimestamp!==Z.dem._timestamp&&(I.borderDoneWithNeighborZ=[-1,-1,-1,-1],I.selfDEMTileTimestamp=Z.dem._timestamp);const te=(Xe,ht)=>{(Xe.flags|ht.flags)&o.e5?(Xe.flags|=o.e5,ht.flags|=o.e5):(Xe.flags&=~o.e5,ht.flags&=~o.e5)},le=Xe=>new o.P(Math.ceil((Xe+o.e6)*o.e7),0),pe=(Xe,ht,vt)=>{const st=Math.ceil((Xe+o.e6)*o.e7),Ut=Math.floor(Math.max(0,Math.min(o.ak-1,vt))/4);return new o.P(st,Ut<<5|(3&ht)<<3|7)},Ae=Xe=>{const ht=f.getSource().minzoom,vt=Ut=>{const Pt=f.getTileByID(Ut);if(Pt&&Pt.hasData())return Pt.getBucket(R)},st=[0,-1,1];for(const Ut of st){if(Xe.overscaledZ+Ut(_e[0]=Math.min(Xe.min.y,ht.min.y),_e[1]=Math.max(Xe.max.y,ht.max.y),_e[2]=o.ak-ht.min.x>Xe.max.x?ht.min.x-o.ak:Xe.max.x,_e),Ve=(Xe,ht)=>(_e[0]=Math.min(Xe.min.x,ht.min.x),_e[1]=Math.max(Xe.max.x,ht.max.x),_e[2]=o.ak-ht.min.y>Xe.max.y?ht.min.y-o.ak:Xe.max.y,_e),qe=[(Xe,ht)=>Le(Xe,ht),(Xe,ht)=>Le(ht,Xe),(Xe,ht)=>Ve(Xe,ht),(Xe,ht)=>Ve(ht,Xe)],Ze=(Xe,ht,vt,st,Ut,Pt,Vt)=>{if(!q)return 0;const St=[[Pt?vt:Xe,Pt?Xe:vt,0],[Pt?vt:ht,Pt?ht:vt,0]],Ct=Vt<0?o.ak+Vt:Vt,qt=[Pt?Ct:(Xe+ht)/2,Pt?(Xe+ht)/2:Ct,0];return vt===0&&Vt<0||vt!==0&&Vt>0?q.getForTilePoints(Ut,[qt],!0,st):St.push(qt),q.getForTilePoints(w,St,!0,Z),Math.max(St[0][2],St[1][2],qt[2])/q.exaggeration()};for(let Xe=0;Xe<4;Xe++){const ht=I.borderFeatureIndices[Xe];if(ht.length===0)continue;const vt=o.e2[Xe](w),st=Ae(vt);if(!(st&&st instanceof o.e3))continue;const Ut=q?q.findDEMTileFor(vt):null;if(!(Ut&&Ut.dem||V)||(q&&Ut&&Ut.dem&&I.borderDEMTileTimestamp[Xe]!==Ut.dem._timestamp&&(I.borderDoneWithNeighborZ[Xe]=-1,I.borderDEMTileTimestamp[Xe]=Ut.dem._timestamp),I.borderDoneWithNeighborZ[Xe]===st.canonical.z))continue;st.centroidVertexArray.length===0&&st.createCentroidsBuffer();const Pt=(Xe<2?1:5)-Xe,Vt=st.borderDoneWithNeighborZ[Pt]!==I.canonical.z,St=st.borderFeatureIndices[Pt];let Ct=0;if(I.canonical.z!==st.canonical.z){for(const hs of ht)I.showCentroid(I.featuresOnBorder[hs]);if(Vt)for(const hs of St)st.showCentroid(st.featuresOnBorder[hs]);I.borderDoneWithNeighborZ[Xe]=st.canonical.z,st.borderDoneWithNeighborZ[Pt]=I.canonical.z;continue}const qt=new Map,Zt=new Set,Wt=new Set;for(let hs=0;hs1||Ns.intersectsCount()>1;{let or=0;if(Ut&&Ut.dem&&!xr){const Js=qe[Xe](Zs,rs),Ys=Xe%2?o.ak-1:0;or=Ze(Js[0],Math.min(o.ak-1,Js[1]),Ys,Ut,vt,Xe<2,Js[2])}Zs.centroidXY=pe(or,Xe,Rs),rs.centroidXY=pe(or,Pt,Rs)}if(I.writeCentroidToBuffer(Zs),st.writeCentroidToBuffer(rs),ms.buildingId!==void 0){for(const or of I.centroidData)or.buildingId===ms.buildingId&&or!==Zs&&(or.centroidXY=Zs.centroidXY,I.writeCentroidToBuffer(or));for(const or of st.centroidData)or.buildingId===ms.buildingId&&or!==rs&&(or.centroidXY=rs.centroidXY,st.writeCentroidToBuffer(or))}}for(const hs of ht){if(Zt.has(hs))continue;const ms=I.featuresOnBorder[hs],Zs=I.centroidData.get(ms.centroidDataIndex),ts=ms.borders[Xe];let Ns;for(;Ctts[0]+3||rs[0]>ts[0]-3)break;st.showCentroid(Ns),Ct++}if(Ns&&Ctts[1]-3||(Ps++,++Ct===St.length))break;Ns=st.featuresOnBorder[St[Ct]]}for(;rs=St.length){I.showCentroid(ms);continue}Ns=st.featuresOnBorder[St[rs]];let Ms=!1;if(Ps>=1){const or=Ns.borders[Pt];Math.abs(ts[0]-or[0])<3&&Math.abs(ts[1]-or[1])<3&&(Ps=1,Ms=!0,Ct=rs+1)}else if(Ps===0){I.showCentroid(ms);continue}const Rs=st.centroidData.get(Ns.centroidDataIndex);V&&Ms&&te(Zs,Rs);const xr=ms.intersectsCount()>1||Ns.intersectsCount()>1;if(Ps>1)Ct=rs,Zs.centroidXY=Rs.centroidXY=new o.P(0,0);else if(Ut&&Ut.dem&&!xr){const or=qe[Xe](Zs,Rs),Js=Xe%2?o.ak-1:0,Ys=Ze(or[0],Math.min(o.ak-1,or[1]),Js,Ut,vt,Xe<2,or[2]);Zs.centroidXY=Rs.centroidXY=le(Ys)}else xr?Zs.centroidXY=Rs.centroidXY=new o.P(0,0):(Zs.centroidXY=I.encodeBorderCentroid(ms),Rs.centroidXY=st.encodeBorderCentroid(Ns));I.writeCentroidToBuffer(Zs),st.writeCentroidToBuffer(Rs)}else I.showCentroid(ms)}I.borderDoneWithNeighborZ[Xe]=st.canonical.z,st.borderDoneWithNeighborZ[Pt]=I.canonical.z}(I.needsCentroidUpdate||!I.centroidVertexBuffer&&I.centroidVertexArray.length!==0)&&I.uploadCentroid(E)}const B7=[1,0,0],z7=[0,1,0],cw=[0,0,1];function $7(E,f,w){const I=w.transform,R=w.shadowRenderer;if(!R)return!0;const q=w.frameCounter,V=w.currentShadowCascade;let Z=w._shadowCullCache;if(!Z||Z.frame!==q||Z.cascade!==V){const Xe=I.tileSize*R._cascades[V].scale,ht=I.scaleZoom(Xe),vt=R.shadowDirection,st=[vt[0],vt[1],-vt[2]],Ut=[B7,z7,cw,st,[st[0],0,st[2]],[0,st[1],st[2]]];Z={frame:q,cascade:V,cameraFrustum:o.cn.fromInvProjectionMatrix(I.invProjMatrix,I.worldSize,ht,I.projection.name!=="globe"),edges:Ut,shadowDir:st,ws:Xe,zoom:ht},w._shadowCullCache=Z}const{cameraFrustum:te,edges:le,shadowDir:pe,ws:Ae,zoom:_e}=Z;let Le=f;if(I.elevation){const Xe=I.elevation.getMinMaxForTile(E);Xe&&(Le+=Xe.max)}Le/=o.e8(I.center.lat,_e);const Ve=R.computeSimplifiedTileShadowVolume(E.toUnwrapped(),Le,Ae,pe);if(!Ve)return!1;const{vertices:qe,planes:Ze}=Ve;return te.intersectsPrecise(qe,Ze,le)===0||R.getCurrentCascadeFrustum().intersectsPrecise(qe,Ze,le)===0}const Tye=(E,f,w,I,R,q,V,Z,te,le=[0,0,1])=>({u_matrix:E,u_normal_matrix:f,u_opacity:w,u_faux_facade_ao_intensity:I,u_camera_pos:R,u_tile_to_meter:q,u_facade_emissive_chance:V,u_flood_light_color:Z,u_flood_light_intensity:te,u_front_cutoff_params:le}),U7=E=>({u_matrix:E}),WT=E=>({u_matrix:E}),KT=new Float32Array(16),W1=new Float32Array(16);function RN(E){const{painter:f,source:w,layer:I,coords:R}=E;let q=E.defines;const V=f.context,Z=f.renderPass==="shadow",te=f.renderPass==="light-beam",le=f.shadowRenderer,pe=o.e8(f.transform.center.lat,f.transform.zoom),Ae=Ym(f,I.paint.get("building-cutoff-fade-range"));Ae.shouldRenderCutoff&&(q=q.concat("RENDER_CUTOFF"));const _e=I.paint.get("building-front-cutoff"),Le=_e[2]<1&&!f.terrain,Ve=lw(f.transform.pitch,_e,!!f.terrain);Le&&(q=q.concat("RENDER_FRONT_CUTOFF"),f.maxFrontCutoffRawStart=Math.max(f.maxFrontCutoffRawStart,_e[0])),E.floodLightIntensity>0&&(q=q.concat("FLOOD_LIGHT"));for(const qe of R){const Ze=w.getTile(qe),Xe=Ze.getBucket(I);if(!Xe)continue;le&&le.getMaxCascadeForTile(qe.toUnwrapped())===0&&(q=q.concat("SHADOWS_SINGLE_CASCADE"));const ht=Xe.programConfigurations.get(I.id);let vt,st;const Ut=f.translatePosMatrix(qe.expandedProjMatrix,Ze,[0,0],"map");o.cE(KT,Ut,[1,1,E.verticalScale]);const Pt=KT;let Vt;if(Z&&le){if($7(Ze.tileID,Xe.maxHeight*pe,f))continue;const Ct=le.calculateShadowPassMatrixFromTile(Ze.tileID.toUnwrapped());o.cE(Ct,Ct,[1,1,E.verticalScale]),Vt=WT(Ct),vt=st=f.getOrCreateProgram("buildingDepth",{config:ht,defines:q,overrideFog:!1})}else if(te)vt=st=f.getOrCreateProgram("buildingBloom",{config:ht,defines:q,overrideFog:!1}),Vt=U7(Pt);else{const Ct=f.transform.calculatePosMatrix(qe.toUnwrapped(),f.transform.worldSize);o.cE(Ct,Ct,[1,1,E.verticalScale]),o.cE(W1,Ct,[1,-1,1/pe]),o.ba(W1,W1),o.e9(W1,W1);const qt=W1,Zt=f.transform.getFreeCameraOptions().position,Wt=1<{if(te){const Zt=Ct.entranceBloom;qt.draw(f,V.gl.TRIANGLES,E.depthMode,kn.disabled,E.blendMode,en.disabled,Vt,I.id,Zt.layoutVertexBuffer,Zt.indexBuffer,Zt.segmentsBucket,I.paint,f.transform.zoom,ht,[Zt.layoutAttenuationBuffer,Zt.layoutColorBuffer])}else{const Zt=Ct.segmentsBucket;let Wt=[Ct.layoutNormalBuffer,Ct.layoutCentroidBuffer,Ct.layoutColorBuffer,Ct.layoutFloodLightDataBuffer];Ct.layoutFacadePaintBuffer&&(Wt=Wt.concat([Ct.layoutFacadeDataBuffer,Ct.layoutFacadeVerticalRangeBuffer,Ct.layoutFacadePaintBuffer])),qt.draw(f,V.gl.TRIANGLES,E.depthMode,kn.disabled,E.blendMode,Z?en.disabled:en.backCW,Vt,I.id,Ct.layoutVertexBuffer,Ct.indexBuffer,Zt,I.paint,f.transform.zoom,ht,Wt)}};f.uploadCommonUniforms(V,st,qe.toUnwrapped(),null,Ae),Xe.buildingWithoutFacade&&St(Xe.buildingWithoutFacade,st),Xe.buildingWithFacade&&(vt!==st&&f.uploadCommonUniforms(V,vt,qe.toUnwrapped(),null,Ae),St(Xe.buildingWithFacade,vt))}}function ON(E,f,w,I,R,q,V,Z,te,le,pe,Ae,_e,Le){const Ve=E.context.gl,qe=E.depthModeForSublayer(1,Br.ReadOnly,Ve.LEQUAL,!0),Ze=.1*(1-(Xe=pe))+3*Xe;var Xe;const ht=E._showOverdrawInspector,vt=Ae,st=new d6;ht||Lp(st,E,f,w,I,qe,new kn({func:Ve.ALWAYS,mask:255},255,255,Ve.KEEP,Ve.KEEP,Ve.REPLACE),new En([Ve.ONE,Ve.ONE,Ve.ONE,Ve.ONE],o.C.transparent,[!1,!1,!1,!0],Ve.MIN),en.disabled,R,"sdf",q,V,Z,te,le,Ze,vt,!1,void 0);{const Ut=ht?kn.disabled:new kn({func:Ve.EQUAL,mask:255},255,255,Ve.KEEP,Ve.DECR,Ve.DECR),Pt=ht?E.colorModeForRenderPass():new En([Ve.ONE_MINUS_DST_ALPHA,Ve.DST_ALPHA,Ve.ONE,Ve.ONE],o.C.transparent,[!0,!0,!0,!0]);Lp(st,E,f,w,I,qe,Ut,Pt,en.disabled,R,"color",q,V,Z,te,le,Ze,vt,!1,void 0)}}const tg=.05,u6=(E,f,w,I,R,q,V,Z,te,le,pe,Ae)=>({u_matrix:E,u_normalize_matrix:f,u_globe_matrix:w,u_merc_matrix:I,u_grid_matrix:R,u_tl_parent:q,u_scale_parent:le,u_fade_t:pe.mix,u_opacity:pe.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ae,u_zoom_transition:V,u_merc_center:Z,u_cutoff_params:te}),q7=(E,f,w,I,R,q,V,Z,te,le)=>({u_particle_texture:E,u_particle_texture_side_len:f,u_tile_offset:w,u_velocity:I,u_color_ramp:q,u_velocity_res:R,u_max_speed:V,u_uv_offset:Z,u_data_scale:[255*te[0],255*te[1]],u_data_offset:le,u_particle_pos_scale:1.1,u_particle_pos_offset:[tg,tg]}),V7=(E,f,w,I,R,q,V,Z,te,le)=>({u_particle_texture:E,u_particle_texture_side_len:f,u_velocity:w,u_velocity_res:I,u_max_speed:R,u_speed_factor:q,u_reset_rate:V,u_rand_seed:Math.random(),u_uv_offset:Z,u_data_scale:[255*te[0],255*te[1]],u_data_offset:le,u_particle_pos_scale:1.1,u_particle_pos_offset:[tg,tg]});var H7=o.ea([{name:"a_index",type:"Int16",components:1}]);class G7{constructor(f,w,I,R){const q={width:I[0],height:I[1],data:null},V=f.gl;this.targetColorTexture=new o.T(f,q,V.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(f,q,V.RGBA8,{useMipmap:!1}),this.context=f,this.updateParticleTexture(w,R),this.lastInvalidatedAt=0}updateParticleTexture(f,w){if(this.particleTextureDimension===w.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const I=this.context.gl,R=w.width*w.height;this.particleTexture0=new o.T(this.context,w,I.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,w,I.RGBA8,{premultiply:!1,useMipmap:!1});const q=new o.eb;q.reserve(R);for(let V=0;V 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:ka(`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:ka("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),rasterParticle:ka(`#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:ka("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:ka("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:ka(`#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);}"),snowParticle:ka("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:ka("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:ka("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);}")};ka(h6,"");const lh=o.ea([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Mye=o.ea([{type:"Float32",name:"a_pos_2f",components:2}]);class FN{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(f,w){const I=f.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const V=new o.ee,Z=new o.dF;V.emplaceBack(-1,-1),V.emplaceBack(1,-1),V.emplaceBack(1,1),V.emplaceBack(-1,1),Z.emplaceBack(0,1,2),Z.emplaceBack(0,2,3),this.vignetteVx=f.context.createVertexBuffer(V,Mye.members),this.vignetteIdx=f.context.createIndexBuffer(Z)}const R=o.dB.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){f.uploadCommonUniforms(f.context,I);const V={u_vignetteShape:(q={vignetteShape:[w.start,w.range,Math.pow(10,w.fadePower)],vignetteColor:[w.color.r,w.color.g,w.color.b,w.color.a*w.strength]}).vignetteShape,u_vignetteColor:q.vignetteColor};I.draw(f,f.context.gl.TRIANGLES,Br.disabled,kn.disabled,En.alphaBlended,en.disabled,V,"vignette",this.vignetteVx,this.vignetteIdx,R)}var q}}class Iye{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(f,w){const I=f.getFreeCameraOptions().position,R=I.toAltitude(),q=I.toLngLat(),V=o.am(q.lng),Z=o.am(q.lat),te=f.pixelsPerMeter/w,le=V*o.eg,pe=o.eg*Math.log(Math.tan(Math.PI/4+Z/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 Ae=-this._offsetYPrev+pe,_e=-this._elevationPrev+R;this._accumulatedOffsetX+=(-this._offsetXPrev+le)*te,this._accumulatedOffsetY+=Ae*te,this._accumulatedElevation+=_e*te,this._offsetXPrev=le,this._offsetYPrev=pe,this._elevationPrev=R}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Ji(E,f){return[-(E[0]-Math.floor(E[0]/f)*f),-(E[1]-Math.floor(E[1]/f)*f),-(E[2]-Math.floor(E[2]/f)*f)]}function fa(E){const f=o.ef(1323123451230),w=[];for(let I=0;I({u_matrix:new o.c3(E),u_normal_matrix:new o.c3(E),u_opacity:new o.c1(E),u_faux_facade_ao_intensity:new o.c1(E),u_camera_pos:new o.c0(E),u_tile_to_meter:new o.c1(E),u_facade_emissive_chance:new o.c1(E),u_flood_light_color:new o.c0(E),u_flood_light_intensity:new o.c1(E),u_front_cutoff_params:new o.c0(E)}),buildingBloom:E=>({u_matrix:new o.c3(E)}),buildingDepth:E=>({u_matrix:new o.c3(E)}),rasterParticle:E=>({u_matrix:new o.c3(E),u_normalize_matrix:new o.c3(E),u_globe_matrix:new o.c3(E),u_merc_matrix:new o.c3(E),u_grid_matrix:new o.dq(E),u_tl_parent:new o.c2(E),u_scale_parent:new o.c1(E),u_fade_t:new o.c1(E),u_opacity:new o.c1(E),u_image0:new o.b$(E),u_image1:new o.b$(E),u_raster_elevation:new o.c1(E),u_zoom_transition:new o.c1(E),u_merc_center:new o.c2(E),u_cutoff_params:new o.cS(E)}),rasterParticleTexture:E=>({u_texture:new o.b$(E),u_opacity:new o.c1(E)}),rasterParticleDraw:E=>({u_particle_texture:new o.b$(E),u_particle_texture_side_len:new o.c1(E),u_tile_offset:new o.c2(E),u_velocity:new o.b$(E),u_color_ramp:new o.b$(E),u_velocity_res:new o.c2(E),u_max_speed:new o.c1(E),u_uv_offset:new o.c2(E),u_data_scale:new o.c2(E),u_data_offset:new o.c1(E),u_particle_pos_scale:new o.c1(E),u_particle_pos_offset:new o.c2(E)}),rasterParticleUpdate:E=>({u_particle_texture:new o.b$(E),u_particle_texture_side_len:new o.c1(E),u_velocity:new o.b$(E),u_velocity_res:new o.c2(E),u_max_speed:new o.c1(E),u_speed_factor:new o.c1(E),u_reset_rate:new o.c1(E),u_rand_seed:new o.c1(E),u_uv_offset:new o.c2(E),u_data_scale:new o.c2(E),u_data_offset:new o.c1(E),u_particle_pos_scale:new o.c1(E),u_particle_pos_offset:new o.c2(E)}),snowParticle:E=>({u_modelview:new o.c3(E),u_projection:new o.c3(E),u_time:new o.c1(E),u_cam_pos:new o.c0(E),u_velocityConeAperture:new o.c1(E),u_velocity:new o.c1(E),u_horizontalOscillationRadius:new o.c1(E),u_horizontalOscillationRate:new o.c1(E),u_boxSize:new o.c1(E),u_billboardSize:new o.c1(E),u_simpleShapeParameters:new o.c2(E),u_screenSize:new o.c2(E),u_thinningCenterPos:new o.c2(E),u_thinningShape:new o.c0(E),u_thinningAffectedRatio:new o.c1(E),u_thinningParticleOffset:new o.c1(E),u_particleColor:new o.cS(E),u_direction:new o.c0(E)}),rainParticle:E=>({u_modelview:new o.c3(E),u_projection:new o.c3(E),u_time:new o.c1(E),u_cam_pos:new o.c0(E),u_texScreen:new o.b$(E),u_velocityConeAperture:new o.c1(E),u_velocity:new o.c1(E),u_boxSize:new o.c1(E),u_rainDropletSize:new o.c2(E),u_distortionStrength:new o.c1(E),u_rainDirection:new o.c0(E),u_color:new o.cS(E),u_screenSize:new o.c2(E),u_thinningCenterPos:new o.c2(E),u_thinningShape:new o.c0(E),u_thinningAffectedRatio:new o.c1(E),u_thinningParticleOffset:new o.c1(E),u_shapeDirectionalPower:new o.c1(E),u_shapeNormalPower:new o.c1(E),u_mode:new o.c1(E)}),vignette:E=>({u_vignetteShape:new o.c0(E),u_vignetteColor:new o.cS(E)})},Wd={drawBuilding:function(E,f,w,I){E.currentLayer0&&q>0,le=!0;const pe=w.paint.get("building-vertical-scale");if(pe<=0)return;E.shadowRenderer||(le=!1);const Ae=E.conflationActive&&E.style.isLayerClipped(w,f.getSource()),_e=E.style.order.indexOf(w.fqid);if(function(Le,Ve,qe,Ze,Xe,ht){for(const vt of ht){const st=Ve.getTile(vt).getBucket(qe);st&&(Xe&&st.updateReplacement(vt,Le.replacementSource,Ze),st.uploadUpdatedIndexBuffer(Le.context))}}(E,f,w,_e,Ae,I),function(Le,Ve,qe,Ze){for(const Xe of Ze){const ht=Ve.getTile(Xe).getBucket(qe);ht&&ht.needsEvaluation()&&ht.uploadUpdatedColorBuffer(Le.context)}}(E,f,w,I),w.resetLayerRenderingStats(E),E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!0),E.renderPass==="shadow"&&E.shadowRenderer){const Le=[],Ve=E.shadowRenderer.getShadowPassDepthMode();RN({painter:E,source:f,layer:w,coords:I,defines:Le,blendMode:En.disabled,depthMode:Ve,opacity:Z,verticalScale:pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(E.renderPass==="translucent"){let Le=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];le&&(Le=Le.concat("RENDER_SHADOWS")),E.shadowRenderer&&E.shadowRenderer.useNormalOffset&&(Le=Le.concat("NORMAL_OFFSET"));const Ve=w.paint.get("building-facade-emissive-chance"),qe=w.paint.get("building-ambient-occlusion-intensity"),Ze=w.paint.get("building-flood-light-intensity"),Xe=w.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",ht=w.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(Xe?null:w.lut).toArray01().slice(0,3),vt=w.paint.get("building-flood-light-ground-attenuation"),st=Ze>0,Ut=new Br(E.context.gl.LEQUAL,Br.ReadWrite,E.depthRangeFor3D);Z<1&&RN({painter:E,source:f,layer:w,coords:I,defines:Le,blendMode:En.disabled,depthMode:Ut,opacity:Z,verticalScale:pe,facadeEmissiveChance:Ve,facadeAOIntensity:qe,floodLightIntensity:Ze,floodLightColor:ht,depthOnly:!0});const Pt=E.colorModeForRenderPass();RN({painter:E,source:f,layer:w,coords:I,defines:Le,blendMode:Pt,depthMode:Ut,opacity:Z,verticalScale:pe,facadeEmissiveChance:Ve,facadeAOIntensity:qe,floodLightIntensity:Ze,floodLightColor:ht});const Vt=w.paint.get("building-front-cutoff");lw(E.transform.pitch,Vt,!!E.terrain),te&&ON(E,f,w,I,!0,Z,R,q,Ze,ht,V,Ae),st&&ON(E,f,w,I,!1,Z,R,q,Ze,ht,vt,Ae)}else if(E.renderPass==="light-beam"){const Le=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],Ve=new Br(E.context.gl.LEQUAL,Br.ReadOnly,E.depthRangeFor3D);RN({painter:E,source:f,layer:w,coords:I,defines:Le,blendMode:En.alphaBlended,depthMode:Ve,opacity:Z,verticalScale:pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!1),E.resetStencilClippingMasks()},drawRasterParticle:function(E,f,w,I,R,q){E.renderPass==="offscreen"&&function(V,Z,te,le){if(!le.length)return;const pe=V.context,Ae=pe.gl,_e=Z.getSource();if(!(_e instanceof Jr))return;const Le=Math.ceil(Math.sqrt(te.paint.get("raster-particle-count")));let Ve=te.particlePositionRGBAImage;if(!Ve||Ve.width!==Le){const vt=function(st){const Ut=st*st,Pt=new Uint8Array(4*Ut),Vt=.9090909090909091;for(let St=0;Sto.e2[Ms](hs));Ns.push(hs);const rs=hs.canonical.x,Ps=hs.canonical.y;for(const Ms of Ns){const Rs=st.getTile(qt?Ms.wrapped():Ms);if(!Rs)continue;const xr=Rs.rasterParticleState;if(!xr)continue;const or=Ms.canonical.x+(1<f.getTileByID(Z));for(const Z of V)Z.updateNeeded(E.id,q)&&I.prepareTile(Z,R,E.id,q)},Rain:class extends zf{constructor(){super(4.25),this._params={intensity:.5,timeFactor:1,velocityConeAperture:0,velocity:300,boxSize:2500,dropletSizeX:1,dropletSizeYScale:10,distortionStrength:70,screenThinning:{intensity:.57,start:.46,range:1.17,fadePower:.17,affectedRatio:1,particleOffset:-.2},color:{r:.66,g:.68,b:.74,a:.7},direction:{x:-50,y:-35},shapeDirPower:2,shapeNormalPower:1},this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(E){const f=E.context;if(!this.particlesVx){const w=fa(this.particlesCount),I=new o.eh,R=new o.dF;let q=0;const V=o.ef(1323123451230);for(let Z=0;ZV)return;const Z=xy(0,1,I.revealStart,I.revealStart+I.revealRange,V);if(!this.particlesVx||!this.particlesIdx)return;q.strength*=Z;const te=this.updateOnRender(E,w.timeFactor),le=E.context,pe=le.gl,Ae=E.transform;this.screenTexture&&this.screenTexture.size[0]===E.width&&this.screenTexture.size[1]===E.height||(this.screenTexture=new o.T(le,{width:E.width,height:E.height,data:null},pe.RGBA8)),w.distortionStrength>0&&(le.activeTexture.set(pe.TEXTURE0),this.screenTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE),pe.copyTexSubImage2D(pe.TEXTURE_2D,0,0,0,0,0,E.width,E.height));const _e=E.getOrCreateProgram("rainParticle");E.uploadCommonUniforms(le,_e),le.activeTexture.set(pe.TEXTURE0),this.screenTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE);const Le=[w.color.r,w.color.g,w.color.b,w.color.a],Ve=(qe,Ze)=>{const Xe=Ji(this._movement.getPosition(),qe),ht=w.dropletSizeX,vt=w.dropletSizeX*w.dropletSizeYScale,st=E.width/2,Ut=E.height/2,Pt=xy(0,w.screenThinning.start,0,1,w.screenThinning.intensity),Vt=xy(.001,w.screenThinning.range,0,1,w.screenThinning.intensity),St=xy(0,w.screenThinning.particleOffset,0,1,w.screenThinning.intensity),Ct=(qt={modelview:te.modelviewMatrix,projection:te.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Xe,velocityConeAperture:w.velocityConeAperture,velocity:w.velocity,boxSize:qe,rainDropletSize:[ht,vt],distortionStrength:w.distortionStrength,rainDirection:R,color:Le,screenSize:[Ae.width,Ae.height],thinningCenterPos:[st,Ut],thinningShape:[Pt,Vt,Math.pow(10,w.screenThinning.fadePower)],thinningAffectedRatio:w.screenThinning.affectedRatio,thinningParticleOffset:St,shapeDirectionalPower:w.shapeDirPower,shapeNormalPower:w.shapeNormalPower,mode:Ze?0:1},{u_modelview:Float32Array.from(qt.modelview),u_projection:Float32Array.from(qt.projection),u_time:qt.time,u_cam_pos:qt.camPos,u_texScreen:0,u_velocityConeAperture:qt.velocityConeAperture,u_velocity:qt.velocity,u_boxSize:qt.boxSize,u_rainDropletSize:qt.rainDropletSize,u_distortionStrength:qt.distortionStrength,u_rainDirection:qt.rainDirection,u_color:qt.color,u_screenSize:qt.screenSize,u_thinningCenterPos:qt.thinningCenterPos,u_thinningShape:qt.thinningShape,u_thinningAffectedRatio:qt.thinningAffectedRatio,u_thinningParticleOffset:qt.thinningParticleOffset,u_shapeDirectionalPower:qt.shapeDirectionalPower,u_shapeNormalPower:qt.shapeNormalPower,u_mode:qt.mode});var qt;const Zt=Math.round(w.intensity*this.particlesCount),Wt=o.dB.simpleSegment(0,0,4*Zt,2*Zt);_e.draw(E,pe.TRIANGLES,Br.disabled,kn.disabled,En.alphaBlended,en.disabled,Ct,"rain_particles",this.particlesVx,this.particlesIdx,Wt)};w.distortionStrength>0&&Ve(w.boxSize,!0),Ve(w.boxSize,!1),this._vignette.draw(E,q)}},Snow:class extends zf{constructor(){super(2.25),this._params={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._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(E){const f=E.context;if(!this.particlesVx){const w=fa(this.particlesCount),I=new o.ei,R=new o.dF;let q=0;const V=o.ef(1323123451230);for(let Z=0;ZV)return;const Z=xy(0,1,I.revealStart,I.revealStart+I.revealRange,V);q.strength*=Z;const te=this.updateOnRender(E,w.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const le=E.context,pe=le.gl,Ae=E.transform,_e=E.getOrCreateProgram("snowParticle");E.uploadCommonUniforms(le,_e),((Le,Ve,qe)=>{const Ze=Ji(this._movement.getPosition(),Le),Xe=Ae.width/2,ht=Ae.height/2,vt=xy(0,qe.screenThinning.start,0,1,qe.screenThinning.intensity),st=xy(.001,qe.screenThinning.range,0,1,qe.screenThinning.intensity),Ut=xy(0,qe.screenThinning.particleOffset,0,1,qe.screenThinning.intensity),Pt=(Vt={modelview:te.modelviewMatrix,projection:te.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Ze,velocityConeAperture:qe.velocityConeAperture,velocity:qe.velocity,horizontalOscillationRadius:qe.horizontalOscillationRadius,horizontalOscillationRate:qe.horizontalOscillationRate,boxSize:Le,billboardSize:1*qe.billboardSize,simpleShapeParameters:[qe.shapeFadeStart,qe.shapeFadePower],screenSize:[Ae.width,Ae.height],thinningCenterPos:[Xe,ht],thinningShape:[vt,st,Math.pow(10,qe.screenThinning.fadePower)],thinningAffectedRatio:qe.screenThinning.affectedRatio,thinningParticleOffset:Ut,color:[qe.color.r,qe.color.g,qe.color.b,qe.color.a],direction:R},{u_modelview:Float32Array.from(Vt.modelview),u_projection:Float32Array.from(Vt.projection),u_time:Vt.time,u_cam_pos:Vt.camPos,u_velocityConeAperture:Vt.velocityConeAperture,u_velocity:Vt.velocity,u_horizontalOscillationRadius:Vt.horizontalOscillationRadius,u_horizontalOscillationRate:Vt.horizontalOscillationRate,u_boxSize:Vt.boxSize,u_billboardSize:Vt.billboardSize,u_simpleShapeParameters:Vt.simpleShapeParameters,u_screenSize:Vt.screenSize,u_thinningCenterPos:Vt.thinningCenterPos,u_thinningShape:Vt.thinningShape,u_thinningAffectedRatio:Vt.thinningAffectedRatio,u_thinningParticleOffset:Vt.thinningParticleOffset,u_particleColor:Vt.color,u_direction:Vt.direction});var Vt;const St=Math.round(qe.intensity*this.particlesCount),Ct=o.dB.simpleSegment(0,0,4*St,2*St);this.particlesVx&&this.particlesIdx&&_e.draw(E,pe.TRIANGLES,Br.disabled,kn.disabled,En.alphaBlended,en.disabled,Pt,"snow_particles",this.particlesVx,this.particlesIdx,Ct)})(w.boxSize,0,w),this._vignette.draw(E,q)}},shaders:Aye,programUniforms:Y1};function YT(E){return[E[0]*o.ej,E[1]*o.ej,E[2]*o.ej,0]}function BN(E,f,w,I,R,q,V,Z,te){const le=I.getSource(),pe=w.globeSharedBuffers;if(!pe)return;let Ae,_e,Le;if(f&&(Ae=I.getTile(f)),le instanceof o.aY?(_e=le.texture,Le=o.dz(0,0,w.transform)):Ae&&f&&(_e=Ae.texture,Le=o.dz(f.canonical.z,f.canonical.x,w.transform)),!_e||!Le)return;E||(Le=o.cE(o.bd(),Le,[1,-1,1]));const Ve=w.context,qe=Ve.gl,Ze=R.paint.get("raster-resampling")==="nearest"?qe.NEAREST:qe.LINEAR,Xe=w.colorModeForDrapableLayerRenderPass(q),ht=V.defines;ht.push("GLOBE_POLES");const vt=new Br(qe.LEQUAL,Br.ReadWrite,w.depthRangeFor3D),st=w.transform.expandedFarZProjMatrix,Ut=Float32Array.from(o.dx(o.dy(new o.cp(0,0,0))));w.terrain&&w.terrain.prepareDrawTile(),Ve.activeTexture.set(qe.TEXTURE0),_e.bind(Ze,qe.CLAMP_TO_EDGE),Ve.activeTexture.set(qe.TEXTURE1),_e.bind(Ze,qe.CLAMP_TO_EDGE),"useMipmap"in _e&&Ve.extTextureFilterAnisotropic&&w.transform.pitch>20&&qe.texParameterf(qe.TEXTURE_2D,Ve.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ve.extTextureFilterAnisotropicMax);const[Pt,Vt,St,Ct]=f?pe.getPoleBuffers(f.canonical.z,!1):pe.getPoleBuffers(0,!0),qt=R.paint.get("raster-elevation");let Zt;E?(Zt=Pt,w.renderDefaultNorthPole=qt!==0):(Zt=Vt,w.renderDefaultSouthPole=qt!==0);const Wt=YT(V.mix),hs=((Zs,ts,Ns,rs,Ps,Ms,Rs,xr,or,Js,Ys,Wr,Vr,Ir)=>zT(Zs,ts,Ns,rs,new Float32Array(16),new Float32Array(9),[0,0],Ps,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Rs,[0,0],or,2,Ys,Wr,Vr,1,0,Ir))(w,st,Ut,Le,o.ai(w.transform.zoom),0,R,0,qt,0,Wt,V.offset,V.range,q),ms=w.getOrCreateProgram("raster",{defines:ht});w.uploadCommonUniforms(Ve,ms,null),ms.draw(w,qe.TRIANGLES,vt,te,Xe,Z,hs,R.id,Zt,St,Ct)}function m6(E){if(E.isOrthographic)return[0,0,0,0];const f=E._nearZ,w=E.projection.farthestPixelDistance(E),I=w-f,R=.2*E.height,q=f+R;return[f,w,(q-R-f)/I,(q-f)/I]}function f6(E,f,w,I){if(E)return f instanceof Jr&&E instanceof E0?f.getTextureDescriptor(E,w,!0):{texture:E.texture,mix:YT(I.mix),offset:I.offset,buffer:0,tileSize:1}}const p6=o.bA(new Float32Array(16)),Zm=new o.C(1,0,0,1),B0=new o.C(0,1,0,1),dw=new o.C(0,0,1,1),ZT=new o.C(1,0,1,1),x6=new o.C(0,1,1,1);function g6(E,f,w,I,R,q,V){const Z=E.context,te=E.transform,le=Z.gl,pe=te.projection.name==="globe",Ae=pe?["PROJECTION_GLOBE_VIEW"]:[];let _e=o.bb(w.projMatrix);if(pe&&o.ai(te.zoom)>0){const Wt=o.ek(w.canonical,te),hs=o.el(Wt);_e=o.aC(new Float32Array(16),te.globeMatrix,hs),o.aC(_e,te.projMatrix,_e)}const Le=o.bd();Le[12]+=2*R/(o.o.devicePixelRatio*te.width),Le[13]+=2*q/(o.o.devicePixelRatio*te.height),o.aC(_e,Le,_e);const Ve=E.getOrCreateProgram("debug",{defines:Ae}),qe=f.getTileByID(w.key);E.terrain&&E.terrain.setupElevationDraw(qe,Ve);const Ze=Br.disabled,Xe=kn.disabled,ht=E.colorModeForRenderPass(),vt="$debug";Z.activeTexture.set(le.TEXTURE0),E.emptyTexture.bind(le.LINEAR,le.CLAMP_TO_EDGE),pe?qe._makeGlobeTileDebugBuffers(E.context,te):qe._makeDebugTileBoundsBuffers(E.context,te.projection);const st=qe._tileDebugBuffer||E.debugBuffer,Ut=qe._tileDebugIndexBuffer||E.debugIndexBuffer,Pt=qe._tileDebugSegments||E.debugSegments;if(Ve.draw(E,le.LINE_STRIP,Ze,Xe,ht,en.disabled,FT(_e,I.toPremultipliedRenderColor(null)),vt,st,Ut,Pt,null,null,null,[qe._globeTileDebugBorderBuffer]),V){const Wt=qe.latestRawTileData,hs=Math.floor((Wt&&Wt.byteLength||0)/1024);let ms=w.canonical.toString();w.overscaledZ!==w.canonical.z&&(ms+=` => ${w.overscaledZ}`),ms+=` ${qe.state}`,ms+=` ${hs}kb`,function(Zs,ts){Zs.initDebugOverlayCanvas();const Ns=Zs.debugOverlayCanvas,rs=Zs.context.gl,Ps=Zs.debugOverlayCanvas.getContext("2d");Ps.clearRect(0,0,Ns.width,Ns.height),Ps.shadowColor="white",Ps.shadowBlur=2,Ps.lineWidth=1.5,Ps.strokeStyle="white",Ps.textBaseline="top",Ps.font="bold 36px Open Sans, sans-serif",Ps.fillText(ts,5,5),Ps.strokeText(ts,5,5),Zs.debugOverlayTexture.update(Ns),Zs.debugOverlayTexture.bind(rs.LINEAR,rs.CLAMP_TO_EDGE)}(E,ms)}const Vt=f.getTile(w).tileSize,St=512/Math.min(Vt,512)*(w.overscaledZ/te.zoom)*.5,Ct=qe._tileDebugTextBuffer||E.debugBuffer,qt=qe._tileDebugTextIndexBuffer||E.quadTriangleIndexBuffer,Zt=qe._tileDebugTextSegments||E.debugSegments;Ve.draw(E,le.TRIANGLES,Ze,Xe,En.alphaBlended,en.disabled,FT(_e,o.C.transparent.toPremultipliedRenderColor(null),St),vt,Ct,qt,Zt,null,null,null,[qe._globeTileDebugTextBuffer])}function gy(E,f,w,I){Bh(E,0,f+w/2,E.transform.width,w,I)}function XT(E,f,w,I){Bh(E,f-w/2,0,w,E.transform.height,I)}function Bh(E,f,w,I,R,q){const V=E.context,Z=V.gl;Z.enable(Z.SCISSOR_TEST),Z.scissor(f*o.o.devicePixelRatio,w*o.o.devicePixelRatio,I*o.o.devicePixelRatio,R*o.o.devicePixelRatio),V.clear({color:q}),Z.disable(Z.SCISSOR_TEST)}const y6=o.ea([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:QT}=y6;function sg(E,f,w,I){E.emplaceBack(f,w,I)}class JT{constructor(f){this.vertexArray=new o.em,this.indices=new o.dF,sg(this.vertexArray,-1,-1,1),sg(this.vertexArray,1,-1,1),sg(this.vertexArray,-1,1,1),sg(this.vertexArray,1,1,1),sg(this.vertexArray,-1,-1,-1),sg(this.vertexArray,1,-1,-1),sg(this.vertexArray,-1,1,-1),sg(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=f.createVertexBuffer(this.vertexArray,QT),this.indexBuffer=f.createIndexBuffer(this.indices),this.segment=o.dB.simpleSegment(0,0,36,12)}}function Go(E,f,w,I,R,q){const V=E.context.gl,Z=f.paint.get("sky-atmosphere-color"),te=f.paint.get("sky-atmosphere-halo-color"),le=f.paint.get("sky-atmosphere-sun-intensity"),pe=((Ae,_e,Le,Ve,qe)=>({u_matrix_3f:Ae,u_sun_direction:_e,u_sun_intensity:Le,u_color_tint_r:[Ve.r,Ve.g,Ve.b,Ve.a],u_color_tint_m:[qe.r,qe.g,qe.b,qe.a],u_luminance:5e-5}))(o.ep(o.dH(),I),R,le,Z.toPremultipliedRenderColor(null),te.toPremultipliedRenderColor(null));V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_CUBE_MAP_POSITIVE_X+q,f.skyboxTexture,0),w.draw(E,V.TRIANGLES,Br.disabled,kn.disabled,En.unblended,en.frontCW,pe,"skyboxCapture",f.skyboxGeometry.vertexBuffer,f.skyboxGeometry.indexBuffer,f.skyboxGeometry.segment)}const v6=o.ea([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class b6{constructor(f){const w=new o.eq;w.emplaceBack(-1,1,1,0,0),w.emplaceBack(1,1,1,1,0),w.emplaceBack(1,-1,1,1,1),w.emplaceBack(-1,-1,1,0,1);const I=new o.dF;I.emplaceBack(0,1,2),I.emplaceBack(2,3,0),this.vertexBuffer=f.createVertexBuffer(w,v6.members),this.indexBuffer=f.createIndexBuffer(I),this.segments=o.dB.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const _6=o.ea([{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 Z1{constructor(){this.colorModeAlphaBlendedWriteRGB=new En([1,Qx,1,Qx],o.C.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new En([1,0,1,0],o.C.transparent,[!1,!1,!1,!0]),this.params={starsCount:16e3,sizeMultiplier:.15,sizeRange:100,intensityRange:200},this.updateNeeded=!0,this._painter=null,this._devtoolsFolder=null}update(f){this._painter=f;const w=f.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new b6(w);let I=this.params;const R=I.sizeRange,q=I.intensityRange,V=function(Ae){const _e=o.ef(30),Le=[];for(let Ve=0;Ve{const St=q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Vt&&St.push("ALPHA_PASS");const Ct=f.getOrCreateProgram("globeAtmosphere",{defines:St}),qt=((Wt,hs,ms,Zs,ts,Ns,rs,Ps,Ms,Rs,xr,or)=>({u_frustum_tl:Wt,u_frustum_tr:hs,u_frustum_br:ms,u_frustum_bl:Zs,u_horizon:ts,u_transition:Ns,u_fadeout_range:rs,u_atmosphere_fog_color:Ps.toArray01(),u_high_color:Ms.toArray01(),u_space_color:Rs.toArray01(),u_temporal_offset:xr,u_horizon_angle:or}))(q.frustumCorners.TL,q.frustumCorners.TR,q.frustumCorners.BR,q.frustumCorners.BL,q.frustumCorners.horizon,Z,Ze,pe,_e,Ve,ht,Ut);f.uploadCommonUniforms(I,Ct);const Zt=this.atmosphereBuffer;Zt&&Ct.draw(f,R.TRIANGLES,V,kn.disabled,Vt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,en.backCW,qt,Vt?"atmosphere_glow_alpha":"atmosphere_glow",Zt.vertexBuffer,Zt.indexBuffer,Zt.segments)};Pt(!1),Pt(!0)}drawStars(f,w){const I=o.aB(w.properties.get("star-intensity"),0,1);if(I===0)return;const R=f.context,q=R.gl,V=f.transform,Z=f.getOrCreateProgram("stars"),te=o.bP([]);o.bR(te,te,-V._pitch),o.bQ(te,te,-V.angle),o.bR(te,te,o.am(V._center.lat)),o.et(te,te,-o.am(V._center.lng));const le=o.bV(new Float32Array(16),te),pe=o.aC([],V.starsProjMatrix,le),Ae=o.ep([],le),_e=o.eu([],Ae);let Le=this.params.sizeMultiplier;const Ve=[0,1,0];o.dJ(Ve,Ve,_e),o.bN(Ve,Ve,Le);const qe=[1,0,0];o.dJ(qe,qe,_e),o.bN(qe,qe,Le);const Ze=(Xe=Ve,ht=qe,vt=I,{u_matrix:Float32Array.from(pe),u_up:Xe,u_right:ht,u_intensity_multiplier:vt});var Xe,ht,vt;f.uploadCommonUniforms(R,Z),this.starsVx&&this.starsIdx&&Z.draw(f,q.TRIANGLES,Br.disabled,kn.disabled,this.colorModeAlphaBlendedWriteRGB,en.disabled,Ze,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class w6{constructor(){this.visibleTiles=[]}updateBorders(f,w){const I=[],R=[],q=f._getRenderableCoordinates(!1,!0);for(const te of q){const le=f.getTile(te);if(!le.hasData())continue;const pe=le.getBucket(w);pe&&(pe.isEmpty()||(I.push(te.key),R.push({bucket:pe,tileID:te.canonical})))}let V=I.length!==this.visibleTiles.length;if(!V){I.sort();for(let te=0;tete.tileID.z-le.tileID.z||te.tileID.x-le.tileID.x||te.tileID.y-le.tileID.y);for(const te of R){const le=new Array,pe=new Array,Ae=te.bucket;for(const _e of Ae.featuresOnBorder)Z.has(_e.featureId)?pe.push(_e.footprintIndex):(Z.add(_e.featureId),le.push(_e.footprintIndex));Ae.updateFootprintHiddenFlags(le,o.ev,!1),Ae.updateFootprintHiddenFlags(pe,o.ev,!0)}}}const zh=new Float64Array(16),$f=new Float64Array(16),z0=new Float64Array(16),j6=new Float32Array(16),yy=[0,0,0];function eE(E,f,w){const I=w.cameraWorldSizeForFog/w.worldSize;return o.cE(E,w.worldToFogMatrix,[I,I,1]),o.aC(E,E,f),E}function X1(E,f,w,I,R){const q=w.material,V=I.context,{baseColorTexture:Z,metallicRoughnessTexture:te}=q.pbrMetallicRoughness,{normalTexture:le,occlusionTexture:pe,emissionTexture:Ae}=q;function _e(Ve,qe,Ze){if(Ve&&(E.push(qe),V.activeTexture.set(V.gl.TEXTURE0+Ze),Ve.gfxTexture)){const{minFilter:Xe,magFilter:ht,wrapS:vt,wrapT:st}=Ve.sampler;Ve.gfxTexture.bindExtraParam(Xe,ht,vt,st)}}_e(Z,"HAS_TEXTURE_u_baseColorTexture",5),_e(te,"HAS_TEXTURE_u_metallicRoughnessTexture",6),_e(le,"HAS_TEXTURE_u_normalTexture",7),_e(pe,"HAS_TEXTURE_u_occlusionTexture",8),_e(Ae,"HAS_TEXTURE_u_emissionTexture",9),R&&(R.texture||(R.texture=new o.dU(I.context,R.image,[R.image.height,R.image.height,R.image.height],V.gl.RGBA8)),V.activeTexture.set(V.gl.TEXTURE0+10),R.texture&&R.texture.bind(V.gl.LINEAR,V.gl.CLAMP_TO_EDGE),E.push("APPLY_LUT_ON_GPU")),w.texcoordBuffer&&(E.push("HAS_ATTRIBUTE_a_uv_2f"),f.push(w.texcoordBuffer)),w.colorBuffer&&(E.push(w.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),f.push(w.colorBuffer)),w.normalBuffer&&(E.push("HAS_ATTRIBUTE_a_normal_3f"),f.push(w.normalBuffer)),w.pbrBuffer&&(E.push("HAS_ATTRIBUTE_a_pbr"),E.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),f.push(w.pbrBuffer)),q.alphaMode!=="OPAQUE"&&q.alphaMode!=="MASK"||E.push("UNPREMULT_TEXTURE_IN_SHADER"),q.defined||E.push("DIFFUSE_SHADED");const Le=I.shadowRenderer;Le&&(E.push("RENDER_SHADOWS"),Le.useNormalOffset&&E.push("NORMAL_OFFSET"))}function uw(E,f,w,I,R,q){const V=E.modelOpacity,Z=f.context,te=new Br(f.context.gl.LEQUAL,E.isLightMesh?Br.ReadOnly:Br.ReadWrite,f.depthRangeFor3D),le=f.transform,pe=E.mesh,Ae=pe.material,_e=Ae.pbrMetallicRoughness,Le=f.style.fog;f.transform.projection.zAxisUnit==="pixels"?zh.set(E.nodeModelMatrix):o.aC(zh,I.zScaleMatrix,E.nodeModelMatrix),o.aC(zh,I.negCameraPosMatrix,zh),o.ba($f,zh),o.e9($f,$f);const Ve=w.paint.get("model-color-use-theme").constantOr("default")==="none",qe=w.paint.get("model-emissive-strength").constantOr(0),Ze=UT(E.worldViewProjection,zh,$f,null,f,V,_e.baseColorFactor,Ae.emissiveFactor,_e.metallicFactor,_e.roughnessFactor,Ae,qe,w,void 0,void 0,E.materialOverride,E.modelColor),Xe={defines:[]},ht=[],vt=f.shadowRenderer;vt&&(vt.useNormalOffset=!1),X1(Xe.defines,ht,pe,f,Ve?null:w.lut);let st=null;if(Le&&(st=eE(z0,E.nodeModelMatrix,f.transform),le.projection.name!=="globe")){const Vt=pe.aabb.min,St=pe.aabb.max,[Ct,qt]=Le.getOpacityForBounds(st,Vt[0],Vt[1],St[0],St[1]);Xe.overrideFog=Ct>=Sp||qt>=Sp}const Ut=Ym(f,w.paint.get("model-cutoff-fade-range"));Ut.shouldRenderCutoff&&Xe.defines.push("RENDER_CUTOFF");const Pt=f.getOrCreateProgram("model",Xe);f.uploadCommonUniforms(Z,Pt,null,st,Ut),f.renderPass!=="shadow"&&vt&&vt.setupShadowsFromMatrix(E.nodeModelMatrix,Pt),Pt.draw(f,Z.gl.TRIANGLES,te,R,q,pe.material.doubleSided?en.disabled:en.backCCW,Ze,w.id,pe.vertexBuffer,pe.indexBuffer,pe.segments,w.paint,f.transform.zoom,void 0,ht)}function zN(E,f){return E.style._importedAsBasemap?"basemap":f.scope}function tE(E,f,w,I,R,q,V,Z,te,le){const pe=E.transform,Ae=!!f.isGeometryBloom&&f.isGeometryBloom;if(Ae&&E.renderPass==="shadow")return;const _e=pe.projection.name==="globe"?o.eD(w,pe):[...w];o.aC(_e,_e,f.globalMatrix);const Le=o.aC([],I,_e);if(f.meshes)for(const Ve of f.meshes){const qe=Z.get(Ve.material.name);if(qe&&qe.opacity<=0)continue;if(Ve.material.alphaMode!=="BLEND"){V.push({mesh:Ve,depth:0,modelIndex:R,worldViewProjection:Le,nodeModelMatrix:_e,isLightMesh:Ae,materialOverride:qe,modelOpacity:te,modelColor:le,node:f,modelMatrix:w});continue}const Ze=o.ae([],Ve.centroid,Le);!pe.isOrthographic&&Ze[2]<=0||q.push({mesh:Ve,depth:Ze[2],modelIndex:R,worldViewProjection:Le,nodeModelMatrix:_e,isLightMesh:Ae,materialOverride:qe,modelOpacity:te,modelColor:le,node:f,modelMatrix:w})}if(f.children)for(const Ve of f.children)tE(E,Ve,w,I,R,q,V,Z,te,le)}function Q1(E,f,w,I){const R=w.shadowRenderer;if(!R)return;const q=R.getShadowPassDepthMode(),V=R.calculateShadowPassMatrixFromMatrix(f),Z=R7(V);w.getOrCreateProgram("modelDepth").draw(w,w.context.gl.TRIANGLES,q,kn.disabled,En.disabled,en.disabled,Z,I.id,E.vertexBuffer,E.indexBuffer,E.segments,I.paint,w.transform.zoom,void 0,void 0)}function N6(E,f,w,I){const R=function(pe,Ae){if(Ae.footprintDebugMesh)return Ae.footprintDebugMesh;if(!Ae.footprint)return null;const _e=pe.context,Le=Ae.footprint.vertices,Ve=Ae.footprint.indices,qe=new o.dE;qe.reserve(Le.length);for(const qt of Le)qe.emplaceBack(qt.x,qt.y);const Ze=new o.dF;Ze.reserve(Ve.length);for(let qt=0;qt0){const _e=q.terrain,Le=_e.findDEMTileFor(Z);Le&&Le.dem?te=o.eF.create(_e,Z,Le):Ae=0}if(Ae===0&&(V.terrainElevationMin=0,V.terrainElevationMax=0),Ae===V.validForExaggeration&&(Ae===0||te&&te._demTile&&te._demTile.tileID===V.validForDEMTile.id&&te._dem._timestamp===V.validForDEMTile.timestamp))return!1;for(const _e in V.instancesPerModel){const Le=V.instancesPerModel[_e];for(let Ve=0;Vele&&(le=Le.max)}const pe=o.aB(I.x,q,V)-I.x,Ae=o.aB(I.y,Z,te)-I.y,_e=o.bY(le,f.center.lat)-I.z;return f._zoomFromMercatorZ(Math.sqrt(pe*pe+Ae*Ae+_e*_e))}function S6(E,f,w,I,R,q,V){const Z=E.context,te=E.renderPass==="shadow",le=E.shadowRenderer,pe=te&&le?le.getShadowPassDepthMode():new Br(Z.gl.LEQUAL,Br.ReadWrite,E.depthRangeFor3D),Ae=E.isTileAffectedByFog(q),_e=E.transform.projection.name==="globe";if(w.meshes)for(const Le of w.meshes){const Ve=_e?[]:["MODEL_POSITION_ON_GPU"],qe=[];let Ze,Xe,ht;const vt=!_e&&I.instancedDataArray.length>20;vt&&Ve.push("INSTANCED_ARRAYS");const st=Ym(E,f.paint.get("model-cutoff-fade-range"));if(st.shouldRenderCutoff&&Ve.push("RENDER_CUTOFF"),te&&le)Ze=E.getOrCreateProgram("modelDepth",{defines:Ve}),Xe=R7(V.shadowTileMatrix,V.shadowTileMatrix,w.globalMatrix),ht=En.disabled;else{X1(Ve,qe,Le,E,f.paint.get("model-color-use-theme").constantOr("default")==="none"?null:f.lut),Ze=E.getOrCreateProgram("model",{defines:Ve,overrideFog:Ae});const Pt=Le.material,Vt=Pt.pbrMetallicRoughness,St=f.paint.get("model-opacity").constantOr(1),Ct=f.paint.get("model-emissive-strength").constantOr(0);Xe=UT(q.expandedProjMatrix,w.globalMatrix,j6,null,E,St,Vt.baseColorFactor,Pt.emissiveFactor,Vt.metallicFactor,Vt.roughnessFactor,Pt,Ct,f,R),le&&(V.shadowUniformsInitialized?Ze.setShadowUniformValues(Z,le.getShadowUniformValues()):(le.setupShadows(q.toUnwrapped(),Ze,"model-tile"),V.shadowUniformsInitialized=!0)),ht=st.shouldRenderCutoff||St<1||Pt.alphaMode!=="OPAQUE"?En.alphaBlended:En.unblended}E.uploadCommonUniforms(Z,Ze,q.toUnwrapped(),null,st);const Ut=Le.material.doubleSided?en.disabled:en.backCCW;if(vt)qe.push(I.instancedDataBuffer),Ze.draw(E,Z.gl.TRIANGLES,pe,kn.disabled,ht,Ut,Xe,f.id,Le.vertexBuffer,Le.indexBuffer,Le.segments,f.paint,E.transform.zoom,void 0,qe,I.instancedDataArray.length);else{const Pt=te?"u_instance":"u_normal_matrix";for(let Vt=0;Vt0)if(E.targetLod<0)E.targetLod=f>I?1:0;else{const q=w/1e3;E.targetLod=f>I?Math.min(E.targetLod+q,1):Math.max(E.targetLod-q,0)}else E.targetLod=0}function e9(E,f,w,I){if(!w.modelManager)return!0;const R=w.modelManager;if(!w.shadowRenderer)return!0;const q=w.shadowRenderer,V=f.aabb;let Z=!0,te=E.maxHeight;if(te===0){let pe=0;for(const Ae in E.instancesPerModel){const _e=R.getModel(Ae,I);_e?pe=Math.max(pe,Math.max(Math.max(_e.aabb.max[0],_e.aabb.max[1]),_e.aabb.max[2])):Z=!1}te=E.maxScale*pe*1.41+E.maxVerticalOffset,Z&&(E.maxHeight=te)}V.max[2]=te,V.min[2]+=E.terrainElevationMin,V.max[2]+=E.terrainElevationMax,o.ae(V.min,V.min,f.tileMatrix),o.ae(V.max,V.max,f.tileMatrix);const le=V.intersects(q.getCurrentCascadeFrustum());return w.currentShadowCascade===0&&(E.isInsideFirstShadowMapFrustum=le===2),le===0}function Pye(E,f){const w=E.uniformValues.u_cutoff_params[0],I=E.uniformValues.u_cutoff_params[1],R=E.uniformValues.u_cutoff_params[2],q=E.uniformValues.u_cutoff_params[3];return I===w||q===R?1:o.aB(((f-w)/(I-w)-R)/(q-R),0,1)}function Lye(E,f,w,I){if(f.pitch<20)return 1;const R=f.getWorldToCameraMatrix();o.aC(R,R,E);const q=o.bw(w.min[0],w.min[1],w.min[2],1);let V=o.aD(o.bI(),q,R),Z=V,te=V;q[1]=w.max[1],V=o.aD(o.bI(),q,R),Z=V[1]te[1]?V:te,q[0]=w.max[0],V=o.aD(o.bI(),q,R),Z=V[1]te[1]?V:te,q[1]=w.min[1],V=o.aD(o.bI(),q,R),Z=V[1]te[1]?V:te;const le=o.aB(I[0],0,1),pe=100*f.pixelsPerMeter*o.aB(I[1],0,1),Ae=o.aB(I[2],0,1),_e=o.eG(o.bI(),Z,te,le),Le=Math.tan(.5*f.fovX),Ve=-_e[2]*Le;if(pe===0)return _e[1]<-Math.abs(Ve)?Ae:1;const qe=(-Math.abs(Ve)-_e[1])/pe,Ze=(ht,vt,st)=>(1-st)*ht+st*vt,Xe=o.aB(Ze(1,Ae,qe),Ae,1);return Ze(1,Xe,o.aB((f.pitch-20)/20,0,1))}class Dye{}class Gi{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(f,w,I){{const Ae=this._storage.get(w.id);if(Ae)return Ae.lastUsedFrameIdx=f,Ae.buf}const R=I.gl,q=R.getBufferParameter(R.ELEMENT_ARRAY_BUFFER,R.BUFFER_SIZE),V=new ArrayBuffer(q),Z=new Int16Array(V);R.getBufferSubData(R.ELEMENT_ARRAY_BUFFER,0,new Int16Array(V));const te=new o.eI;for(let Ae=0;Ae30&&(I.buf.destroy(),this._storage.delete(w))}destroy(){for(const[f,w]of this._storage)w.buf.destroy(),this._storage.delete(f)}}class hw{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const sE={symbol:function(E,f,w,I,R){if(E.renderPass!=="translucent")return;const q=kn.disabled,V=E.colorModeForRenderPass(),Z=w.layout.get("text-variable-anchor"),te=w.layout.get("text-size-scale-range"),le=o.aB(E.scaleFactor,te[0],te[1]);Z&&function(_e,Le,Ve,qe,Ze,Xe,ht,vt){const st=Le.transform,Ut=Ze==="map",Pt=Xe==="map";for(const Vt of _e){const St=qe.getTile(Vt),Ct=St.getBucket(Ve);if(!Ct||!Ct.text||!Ct.text.segments.get().length)continue;const qt=o.bl(Ct.textSizeData,st.zoom,vt),Zt=Au(Vt,Ct.getProjection(),st),Wt=st.calculatePixelsToTileUnitsMatrix(St),hs=Rl(Zt,St.tileID.canonical,Pt,Ut,st,Ct.getProjection(),Wt),ms=Ct.hasIconTextFit()&&Ct.hasIconData();qt&&F7(Ct,Ut,Pt,ht,st,hs,Vt,Math.pow(2,st.zoom-St.tileID.overscaledZ),qt,ms)}}(I,E,w,f,w.layout.get("text-rotation-alignment"),w.layout.get("text-pitch-alignment"),R,le);const pe=w.paint.get("icon-opacity").constantOr(1)!==0,Ae=w.paint.get("text-opacity").constantOr(1)!==0;w.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(pe||Ae)?Pp(E,f,w,I,q,V):(pe&&Pp(E,f,w,I,q,V,{onlyIcons:!0}),Ae&&Pp(E,f,w,I,q,V,{onlyText:!0})),f.map.showCollisionBoxes&&(i6(E,f,w,I,w.paint.get("text-translate"),w.paint.get("text-translate-anchor"),!0),i6(E,f,w,I,w.paint.get("icon-translate"),w.paint.get("icon-translate-anchor"),!1))},circle:function(E,f,w,I){if(E.renderPass!=="translucent")return;const R=w.paint.get("circle-opacity"),q=w.paint.get("circle-stroke-width"),V=w.paint.get("circle-stroke-opacity"),Z=w.layout.get("circle-sort-key").constantOr(1)!==void 0,te=w.paint.get("circle-emissive-strength");if(R.constantOr(1)===0&&(q.constantOr(1)===0||V.constantOr(1)===0))return;const le=E.context,pe=le.gl,Ae=E.transform,_e=!(!E.terrain||!E.terrain.enabled),Le=w.layout.get("circle-elevation-reference"),Ve=E.depthModeForSublayer(0,Br.ReadOnly),qe=new Br(E.context.gl.LEQUAL,Br.ReadOnly,E.depthRangeFor3D),Ze=Le==="none"||_e?Ve:qe,Xe=kn.disabled,ht=E.colorModeForDrapableLayerRenderPass(te),vt=Ae.projection.name==="globe",st=[o.aG(Ae.center.lng),o.aJ(Ae.center.lat)],Ut=[];for(let Vt=0;VtVt.sortKey-St.sortKey);const Pt={useDepthForOcclusion:Ae.depthOcclusionForSymbolsAndCircles};for(const Vt of Ut){const{programConfiguration:St,program:Ct,layoutVertexBuffer:qt,dynamicBuffers:Zt,indexBuffer:Wt,uniformValues:hs,tile:ms}=Vt.state,Zs=Vt.segments;E.terrain&&E.terrain.setupElevationDraw(ms,Ct,Pt),E.uploadCommonUniforms(le,Ct,ms.tileID.toUnwrapped()),Ct.draw(E,pe.TRIANGLES,Ze,Xe,ht,en.disabled,hs,w.id,qt,Wt,Zs,w.paint,Ae.zoom,St,Zt)}},heatmap:function(E,f,w,I){if(w.paint.get("heatmap-opacity")!==0)if(E.renderPass==="offscreen"){const R=E.context,q=R.gl,V=kn.disabled,Z=new En([q.ONE,q.ONE,q.ONE,q.ONE],o.C.transparent,[!0,!0,!0,!0]),te=E.transform.projection.name==="globe"?.5:.25;w.heatmapFbo=R0.createWithTexture(R,w.heatmapFbo,E.width*te,E.height*te),R.clear({color:o.C.transparent});const le=E.transform,pe=le.projection.name==="globe",Ae=pe?["PROJECTION_GLOBE_VIEW"]:[],_e=pe?en.frontCCW:en.disabled,Le=[o.aG(le.center.lng),o.aJ(le.center.lat)];for(let Ve=0;Ve({u_image:0,u_color_ramp:1,u_opacity:Ae.paint.get("heatmap-opacity")}))(0,q),q.id,R.viewportBuffer,R.quadTriangleIndexBuffer,R.viewportSegments,q.paint,R.transform.zoom)}(E,w))},line:function(E,f,w,I){const R=w.paint.get("line-opacity"),q=w.paint.get("line-width");if(R.constantOr(1)===0||q.constantOr(1)===0)return;const V=w.paint.get("line-blend-mode"),Z=E.terrain&&E.terrain.renderingToTexture;if(V==="default"||E.transform.projection.name==="globe")E.renderPass==="translucent"&&fi(E,f,w,I);else{if(Z)return void function(te,le,pe,Ae,_e){if(te.renderPass!=="translucent")return;const Le=te.context,Ve=Le.gl,qe=te.terrain;if(!qe)return;const Ze=Le.bindFramebuffer.current,Xe=te.emissiveMode==="mrt-fallback",ht=qe.drapeBufferSize[0],vt=qe.drapeBufferSize[1];pe.lineBlendFbos||(pe.lineBlendFbos=new PN),pe.lineBlendFbos.drapeFbo=R0.createWithTexture(Le,pe.lineBlendFbos.drapeFbo,ht,vt,!0),Xe&&Ve.drawBuffers([Ve.COLOR_ATTACHMENT0]),Le.clear({color:LN[_e].clearColor,depth:1,stencil:0});const st=te.currentStencilSource,Ut=te._tileClippingMaskIDs,Pt=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1;const Vt=te._terrain;te._terrain=null,te._renderTileClippingMasks(pe,le,Ae),fi(te,le,pe,Ae,VT(_e,te.context),!0),te._terrain=Vt,te.currentStencilSource=st,te._tileClippingMaskIDs=Ut,te.nextStencilID=Pt,Xe&&Ve.drawBuffers([Ve.COLOR_ATTACHMENT0,Ve.COLOR_ATTACHMENT1]);const St=qe.drapeBufferSize,Ct=pe.lineBlendFbos&&pe.lineBlendFbos.drapeFbo;Ct&&(_e==="additive"&&O0(te,pe,Ct),py(te,pe,_e,Ct,Ze,St))}(E,f,w,I,V);if(E.renderPass==="offscreen")return void function(te,le,pe,Ae,_e){const Le=te.context,Ve=Math.ceil(te.width),qe=Math.ceil(te.height);pe.lineBlendFbos||(pe.lineBlendFbos=new PN),pe.lineBlendFbos.fbo=R0.createWithTexture(Le,pe.lineBlendFbos.fbo,Ve,qe,!0),Le.clear({color:LN[_e].clearColor,depth:1,stencil:0});const Ze=te.currentStencilSource,Xe=te._tileClippingMaskIDs,ht=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1,te._renderTileClippingMasks(pe,le,Ae);const vt=te.renderPass;te.renderPass="translucent",fi(te,le,pe,Ae,VT(_e,te.context)),te.renderPass=vt,te.currentStencilSource=Ze,te._tileClippingMaskIDs=Xe,te.nextStencilID=ht,Le.viewport.set([0,0,te.width,te.height]),_e==="additive"&&O0(te,pe,pe.lineBlendFbos.fbo)}(E,f,w,I,V);if(E.renderPass==="translucent"){const te=w.lineBlendFbos&&w.lineBlendFbos.fbo;return void(te&&py(E,w,V,te,null))}}},fill:function(E,f,w,I){const R=w.paint.get("fill-color"),q=w.paint.get("fill-opacity");if(q.constantOr(1)===0)return;const V=w.paint.get("fill-emissive-strength"),Z=E.colorModeForDrapableLayerRenderPass(V),te=w.paint.get("fill-pattern"),le=E.opaquePassEnabledForLayer()&&!te.constantOr(1)&&R.constantOr(o.C.transparent).a===1&&q.constantOr(0)===1?"opaque":"translucent";let pe="none";w.layout.get("fill-elevation-reference")!=="none"?pe="road":w.paint.get("fill-z-offset").constantOr(1)!==0&&(pe="offset");const Ae=!(!E.terrain||!E.terrain.enabled),_e={painter:E,sourceCache:f,layer:w,coords:I,colorMode:Z,elevationType:pe,terrainEnabled:Ae,pass:le};if(E.renderPass==="shadow")return void(E.shadowRenderer&&pe==="road"&&!Ae&&function(Ve){const{painter:qe,sourceCache:Ze,layer:Xe,coords:ht}=Ve,vt=qe.context.gl,st=Ve.painter.shadowRenderer;for(const Ut of ht){const Pt=Ze.getTile(Ut),Vt=Pt.getBucket(Xe);if(!Vt)continue;const St=Vt.elevatedStructures;if(!St||!St.shadowCasterSegments||St.shadowCasterSegments.segments[0].primitiveLength===0)continue;qe.prepareDrawTile();const Ct=Vt.bufferData.programConfigurations.get(Xe.id),qt=qe.isTileAffectedByFog(Ut),Zt=qe.getOrCreateProgram("elevatedStructuresDepth",{config:Ct,overrideFog:qt}),Wt=st.calculateShadowPassMatrixFromTile(Pt.tileID.toUnwrapped());qe.uploadCommonUniforms(qe.context,Zt,Ut.toUnwrapped());const hs=T7(Wt,0);Zt.draw(qe,vt.TRIANGLES,st.getShadowPassDepthMode(),kn.disabled,En.disabled,en.disabled,hs,Xe.id,St.vertexBuffer,St.indexBuffer,St.shadowCasterSegments,Xe.paint,qe.transform.zoom,Ct)}}(_e));const Le=E.emissiveMode==="mrt-fallback";if(pe!=="offset"){if(F0(_e,!1,Le),pe==="road"){const Ve=!Ae&&E.renderPass==="translucent";Ve&&lr(E,f,w,I,"geometry"),F0(_e,!0,Le,kn.disabled),Ve&&function(qe){const{painter:Ze,sourceCache:Xe,layer:ht,coords:vt,colorMode:st}=qe,Ut=Ze.context.gl,Pt=qe.painter.shadowRenderer,Vt=!!Pt&&Pt.enabled,St=new Br(Ze.context.gl.LEQUAL,Br.ReadOnly,Ze.depthRangeFor3D);let Ct=[0,0,0];if(Vt){const Zt=Ze.style.directionalLight,Wt=Ze.style.ambientLight;Zt&&Wt&&(Ct=$1(Ze.style,Zt,Wt))}const qt=Zt=>{for(const Wt of vt){const hs=Xe.getTile(Wt),ms=hs.getBucket(ht);if(!ms)continue;const Zs=ms.elevatedStructures;if(!Zs)continue;let ts,Ns;if(Zt?(ts=Zs.renderableBridgeSegments,Ns=Zs.bridgeProgramConfigurations.get(ht.id)):(ts=Zs.renderableTunnelSegments,Ns=Zs.tunnelProgramConfigurations.get(ht.id)),!ts||ts.segments[0].primitiveLength===0)continue;Ns.updatePaintBuffers(),Ze.prepareDrawTile();const rs=Ze.isTileAffectedByFog(Wt),Ps=[];Vt&&Ps.push("RENDER_SHADOWS","NORMAL_OFFSET");const Ms=Ze.getOrCreateProgram("elevatedStructures",{config:Ns,overrideFog:rs,defines:Ps}),Rs=Ze.translatePosMatrix(Wt.projMatrix,hs,ht.paint.get("fill-translate"),ht.paint.get("fill-translate-anchor"));Vt&&Pt.setupShadows(hs.tileID.toUnwrapped(),Ms,"vector-tile");const xr=e6(Rs,Ct);Ze.uploadCommonUniforms(Ze.context,Ms,Wt.toUnwrapped()),Ms.draw(Ze,Ut.TRIANGLES,St,kn.disabled,st,en.backCCW,xr,ht.id,Zs.vertexBuffer,Zs.indexBuffer,ts,ht.paint,Ze.transform.zoom,Ns,[Zs.vertexBufferNormal])}};qt(!0),qt(!1)}(_e)}}else F0(_e,!1,Le,E.stencilModeFor3D())},"fill-extrusion":function(E,f,w,I){const R=w.paint.get("fill-extrusion-opacity"),q=E.context,V=q.gl,Z=E.terrain,te=Z&&Z.renderingToTexture;if(R===0)return;const le=E.emissiveMode==="mrt-fallback",pe=E.conflationActive&&E.style.isLayerClipped(w,f.getSource()),Ae=E.style.order.indexOf(w.fqid);if(pe&&function(_e,Le,Ve,qe,Ze){for(const Xe of qe){const ht=Le.getTile(Xe).getBucket(Ve);ht&&(ht.updateReplacement(Xe,_e.replacementSource,Ze),ht.uploadCentroid(_e.context))}}(E,f,w,I,Ae),Z||pe)for(const _e of I){const Le=f.getTile(_e).getBucket(w);Le&>(E.context,f,_e,Le,w,Z,pe)}if(E.renderPass==="shadow"&&E.shadowRenderer){if(Z&&R<.65&&w._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.ac)return;const _e=E.shadowRenderer.getShadowPassDepthMode();Yt(E,f,w,I,_e,kn.disabled,En.disabled,pe)}else if(E.renderPass==="translucent"){const _e=!w.paint.get("fill-extrusion-pattern").constantOr(1),Le=w.paint.get("fill-extrusion-color").constantOr(o.C.white);if(!te&&Le.a!==0){const Ve=new Br(E.context.gl.LEQUAL,Br.ReadWrite,E.depthRangeFor3D);R===1&&_e?Yt(E,f,w,I,Ve,kn.disabled,En.unblended,pe):(Yt(E,f,w,I,Ve,kn.disabled,En.disabled,pe),Yt(E,f,w,I,Ve,E.stencilModeFor3D(),E.colorModeForRenderPass(),pe),E.resetStencilClippingMasks())}if(E.style.enable3dLights()&&_e&&(!Z&&E.transform.projection.name!=="globe"||te)){const Ve=w.paint.get("fill-extrusion-opacity"),qe=w.paint.get("fill-extrusion-ambient-occlusion-intensity"),Ze=w.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Xe=w.paint.get("fill-extrusion-flood-light-intensity"),ht=w.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",vt=w.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(ht?null:w.lut).toArray01().slice(0,3),st=qe>0&&Ze>0,Ut=Xe>0,Pt=(Ct,qt,Zt)=>(1-Zt)*Ct+Zt*qt,Vt=new d6;Vt.translate=w.paint.get("fill-extrusion-translate"),Vt.translateAnchor=w.paint.get("fill-extrusion-translate-anchor"),Vt.edgeRadius=w.layout.get("fill-extrusion-edge-radius"),Vt.cutoffFadeRange=w.paint.get("fill-extrusion-cutoff-fade-range");const St=Ct=>{const qt=E.depthModeForSublayer(1,Br.ReadOnly,V.LEQUAL,!0),Zt=w.paint.get(Ct?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Wt=Pt(.1,3,Zt),hs=E._showOverdrawInspector;if(!hs){const ms=new kn({func:V.ALWAYS,mask:255},255,255,V.KEEP,V.KEEP,V.REPLACE),Zs=new En([V.ONE,V.ONE,V.ONE,V.ONE],o.C.transparent,[!1,!1,!1,!0],V.MIN);Lp(Vt,E,f,w,I,qt,ms,Zs,en.disabled,Ct,"sdf",Ve,qe,Ze,Xe,vt,Wt,pe,!1)}{const ms=hs?kn.disabled:new kn({func:V.EQUAL,mask:255},255,255,V.KEEP,V.DECR,V.DECR),Zs=hs?E.colorModeForRenderPass():new En([V.ONE_MINUS_DST_ALPHA,V.DST_ALPHA,V.ONE,V.ONE],o.C.transparent,[!0,!0,!0,!0]);Lp(Vt,E,f,w,I,qt,ms,Zs,en.disabled,Ct,"color",Ve,qe,Ze,Xe,vt,Wt,pe,!1)}};if(te){const Ct=()=>{const Zt=Z.drapeBufferSize[0],Wt=Z.drapeBufferSize[1];let hs=Z.framebufferCopyTexture;return hs&&(!hs||hs.size[0]===Zt&&hs.size[1]===Wt)||(hs&&hs.destroy(),hs=Z.framebufferCopyTexture=new o.T(q,new o.q({width:Zt,height:Wt}),V.RGBA8)),hs.bind(V.LINEAR,V.CLAMP_TO_EDGE),V.copyTexSubImage2D(V.TEXTURE_2D,0,0,0,0,0,Zt,Wt),hs},qt=(Zt,Wt,hs)=>{const ms=E.depthModeForSublayer(1,Br.ReadOnly,V.LEQUAL,!1),Zs=w.paint.get(Zt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),ts=Pt(.1,3,Zs);{const Ns=new En([V.ONE,V.ONE,V.ONE,V.ONE],o.C.transparent,[!1,!1,!1,!0]);Lp(Vt,E,f,w,I,ms,kn.disabled,Ns,en.disabled,Zt,"clear",Ve,qe,Ze,Xe,vt,ts,pe,Wt)}{const Ns=new kn({func:V.ALWAYS,mask:255},255,255,V.KEEP,V.KEEP,V.REPLACE),rs=new En([V.ONE,V.ONE,V.ONE,V.ONE],o.C.transparent,[!1,!1,!1,!0],V.MIN);Lp(Vt,E,f,w,I,ms,Ns,rs,en.disabled,Zt,"sdf",Ve,qe,Ze,Xe,vt,ts,pe,Wt)}le&&!Zt&&(hs=Ct());{const Ns=Zt?V.ZERO:V.ONE_MINUS_DST_ALPHA,rs=new kn({func:V.EQUAL,mask:255},255,255,V.KEEP,V.DECR,V.DECR),Ps=new En([Ns,V.DST_ALPHA,V.ONE_MINUS_DST_ALPHA,V.ZERO],o.C.transparent,[!0,!0,!0,!0]);Lp(Vt,E,f,w,I,ms,rs,Ps,en.disabled,Zt,"color",Ve,qe,Ze,Xe,vt,ts,pe,Wt)}if(!le||Zt){const Ns=new En([V.ONE,V.ONE,V.ONE,Zt?V.ZERO:V.ONE],o.C.transparent,[!1,!1,!1,!0],Zt?V.FUNC_ADD:V.MAX);Lp(Vt,E,f,w,I,ms,kn.disabled,Ns,en.disabled,Zt,"clear",Ve,qe,Ze,Xe,vt,ts,pe,Wt,hs)}else{V.drawBuffers([V.NONE,V.COLOR_ATTACHMENT1]);const Ns=new kn({func:V.EQUAL,mask:255},254,255,V.KEEP,V.DECR,V.DECR),rs=new En([V.ONE,V.ONE,V.ONE,V.ONE],o.C.transparent,[!0,!1,!1,!1],V.MAX);Lp(Vt,E,f,w,I,ms,Ns,rs,en.disabled,Zt,"emissive",Ve,qe,Ze,Xe,vt,ts,pe,Wt,hs),V.drawBuffers([V.COLOR_ATTACHMENT0])}};if(st||Ut){let Zt;E.prepareDrawTile(),le&&!st||(Zt=Ct()),st&&qt(!0,!1,Zt),Ut&&qt(!1,!0,Zt)}}else st&&St(!0),Ut&&St(!1),(st||Ut)&&E.resetStencilClippingMasks()}}},hillshade:function(E,f,w,I){if(E.renderPass!=="offscreen"&&E.renderPass!=="translucent"||E.style.disableElevatedTerrain)return;const R=E.context,q=E.terrain&&E.terrain.renderingToTexture,[V,Z]=E.renderPass!=="translucent"||q?[{},I]:E.stencilConfigForOverlap(I);for(const te of Z){const le=f.getTile(te);if(le.needsHillshadePrepare&&E.renderPass==="offscreen")TT(E,le,w);else if(E.renderPass==="translucent"){const pe=E.depthModeForSublayer(0,Br.ReadOnly),Ae=w.paint.get("hillshade-emissive-strength"),_e=E.colorModeForDrapableLayerRenderPass(Ae),Le=q&&E.terrain?E.terrain.stencilModeForRTTOverlap(te):V[te.overscaledZ];FL(E,te,le,w,pe,Le,_e)}}R.viewport.set([0,0,E.width,E.height]),E.resetStencilClippingMasks()},raster:function(E,f,w,I,R,q){if(E.renderPass!=="translucent")return;const V=w.paint.get("raster-opacity");if(V===0)return;const Z=E.transform.projection.name==="globe",te=w.paint.get("raster-elevation")!==0,le=te&&Z,pe=E.terrain&&E.terrain.exaggeration()>0&&te&&w.paint.get("raster-elevation-reference")==="ground",Ae=!Z&&pe;if(E.renderElevatedRasterBackface&&!le)return;const _e=E.context,Le=_e.gl,Ve=f.getSource(),qe=function(Ct,qt,Zt,Wt,hs){const ms=qt.paint.get("raster-color"),Zs=Ct.type==="raster-array",ts=[],Ns=qt.paint.get("raster-resampling"),rs=qt.paint.get("raster-color-mix");let Ps=qt.paint.get("raster-color-range");const Ms=[rs[0],rs[1],rs[2],0],Rs=rs[3];let xr=Ns==="nearest"?Wt.NEAREST:Wt.LINEAR;if(Zs&&(ts.push("RASTER_ARRAY"),ms||ts.push("RASTER_COLOR"),Ns==="linear"&&ts.push("RASTER_ARRAY_LINEAR"),xr=Wt.NEAREST,!Ps&&Ct.rasterLayers)){const or=Ct.rasterLayers.find(({id:Js})=>Js===qt.sourceLayer);or&&or.fields&&or.fields.range&&(Ps=or.fields.range)}if(Ps=Ps||[0,1],ms){ts.push("RASTER_COLOR"),Zt.activeTexture.set(Wt.TEXTURE2),qt.updateColorRamp(Ps);let or=qt.colorRampTexture;or||(or=qt.colorRampTexture=new o.T(Zt,qt.colorRamp,Wt.RGBA8)),or.bind(xr,Wt.CLAMP_TO_EDGE)}return hs&&ts.push("USE_MRT1"),{mix:Ms,range:Ps,offset:Rs,defines:ts,resampling:xr}}(Ve,w,_e,Le,E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback");if(Ve instanceof o.aY&&!I.length&&!Z)return;const Ze=w.paint.get("raster-emissive-strength"),Xe=E.colorModeForDrapableLayerRenderPass(Ze),ht=E.terrain&&E.terrain.renderingToTexture,vt=!E.options.moving,st=w.paint.get("raster-resampling")==="nearest"?Le.NEAREST:Le.LINEAR;if(Ve instanceof o.aY&&!I.length&&(Ve.onNorthPole||Ve.onSouthPole)){const Ct=te?E.stencilModeFor3D():kn.disabled;return void BN(!!Ve.onNorthPole,null,E,f,w,Ze,qe,en.disabled,Ct)}if(!I.length)return;const[Ut,Pt]=Ve instanceof o.aY||ht?[{},I]:E.stencilConfigForOverlap(I),Vt=Pt.at(-1).overscaledZ;le&&qe.defines.push("PROJECTION_GLOBE_VIEW"),te&&qe.defines.push("RENDER_CUTOFF","ELEVATED"),pe&&qe.defines.push("ELEVATION_REFERENCE_GROUND");const St=(Ct,qt,Zt)=>{for(const Wt of Ct){const hs=Wt.toUnwrapped(),ms=f.getTile(Wt);if(ht&&(!ms||!ms.hasData()))continue;_e.activeTexture.set(Le.TEXTURE0);const Zs=f6(ms,Ve,w,qe);if(!Zs||!Zs.texture)continue;const{texture:ts,mix:Ns,offset:rs,tileSize:Ps,buffer:Ms}=Zs;let Rs,xr;ht?(Rs=Br.disabled,xr=Wt.projMatrix):te?(Rs=new Br(Le.LEQUAL,Br.ReadWrite,E.depthRangeFor3D),xr=Z?E.transform.expandedFarZProjMatrix:E.transform.calculateProjMatrix(hs,vt)):(Rs=E.depthModeForSublayer(Wt.overscaledZ-Vt,V===1?Br.ReadWrite:Br.ReadOnly,Le.LESS),xr=E.transform.calculateProjMatrix(hs,vt));const or=E.terrain&&ht?E.terrain.stencilModeForRTTOverlap(Wt):Ut[Wt.overscaledZ],Js=q?0:w.paint.get("raster-fade-duration");ms.registerFadeDuration(Js);const Ys=f.findLoadedParent(Wt,0),Wr=aw(ms,Ys,f,E.transform,Js);let Vr,Ir;!Wr.isFading&&ms.refreshedUponExpiration&&(ms.refreshedUponExpiration=!1),E.terrain&&E.terrain.prepareDrawTile(),_e.activeTexture.set(Le.TEXTURE0),ts.bind(st,Le.CLAMP_TO_EDGE),_e.activeTexture.set(Le.TEXTURE1),Ys?(Ys.texture&&Ys.texture.bind(st,Le.CLAMP_TO_EDGE),Vr=Math.pow(2,Ys.tileID.overscaledZ-ms.tileID.overscaledZ),Ir=[ms.tileID.canonical.x*Vr%1,ms.tileID.canonical.y*Vr%1]):ts.bind(st,Le.CLAMP_TO_EDGE),"useMipmap"in ts&&_e.extTextureFilterAnisotropic&&E.transform.pitch>20&&Le.texParameterf(Le.TEXTURE_2D,_e.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,_e.extTextureFilterAnisotropicMax);const Rr=E.transform;let mn;const Ln=te?m6(Rr):[0,0,0,0];let An,ta,Tn,Ia,qn,Ha=0;if(le&&Ve instanceof o.aY&&Ve.coordinates.length>3)An=Float32Array.from(o.dx(o.dy(new o.cp(0,0,0)))),ta=Float32Array.from(Rr.globeMatrix),Tn=Float32Array.from(o.dt(Rr)),Ia=[o.aG(Rr.center.lng),o.aJ(Rr.center.lat)],mn=Ve.elevatedGlobePerspectiveTransform,qn=Ve.elevatedGlobeGridMatrix||new Float32Array(9);else if(le){const ai=o.du(Wt.canonical);Ha=o.dv(ai.getCenter().lat),An=Float32Array.from(o.dx(o.dy(Wt.canonical))),ta=Float32Array.from(Rr.globeMatrix),Tn=Float32Array.from(o.dt(Rr)),Ia=[o.aG(Rr.center.lng),o.aJ(Rr.center.lat)],mn=[0,0],qn=Float32Array.from(o.dw(Wt.canonical,ai,Ha,Rr.worldSize/Rr._pixelsPerMercatorPixel))}else mn=Ve instanceof o.aY?Ve.perspectiveTransform:[0,0],An=new Float32Array(16),ta=new Float32Array(9),Tn=new Float32Array(16),Ia=[0,0],qn=new Float32Array(9);const Ai=zT(E,xr,An,ta,Tn,qn,Ir||[0,0],o.ai(E.transform.zoom),Ia,Ln,Vr||1,Wr,w,mn,te?w.paint.get("raster-elevation"):0,2,Ns,rs,qe.range,Ps,Ms,Ze),Li=E.isTileAffectedByFog(Wt),zi=E.getOrCreateProgram("raster",{defines:qe.defines,overrideFog:Li});if(E.uploadCommonUniforms(_e,zi,hs),Ve instanceof o.aY){const ai=Ve.elevatedGlobeVertexBuffer,sa=Ve.elevatedGlobeIndexBuffer;if(ht||!Z)Ve.boundsBuffer&&Ve.boundsSegments&&zi.draw(E,Le.TRIANGLES,Rs,kn.disabled,Xe,en.disabled,Ai,w.id,Ve.boundsBuffer,E.quadTriangleIndexBuffer,Ve.boundsSegments);else if(ai&&sa){const la=Rr.zoom<=o.cN?Ve.elevatedGlobeSegments:Ve.getSegmentsForLongitude(Rr.center.lng);la&&zi.draw(E,Le.TRIANGLES,Rs,kn.disabled,Xe,qt,Ai,w.id,ai,sa,la)}}else if(le){Rs=new Br(Le.LEQUAL,Br.ReadOnly,E.depthRangeFor3D);const ai=E.globeSharedBuffers;if(ai){pe&&(E.terrain.setupElevationDraw(ms,zi),E.uploadCommonUniforms(_e,zi,ms.tileID.toUnwrapped()));const[sa,la,$i]=ai.getGridBuffers(Ha,!1),Qo=zi.getAttributeLocation(Le,"a_texture_pos");Qo!==-1&&Le.vertexAttribI4ui(Qo,0,0,0,0),zi.draw(E,Le.TRIANGLES,Rs,Zt||or,E.colorModeForRenderPass(),qt,Ai,w.id,sa,la,$i)}}else if(Ae)Rs=new Br(Le.LEQUAL,Br.ReadWrite,E.depthRangeFor3D),E.terrain.setupElevationDraw(ms,zi),E.uploadCommonUniforms(_e,zi,ms.tileID.toUnwrapped()),Rr.pitch>20&&zi.draw(E,Le.TRIANGLES,Rs,kn.disabled,En.disabled,en.frontCCW,Ai,w.id,E.terrain.gridBuffer,E.terrain.gridIndexBuffer,E.terrain.gridSegments),zi.draw(E,Le.TRIANGLES,Rs,or,Xe,en.backCCW,Ai,w.id,E.terrain.gridBuffer,E.terrain.gridIndexBuffer,E.terrain.gridSegments);else{const{tileBoundsBuffer:ai,tileBoundsIndexBuffer:sa,tileBoundsSegments:la}=E.getTileBoundsBuffers(ms);zi.draw(E,Le.TRIANGLES,Rs,or,Xe,en.disabled,Ai,w.id,ai,sa,la)}}if(!(Ve instanceof o.aY)&&le)for(const Wt of Ct){const hs=Wt.canonical.y===(1<Vt.tileID)),Le&&(le.activeTexture.set(pe.TEXTURE0),E.imageManager.bind(E.context,w.scope));const Pt=[];if(E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback"&&Pt.push("USE_MRT1"),te){const Vt=E.getOrCreateProgram(vt,{overrideFog:!1,overrideRtt:!0,defines:Pt}),St=p6,Ct=new o.aU(0,0,0,0,0),qt=Le?$T(St,Z,V,E,0,w.scope,Ve,te,{tileID:Ct,tileSize:_e}):D7(St,Z,V,R.toPremultipliedRenderColor(q?null:w.lut));return void Vt.draw(E,pe.TRIANGLES,Xe,Ze,ht,en.disabled,qt,w.id,E.viewportBuffer,E.quadTriangleIndexBuffer,E.viewportSegments)}for(const Vt of Ut){const St=E.isTileAffectedByFog(Vt),Ct=E.getOrCreateProgram(vt,{overrideFog:St,defines:Pt}),qt=Vt.toUnwrapped(),Zt=I?Vt.projMatrix:E.transform.calculateProjMatrix(qt);E.prepareDrawTile();const Wt=f?f.getTile(Vt):st?st[Vt.key]:new o.b3(Vt,_e,Ae.zoom,E),hs=Le?$T(Zt,Z,V,E,0,w.scope,Ve,te,{tileID:Vt,tileSize:_e}):D7(Zt,Z,V,R.toPremultipliedRenderColor(q?null:w.lut));E.uploadCommonUniforms(le,Ct,qt);const{tileBoundsBuffer:ms,tileBoundsIndexBuffer:Zs,tileBoundsSegments:ts}=E.getTileBoundsBuffers(Wt);Ct.draw(E,pe.TRIANGLES,Xe,Ze,ht,en.disabled,hs,w.id,ms,Zs,ts)}},sky:function(E,f,w){const I=E._atmosphere?o.ai(E.transform.zoom):1,R=w.paint.get("sky-opacity")*I;if(R===0)return;const q=E.context,V=w.paint.get("sky-type"),Z=new Br(q.gl.LEQUAL,Br.ReadOnly,[0,1]),te=E.frameCounter/1e3%1;V==="atmosphere"?E.renderPass==="offscreen"?w.needsSkyboxCapture(E)&&(function(le,pe){const Ae=le.context,_e=Ae.gl;let Le=pe.skyboxFbo;if(!Le){Le=pe.skyboxFbo=Ae.createFramebuffer(32,32,1,null),pe.skyboxGeometry=new JT(Ae),pe.skyboxTexture=Ae.gl.createTexture(),_e.bindTexture(_e.TEXTURE_CUBE_MAP,pe.skyboxTexture),_e.texParameteri(_e.TEXTURE_CUBE_MAP,_e.TEXTURE_WRAP_S,_e.CLAMP_TO_EDGE),_e.texParameteri(_e.TEXTURE_CUBE_MAP,_e.TEXTURE_WRAP_T,_e.CLAMP_TO_EDGE),_e.texParameteri(_e.TEXTURE_CUBE_MAP,_e.TEXTURE_MIN_FILTER,_e.LINEAR),_e.texParameteri(_e.TEXTURE_CUBE_MAP,_e.TEXTURE_MAG_FILTER,_e.LINEAR);for(let Xe=0;Xe<6;++Xe)_e.texImage2D(_e.TEXTURE_CUBE_MAP_POSITIVE_X+Xe,0,_e.RGBA,32,32,0,_e.RGBA,_e.UNSIGNED_BYTE,null)}Ae.bindFramebuffer.set(Le.framebuffer),Ae.viewport.set([0,0,32,32]);const Ve=pe.getCenter(le,!0),qe=le.getOrCreateProgram("skyboxCapture"),Ze=new Float64Array(16);o.en(Ze,.5*-Math.PI),Go(le,pe,qe,Ze,Ve,0),o.en(Ze,.5*Math.PI),Go(le,pe,qe,Ze,Ve,1),o.eo(Ze,.5*-Math.PI),Go(le,pe,qe,Ze,Ve,2),o.eo(Ze,.5*Math.PI),Go(le,pe,qe,Ze,Ve,3),o.bA(Ze),Go(le,pe,qe,Ze,Ve,4),o.en(Ze,Math.PI),Go(le,pe,qe,Ze,Ve,5),Ae.viewport.set([0,0,le.width,le.height])}(E,w),w.markSkyboxValid(E)):E.renderPass==="sky"&&function(le,pe,Ae,_e,Le){const Ve=le.context,qe=Ve.gl,Ze=le.transform,Xe=le.getOrCreateProgram("skybox");Ve.activeTexture.set(qe.TEXTURE0),qe.bindTexture(qe.TEXTURE_CUBE_MAP,pe.skyboxTexture);const ht=((vt,st,Ut,Pt,Vt)=>({u_matrix:vt,u_sun_direction:st,u_cubemap:0,u_opacity:Pt,u_temporal_offset:Vt}))(Ze.skyboxMatrix,pe.getCenter(le,!1),0,_e,Le);le.uploadCommonUniforms(Ve,Xe),Xe.draw(le,qe.TRIANGLES,Ae,kn.disabled,le.colorModeForRenderPass(),en.backCW,ht,"skybox",pe.skyboxGeometry.vertexBuffer,pe.skyboxGeometry.indexBuffer,pe.skyboxGeometry.segment)}(E,w,Z,R,te):V==="gradient"&&E.renderPass==="sky"&&function(le,pe,Ae,_e,Le){const Ve=le.context,qe=Ve.gl,Ze=le.transform,Xe=le.getOrCreateProgram("skyboxGradient");pe.skyboxGeometry||(pe.skyboxGeometry=new JT(Ve)),Ve.activeTexture.set(qe.TEXTURE0);let ht=pe.colorRampTexture;ht||(ht=pe.colorRampTexture=new o.T(Ve,pe.colorRamp,qe.RGBA8)),ht.bind(qe.LINEAR,qe.CLAMP_TO_EDGE);const vt=((st,Ut,Pt,Vt,St)=>({u_matrix:st,u_color_ramp:0,u_center_direction:Ut,u_radius:o.am(Pt),u_opacity:Vt,u_temporal_offset:St}))(Ze.skyboxMatrix,pe.getCenter(le,!1),pe.paint.get("sky-gradient-radius"),_e,Le);le.uploadCommonUniforms(Ve,Xe),Xe.draw(le,qe.TRIANGLES,Ae,kn.disabled,le.colorModeForRenderPass(),en.backCW,vt,"skyboxGradient",pe.skyboxGeometry.vertexBuffer,pe.skyboxGeometry.indexBuffer,pe.skyboxGeometry.segment)}(E,w,Z,R,te)},custom:function(E,f,w,I){const R=E.context,q=w.implementation;if(!E.transform.projection.unsupportedLayers||!E.transform.projection.unsupportedLayers.includes("custom")||E.terrain&&(E.terrain.renderingToTexture||E.renderPass==="offscreen")&&w.isDraped(f)){if(E.renderPass==="offscreen"){const V=q.prerender;if(V){if(E.setCustomLayerDefaults(),R.setColorMode(E.colorModeForRenderPass()),E.transform.projection.name==="globe"){const Z=E.transform.pointMerc;V.call(q,R.gl,E.transform.customLayerMatrix(),E.transform.getProjection(),E.transform.globeToMercatorMatrix(),o.ai(E.transform.zoom),[Z.x,Z.y],E.transform.pixelsPerMeterRatio)}else V.call(q,R.gl,E.transform.customLayerMatrix());R.setDirty(),E.setBaseState()}}else if(E.renderPass==="translucent"){if(E.terrain&&E.terrain.renderingToTexture){const Z=q.renderToTile;if(Z){const te=I[0].canonical,le={x:te.x+I[0].wrap*(q.wrapTileId?0:1<{le&&(le.useNormalOffset=!0,pe||(le.enabled=!0))},_e=f.getSource();if(E.renderPass==="light-beam"&&_e.type!=="batched-model")return;if(_e.type==="vector"||_e.type==="geojson")return function(st,Ut,Pt,Vt,St){const Ct=st.transform,qt=Ct.projection.name==="globe",Zt=Ct.getFreeCameraOptions().position;if(!st.modelManager)return;const Wt=st.modelManager;Pt.modelManager=Wt;const hs=st.shadowRenderer;if(!Object.hasOwn(Pt._unevaluatedLayout._values,"model-id"))return;const ms=Pt._unevaluatedLayout._values["model-id"],Zs=Object.assign({},Pt.layout.get("model-id").parameters),ts=st.style.order.indexOf(Pt.fqid),Ns=Pt.paint.get("model-opacity").constantOr(1);for(const rs of Vt){const Ps=Ut.getTile(rs).getBucket(Pt);if(!Ps||Ps.projection.name!==Ct.projection.name)continue;const Ms=Ps.getModelUris();if(Ms&&!Ps.modelsRequested&&(Wt.addModelsFromBucket(Ms,St),Ps.modelsRequested=!0),qt)Zs.zoom=rs.overscaledZ;else{const Ir=X7(rs,Ct);Zs.zoom=Ir}const Rs=ms.possiblyEvaluate(Zs);if(Z7(st,Ps,rs),Dp.shadowUniformsInitialized=!1,Dp.useSingleShadowCascade=!!hs&&hs.getMaxCascadeForTile(rs.toUnwrapped())===0,st.renderPass==="shadow"&&hs){if(st.currentShadowCascade===1&&Ps.isInsideFirstShadowMapFrustum)continue;const Ir=Ct.calculatePosMatrix(rs.toUnwrapped(),Ct.worldSize);if(Dp.tileMatrix.set(Ir),Dp.shadowTileMatrix.set(hs.calculateShadowPassMatrixFromMatrix(Ir)),Dp.aabb.min=[0,0,0],Dp.aabb.max[0]=Dp.aabb.max[1]=o.ak,Dp.aabb.max[2]=0,e9(Ps,Dp,st,Pt.scope))continue}const xr=1<0&&st.style.isLayerClipped(Pt,Ut.getSource())&&Ps.updateReplacement(rs,st.replacementSource,ts,Pt.scope)&&(Ps.uploaded=!1,Ps.upload(st.context));let Js=0;const Ys=new Array,Wr=new Array,Vr=new Array;for(let Ir in Ps.instancesPerModel){const Rr=Ps.instancesPerModel[Ir];Rr.features.length>0&&!qt&&(Ir=Rs.evaluate(Rr.features[0].feature,{}));const mn=Wt.getModel(Ir,St);if(mn||Wt.hasURLBeenRequested(Ir)||Ps.modelUris.includes(Ir)||(Ps.modelUris.push(Ir),Ps.modelsRequested=!1),mn&&mn.uploaded)if(qt){const Ln=o.bN([],[Zt.x,Zt.y,Zt.z],st.transform.worldSize);o.ew(Ln,Ln);for(let An=0;An0&&Ia.elevationUpdate(Ir.terrain,An,Tn,mn.source),Ia.needsReEvaluation(Ir,ta,mn)&&Ia.evaluate(mn))}})(st,Ut,Pt,Vt),function(){const Ir=new Map;let Rr,mn,Ln;Ys?(Rr=Vt.length-1,mn=-1,Ln=-1):(Rr=0,mn=Vt.length,Ln=1);const An=new Float64Array(16),ta=o.cg(),Tn=new o.P(0,0);for(let Ia=Rr;Ia!==mn;Ia+=Ln){const qn=Vt[Ia],Ha=Ut.getTile(qn).getBucket(Pt);if(!Ha||!Ha.uploaded)continue;let Ai=!1;Zt&&(Ai=Zt.getMaxCascadeForTile(qn.toUnwrapped())===0);const Li=Ct.calculatePosMatrix(qn.toUnwrapped(),Ct.worldSize),zi=Ha.modelTraits;!xr&&Ys&&(o.ba(An,Li),o.ae(ta,hs,An),Tn.x=ta[0],Tn.y=ta[1]);const ai=[];Ha.setFilter(Pt.filter);for(const sa of Ha.getNodesInfo()){if(sa.hiddenByReplacement||!sa.node.meshes)continue;const la=sa.node;let $i=0;st.terrain&&la.elevation&&($i=la.elevation*st.terrain.exaggeration());const Qo=(()=>{const nc=sa.aabb;return Rs.min=[...nc.min],Rs.max=[...nc.max],Rs.min[2]+=$i,Rs.max[2]+=$i,o.ae(Rs.min,Rs.min,Li),o.ae(Rs.max,Rs.max,Li),Rs})(),wi=sa.evaluatedScale;if(wi[0]<=1&&wi[1]<=1&&wi[2]<=1&&Qo.intersects(or)===0)continue;if(!xr){const nc=Qo.min,dh=Qo.max;yy[0]=.5*(nc[0]+dh[0]),yy[1]=.5*(nc[1]+dh[1]),yy[2]=.5*(nc[2]+dh[2]);const uh=o.bh(hs,yy)*ts;J7(sa,uh,Math.min(st._debugParams.dt,1e3/30),st._debugParams.lodSwitchDistance)}if(!xr&&Ys){const nc=.16666666666666666;sa.cameraCollisionOpacity=hs[0]>Qo.min[0]&&hs[0]Qo.min[1]&&hs[1]!Ys||sa.opacity===1&&la.opacity===1?sa.depthla.depth?-1:1);for(const sa of ai){const la=sa.nodeInfo,$i=la.node;if(st._debugParams.show3DModelFootprints&&$i.footprint){const bc=$i.id||$i.name||"footprint";Ir.has(bc)||Ir.set(bc,{node:$i,mvp:sa.wvpForTile})}o.aC(zh,Ns,sa.tileModelMatrix),o.aC(zh,Zs,zh),o.ba($f,zh),o.e9($f,$f),o.cE($f,$f,Q7),o.aC(zh,zh,$i.globalMatrix);const Qo=st.renderPass==="light-beam",wi=Pt.paint.get("model-color-use-theme").constantOr("default")==="none",$n=zi&o.eH.HasMapboxMeshFeatures,ho=$n?0:la.evaluatedRMEA[0][2],qi=la.targetLod,cl=$i.lodMeshes&&$i.lodMeshes.length>0,Oa=cl&&qi>0&&qi<1;if(xr&&cl&&Math.round(qi)===1)continue;const jl=Oa?2:1,Kd=cl&&Math.round(qi)===1;for(let bc=0;bc=Sp||Op>=Sp}const Rc=Ol.material;let Jo;Rc.occlusionTexture&&Rc.occlusionTexture.offsetScale&&(Jo=Rc.occlusionTexture.offsetScale,Mi.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),Oa&&Mi.defines.push("DITHERED_DISCARD");const Mu=st.getOrCreateProgram("model",Mi);!xr&&Zt&&Zt.setupShadowsFromMatrix(sa.tileModelMatrix,Mu,Zt.useNormalOffset),st.uploadCommonUniforms(St,Mu,null,Nl);const Iu=Rc.pbrMetallicRoughness;Iu.metallicFactor=.9,Iu.roughnessFactor=.5;const Rp=UT(ii,zh,$f,$i.globalMatrix,st,sa.opacity,Iu.baseColorFactor,Rc.emissiveFactor,Iu.metallicFactor,Iu.roughnessFactor,Rc,ho,Pt,[0,0,0],Jo,void 0,void 0,dh);!pu&&(la.hasTranslucentParts||sa.opacity<1)&&Mu.draw(st,St.gl.TRIANGLES,Ps,kn.disabled,En.disabled,en.backCCW,Rp,Pt.id,Ol.vertexBuffer,Ol.indexBuffer,Ol.segments,Pt.paint,st.transform.zoom,void 0,pi),Mu.draw(st,St.gl.TRIANGLES,pu?Ms:Ps,kn.disabled,pu||sa.opacity<1||la.hasTranslucentParts?En.alphaBlended:En.unblended,en.backCCW,Rp,Pt.id,Ol.vertexBuffer,Ol.indexBuffer,Ol.segments,Pt.paint,st.transform.zoom,void 0,pi)}}}}if(st._debugParams.show3DModelFootprints&&Ir.size>0){const Ia=Array.from(Ir.keys()).sort();for(const qn of Ia){const{node:Ha,mvp:Ai}=Ir.get(qn);N6(st,0,Ha,Ai)}}}()}(E,f,w,I),void Ae();if(_e.type!=="model")return;const Le=_e.getModels(),Ve=[],qe=E.transform.getFreeCameraOptions().position,Ze=o.bN([],[qe.x,qe.y,qe.z],E.transform.worldSize);o.ew(Ze,Ze);const Xe=[],ht=[];let vt=0;for(const st of Le){const Ut=f.getFeatureState("",st.id),Pt={type:"Unknown",id:st.id,properties:st.featureProperties},Vt=w.paint.get("model-rotation").evaluate(Pt,Ut),St=w.paint.get("model-scale").evaluate(Pt,Ut),Ct=w.paint.get("model-translation").evaluate(Pt,Ut),qt=w.paint.get("model-opacity").evaluate(Pt,Ut);K7(w,st.id,Ut,st.featureProperties,st.nodeOverrideNames,st.nodeOverrides),Y7(w,st.id,Ut,st.featureProperties,st.materialOverrideNames,st.materialOverrides),st.nodeOverrides.size>0&&st.computeBoundsAndApplyParent(),st.computeModelMatrix(E,Vt,St,Ct,Z,V,!1);const Zt=o.cK([],Ze),Wt=o.e8(st.position.lat,E.transform.zoom),hs=o.bT([],[1,1,1/Wt]);Ve.push({zScaleMatrix:hs,negCameraPosMatrix:Zt});for(const ms of st.nodes)tE(E,ms,st.matrix,E.transform.expandedFarZProjMatrix,vt,Xe,ht,st.materialOverrides,qt);vt++}if(Xe.sort((st,Ut)=>Ut.depth-st.depth),E.renderPass!=="shadow"){if(E._debugParams.show3DModelFootprints){const st=E.transform.projMatrix,Ut=new Map,Pt=(St,Ct)=>{if(St.footprint){const qt=St.id||St.name||"footprint";if(!Ut.has(qt)){const Zt=o.aC([],st,Ct);Ut.set(qt,{node:St,mvp:Zt})}}};for(const St of ht)Pt(St.node,St.modelMatrix);for(const St of Xe)Pt(St.node,St.modelMatrix);const Vt=Array.from(Ut.keys()).sort();for(const St of Vt){const{node:Ct,mvp:qt}=Ut.get(St);N6(E,0,Ct,qt)}}k6(E,w,Xe,ht,Ve),Ae()}else{for(const st of ht)Q1(st.mesh,st.nodeModelMatrix,E,w);for(const st of Xe)Q1(st.mesh,st.nodeModelMatrix,E,w);Ae()}}},C6={line:function(E,f,w){if(E.hasElevatedBuckets=!1,E.hasNonElevatedBuckets=!1,E._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||E._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(f){const I=f.getVisibleCoordinates();for(const R of I){const q=f.getTile(R).getBucket(E);if(q&&(q.elevationType!=="none"?E.hasElevatedBuckets=!0:E.hasNonElevatedBuckets=!0,E.hasElevatedBuckets&&E.hasNonElevatedBuckets))break}}}else E.hasNonElevatedBuckets=!0},model:function(E,f,w){const I=f.getSource();if(!I.loaded())return;if(I.type==="vector"||I.type==="geojson")return void(w.modelManager&&w.modelManager.upload(w,zN(w,E)));if(I.type==="batched-model"||I.type!=="model")return;const R=I.getModels();for(const q of R)q.upload(w.context)},raster:function(E,f,w){const I=f.getSource();if(!(I instanceof Jr&&I.loaded()))return;const R=E.sourceLayer||I.rasterLayerIds&&I.rasterLayerIds[0];if(!R)return;const q=E.paint.get("raster-array-band")||I.getInitialBand(R);if(q==null)return;const V=f.getIds().map(Z=>f.getTileByID(Z));for(const Z of V)Z.updateNeeded(E.id,q)&&I.prepareTile(Z,R,E.id,q)}},t9={fill:lr},mw={fill:function(E,f,w,I){if(!w.layout||w.layout.get("fill-elevation-reference")==="none"||w.paint.get("fill-opacity").constantOr(1)===0)return;const R=E.context.gl,q=new Br(R.LEQUAL,Br.ReadOnly,E.depthRangeFor3D),V=new kn({func:R.ALWAYS,mask:255},255,255,R.KEEP,R.KEEP,R.REPLACE),Z=E.transform.getFreeCameraOptions().position,te=E.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const le of I){const pe=f.getTile(le),Ae=pe.getBucket(w);if(!Ae)continue;const _e=Ae.elevatedStructures;if(!_e||!_e.depthSegments||_e.depthSegments.segments[0].primitiveLength===0)continue;const Le=rr(le.toUnwrapped(),Z),Ve=E.translatePosMatrix(le.projMatrix,pe,w.paint.get("fill-translate"),w.paint.get("fill-translate-anchor")),qe=iw(Ve,Le,0,1,0);te.draw(E,R.TRIANGLES,q,V,En.disabled,en.disabled,qe,w.id,_e.vertexBuffer,_e.indexBuffer,_e.depthSegments,w.paint,E.transform.zoom)}}};class s9{constructor(f,w,I,R,q){this.context=new oh(f,w),this.transform=I,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,dt:0,timeStamp:o.o.now(),continousRedraw:!1,enabledLayers:{},buildingsShowNormals:!1,buildingsDrawGroundAO:!0,buildingsDrawShadowPass:!0,buildingsDrawTranslucentPass:!0,showTerrainProxyTiles:!1,terrainSortTilesHiZFirst:!0,terrainDisableRenderCache:!1,forceEnablePrecipitation:!1,overrideSnowParams:!1,snowParamsOverride:null,snowRevealParamsOverride:null,snowVignetteParamsOverride:null,overrideRainParams:!1,rainParamsOverride:null,rainRevealParamsOverride:null,rainVignetteParamsOverride:null,overrideStarsParams:!1,starsParamsOverride:null,show3DModelFootprints:!1,showElevationIdDebug:!1,lodSwitchDistance:3e3},this.occlusionParams=new hw,this.setup(),this.numSublayers=$a.maxUnderzooming+$a.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._shadowCullCache=null,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eJ,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new n7(this),this._wireframeDebugCache=new Gi,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const V=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,V,f.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=R,this.maxFrontCutoffRawStart=0,this.worldview=q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(f,w){const I=!!f&&!!f.terrain&&this.transform.projection.supportsTerrain;if(!(I||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new fy(this,f));const R=this._terrain;this.transform.elevation=I?R:null,R.update(f,this.transform,w),this.transform.elevation&&!R.enabled&&(this.transform.elevation=null)}_updateFog(f){const w=f.fog;if(!w||this.transform.projection.name==="globe"||w.getOpacity(this.transform.pitch)<1||w.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[I,R]=w.getRangeForProjection();if(I>R)return void(this.transform.fogCullDistSq=null);const q=I+.78*(R-I);this.transform.fogCullDistSq=q*q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(f){f&&!this._terrain&&(this._terrain=new fy(this,this.style)),this._forceTerrainMode=f}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(f,w){if(this.width=f*o.o.devicePixelRatio,this.height=w*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const I of this.style.order)this.style._mergedLayers[I].resize()}setup(){const f=this.context,w=new o.dE;w.emplaceBack(0,0),w.emplaceBack(o.ak,0),w.emplaceBack(0,o.ak),w.emplaceBack(o.ak,o.ak),this.tileExtentBuffer=f.createVertexBuffer(w,o.dA.members),this.tileExtentSegments=o.dB.simpleSegment(0,0,4,2);const I=new o.dE;I.emplaceBack(0,0),I.emplaceBack(o.ak,0),I.emplaceBack(0,o.ak),I.emplaceBack(o.ak,o.ak),this.debugBuffer=f.createVertexBuffer(I,o.dA.members),this.debugSegments=o.dB.simpleSegment(0,0,4,5);const R=new o.dE;R.emplaceBack(-1,-1),R.emplaceBack(1,-1),R.emplaceBack(-1,1),R.emplaceBack(1,1),this.viewportBuffer=f.createVertexBuffer(R,o.dA.members),this.viewportSegments=o.dB.simpleSegment(0,0,4,2);const q=new o.eK;q.emplaceBack(0,0,0,0),q.emplaceBack(o.ak,0,o.ak,0),q.emplaceBack(0,o.ak,0,o.ak),q.emplaceBack(o.ak,o.ak,o.ak,o.ak),this.mercatorBoundsBuffer=f.createVertexBuffer(q,o.eL.members),this.mercatorBoundsSegments=o.dB.simpleSegment(0,0,4,2);const V=new o.dF;V.emplaceBack(0,1,2),V.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=f.createIndexBuffer(V);const Z=new o.eM;for(const le of[0,1,3,2,0])Z.emplaceBack(le);this.debugIndexBuffer=f.createIndexBuffer(Z),this.emptyTexture=new o.T(f,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),f.gl.RGBA8),this.identityMat=o.bd();const te=this.context.gl;this.stencilClearMode=new kn({func:te.ALWAYS,mask:0},0,255,te.ZERO,te.ZERO,te.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(f){return f._makeTileBoundsBuffers(this.context,this.transform.projection),f._tileBoundsBuffer?{tileBoundsBuffer:f._tileBoundsBuffer,tileBoundsIndexBuffer:f._tileBoundsIndexBuffer,tileBoundsSegments:f._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const f=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,f.TRIANGLES,Br.disabled,this.stencilClearMode,En.disabled,en.disabled,G1(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(f,w,I){if(!w||this.currentStencilSource===w.id||!f.isTileClipped()||!I||I.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let Z=!1;for(const te of I)if(this._tileClippingMaskIDs[te.key]===void 0){Z=!0;break}if(!Z)return}this.currentStencilSource=w.id;const R=this.context,q=R.gl;this.nextStencilID+I.length>256&&this.clearStencil(),R.setColorMode(En.disabled),R.setDepthMode(Br.disabled);const V=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const Z of I){const te=w.getTile(Z),le=this._tileClippingMaskIDs[Z.key]=this.nextStencilID++,{tileBoundsBuffer:pe,tileBoundsIndexBuffer:Ae,tileBoundsSegments:_e}=this.getTileBoundsBuffers(te);V.draw(this,q.TRIANGLES,Br.disabled,new kn({func:q.ALWAYS,mask:0},le,255,q.KEEP,q.KEEP,q.REPLACE),En.disabled,en.disabled,G1(Z.projMatrix),"$clipping",pe,Ae,_e)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const f=this.nextStencilID++,w=this.context.gl;return new kn({func:w.NOTEQUAL,mask:255},f,255,w.KEEP,w.KEEP,w.REPLACE)}stencilModeForClipping(f){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(f);const w=this.context.gl;return new kn({func:w.EQUAL,mask:255},this._tileClippingMaskIDs[f.key],0,w.KEEP,w.KEEP,w.REPLACE)}stencilConfigForOverlap(f){const w=this.context.gl,I=f.sort((V,Z)=>Z.overscaledZ-V.overscaledZ),R=I.at(-1).overscaledZ,q=I[0].overscaledZ-R+1;if(q>1){this.currentStencilSource=void 0,this.nextStencilID+q>256&&this.clearStencil();const V={};for(let Z=0;Zthis.style._getOrder(R);let V=q(),Z=!1,te=!1,le=null,pe=0,Ae=!1;for(const ts of V){const Ns=I[ts];Ns.visibility!=="none"&&(Ns.type==="circle"?Z=!0:Ns.type==="building"?(le=Ns,++pe):Ns.type==="symbol"&&(Ns.hasOcclusionOpacityProperties?te=!0:Z=!0))}this.updateEmissiveMode();let _e=V.map(ts=>I[ts]);const Le=this.style._mergedSourceCaches;this.imageManager=f.imageManager,this.modelManager=f.modelManager,this.symbolFadeChange=f.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const ts in Le){const Ns=Le[ts];Ns.used&&(Ns.prepare(this.context),Ns.getSource().usedInConflation&&++pe)}let Ve=!1;for(const ts of _e)ts.isHidden(this.transform.zoom)||(ts.type==="clip"&&(Ve=!0),this.prepareLayer(ts));const qe={},Ze={},Xe={},ht={},vt={};for(const ts in Le){const Ns=Le[ts];qe[ts]=Ns.getVisibleCoordinates(),Ze[ts]=qe[ts].slice().reverse(),Xe[ts]=Ns.getVisibleCoordinates(!0).reverse(),ht[ts]=Ns.getShadowCasterCoordinates(),vt[ts]=Ns.sortCoordinatesByDistance(qe[ts])}const st=ts=>{const Ns=this.style.getLayerSourceCache(ts);return Ns&&Ns.used?Ns.getSource():null};if(pe||Ve||this._clippingActiveLastFrame){const ts=[],Ns=[];let rs=0;for(const Ps of _e)this.isSourceForClippingOrConflation(Ps,st(Ps))&&(ts.push(Ps),Ns.push(rs)),rs++;if(ts&&(Ve||ts.length>1)||this._clippingActiveLastFrame){Ve=!1;const Ps=[];for(let Ms=0;Ms0){const Ps=st(Ns);Ps&&(this.minCutoffZoom=Math.max(Ps.minzoom,this.minCutoffZoom)),Ns.minzoom&&(this.minCutoffZoom=Math.max(Ns.minzoom,this.minCutoffZoom))}Ns.is3D(R)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=ts),this._lastOcclusionLayer=ts)}const Ut=this.style&&this.style.fog;Ut?(this._fogVisible=Ut.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Ut.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Xe),this.opaquePassCutoff=0,V=q(),_e=V.map(ts=>I[ts]));const Pt=this._shadowRenderer;if(Pt){Pt.updateShadowParameters(this.transform,this.style.directionalLight);for(const ts in Le)for(const Ns of qe[ts]){let rs={min:0,max:0};this.terrain&&(rs=this.terrain.getMinMaxForTile(Ns)||rs),Pt.addShadowReceiver(Ns.toUnwrapped(),rs.min,rs.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.eO(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new Z1),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let Vt=!(!this.style||!this.style.snow),St=!(!this.style||!this.style.rain);if(Vt&&!this._snow&&Wd.Snow&&(this._snow=new Wd.Snow),!Vt&&this._snow&&(this._snow.destroy(),delete this._snow),St&&!this._rain&&Wd.Rain&&(this._rain=new Wd.Rain),!St&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),le){this.buildingTileBorderManager||(this.buildingTileBorderManager=new w6);const ts=this.style.getLayerSourceCache(le);this.buildingTileBorderManager.updateBorders(ts,le)}if(!Nt.has(this.context.gl))return;this.renderPass="offscreen";for(const ts of _e){const Ns=f.getLayerSourceCache(ts);if(!ts.hasOffscreenPass()||ts.isHidden(this.transform.zoom))continue;const rs=Ns?Ze[Ns.id]:void 0;(ts.type==="custom"||ts.type==="raster"||ts.type==="raster-particle"||ts.isSky()||rs&&rs.length)&&this.renderLayer(this,Ns,ts,rs)}this.depthRangeFor3D=[0,1-(_e.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,ht)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ct=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),qt=(()=>{if(w.showOverdrawInspector)return o.C.black;const ts=this.style.fog;if(ts&&this.transform.projection.supportsFog){const Ns=this.style.getLut(ts.scope);if(!Ct){const rs=ts.properties.get("color-use-theme")==="none",Ps=ts.properties.get("color").toNonPremultipliedRenderColor(rs?null:Ns).toArray01();return new o.C(...Ps)}if(Ct){const rs=ts.properties.get("space-color-use-theme")==="none",Ps=ts.properties.get("space-color").toNonPremultipliedRenderColor(rs?null:Ns).toArray01();return new o.C(...Ps)}}return o.C.transparent})();if(this.context.clear({color:qt,depth:1}),this.clearStencil(),this._showOverdrawInspector=w.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ct&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=V.length-1;this.currentLayer>=0;this.currentLayer--){const ts=_e[this.currentLayer],Ns=f.getLayerSourceCache(ts);if(ts.isSky())continue;const rs=Ns?(ts.is3D(R)?vt:Ze)[Ns.id]:void 0;this._renderTileClippingMasks(ts,Ns,rs),this.renderLayer(this,Ns,ts,rs)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ct&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.ai(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer<_e.length;this.currentLayer++){const Rs=_e[this.currentLayer];if(t9[Rs.type]){const xr=this.style.getLayerSourceCache(Rs);t9[Rs.type](this,xr,Rs,Zt(Rs,xr),Ms)}}};Ps("initialize"),Ps("reset"),this.currentLayer=rs,Zs=!0}if(Z&&!hs&&this.terrain&&!this.transform.isOrthographic&&(hs=!0,this.blitDepth()),te&&ms!==-1&&this.currentLayer===ms+1&&!this.transform.isOrthographic&&this.blitDepth(),this.terrain||this._renderTileClippingMasks(ts,Ns,Ns?qe[Ns.id]:void 0),this.renderLayer(this,Ns,ts,Zt(ts,Ns)),!this.terrain&&Pt&&this.currentLayer===Wt){{this.clearStencil(),this.resetStencilClippingMasks();const rs=this.currentLayer;for(this.currentLayer=0;this.currentLayer<_e.length;this.currentLayer++){const Ps=_e[this.currentLayer];if(mw[Ps.type]){const Ms=this.style.getLayerSourceCache(Ps);mw[Ps.type](this,Ms,Ps,Zt(Ps,Ms))}}this.currentLayer=rs}if(Pt.drawGroundShadows(),this.firstLightBeamLayer<=this.currentLayer){const rs=this.currentLayer;for(this.renderPass="light-beam",this.currentLayer=this.firstLightBeamLayer;this.currentLayer<=rs;this.currentLayer++){const Ps=_e[this.currentLayer];if(!Ps.hasLightBeamPass())continue;const Ms=f.getLayerSourceCache(Ps);this.renderLayer(this,Ms,Ps,Ms?Ze[Ms.id]:void 0)}this.currentLayer=rs,this.renderPass="translucent"}}if(this.currentLayer>=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const rs=this.currentLayer;this.depthOcclusion=!0;for(const Ps of this.layersWithOcclusionOpacity){this.currentLayer=Ps;const Ms=_e[this.currentLayer],Rs=f.getLayerSourceCache(Ms),xr=Rs?Ze[Rs.id]:void 0;this.terrain||this._renderTileClippingMasks(Ms,Rs,Rs?qe[Rs.id]:void 0),this.renderLayer(this,Rs,Ms,xr)}this.depthOcclusion=!1,this.currentLayer=rs,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 ts=null;_e.forEach(Ns=>{const rs=f.getLayerSourceCache(Ns);rs&&!Ns.isHidden(this.transform.zoom)&&rs.getVisibleCoordinates().length&&(!ts||ts.getSource().maxzoom0?w.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(f,w,I,R,q){const V=I===void 0?this.terrain&&this.terrain.renderingToTexture:I,Z=R===void 0?this.terrainRenderModeElevated():R,te=q===void 0?this.transform.projection.name==="globe":q,le=[];return this.style&&this.style.enable3dLights()&&(f==="globeRaster"||f==="terrainRaster"?(le.push("LIGHTING_3D_MODE"),le.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):V||le.push("LIGHTING_3D_MODE")),Z&&(le.push("TERRAIN"),this.linearFloatFilteringSupported()&&le.push("TERRAIN_DEM_FLOAT_FORMAT")),te&&le.push("GLOBE"),!this._fogVisible||V||w!==void 0&&!w||le.push("FOG"),V&&le.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&le.push("OVERDRAW_INSPECTOR"),le}getOrCreateProgram(f,w){this.cache=this.cache||{};const{defines:I,config:R,overrideFog:q,overrideRtt:V,overrideTerrain:Z,overrideGlobe:te,precompiled:le}=w||{},pe=this.currentGlobalDefines(f,q,V,Z,te).concat(I||[]),Ae=this.getShaderSource(f),_e=O7[f]||Wd.programUniforms[f],Le=ZL.cacheKey(Ae,f,pe,R);return this.cache[Le]||(this.cache[Le]=new ZL(this.context,f,Ae,R,_e,pe,le)),this.cache[Le]}getShaderSource(f){return yye[f]||Wd.shaders&&Wd.shaders[f]}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 f=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(f.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(f,w){if(this.style.enable3dLights()){const I=this.style.directionalLight,R=this.style.ambientLight;if(I&&R){const q=((V,Z,te)=>{const le=V.properties.get("direction"),pe=V.properties.get("color-use-theme")==="none",Ae=V.properties.get("color").toNonPremultipliedRenderColor(pe?null:te.getLut(V.scope)).toArray01(),_e=V.properties.get("intensity"),Le=Z.properties.get("color-use-theme")==="none",Ve=Z.properties.get("color").toNonPremultipliedRenderColor(Le?null:te.getLut(Z.scope)).toArray01(),qe=Z.properties.get("intensity"),Ze=[le.x,le.y,le.z],Xe=o.dG(Ve,qe),ht=o.dG(Ae,_e);return{u_lighting_ambient_color:Xe,u_lighting_directional_dir:Ze,u_lighting_directional_color:ht,u_ground_radiance:w7(Ze,ht,Xe)}})(I,R,this.style);w.setLightsUniformValues(f,q)}}}uploadCommonUniforms(f,w,I,R,q){if(this.uploadCommonLightUniforms(f,w),this.terrain&&this.terrain.renderingToTexture)return;const V=this.style.fog;if(V){const Z=V.getOpacity(this.transform.pitch),te=((le,pe,Ae,_e,Le,Ve,qe,Ze,Xe,ht,vt,st)=>{const Ut=le.transform,Pt=pe.properties.get("color-use-theme")==="none",Vt=pe.properties.get("color").toNonPremultipliedRenderColor(Pt?null:le.style.getLut(pe.scope)).toArray01();Vt[3]=_e;const St=le.frameCounter/1e3%1,[Ct,qt]=pe.properties.get("vertical-range");return{u_fog_matrix:Ae?Ut.calculateFogTileMatrix(Ae):st||le.identityMat,u_fog_range:pe.getRangeForProjection(),u_fog_color:Vt,u_fog_horizon_blend:pe.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Ct,qt),qt],u_fog_temporal_offset:St,u_frustum_tl:Le,u_frustum_tr:Ve,u_frustum_br:qe,u_frustum_bl:Ze,u_globe_pos:Xe,u_globe_radius:ht,u_viewport:vt,u_globe_transition:o.ai(Ut.zoom),u_is_globe:+(Ut.projection.name==="globe")}})(this,V,I,Z,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],R);w.setFogUniformValues(f,te)}q&&w.setCutoffUniformValues(f,q.uniformValues)}setTileLoadedFlag(f){this.tileLoaded=f}saveCanvasCopy(){const f=this.canvasCopy();f&&(this.frameCopies.push(f),this.tileLoaded=!1)}canvasCopy(){const f=this.context.gl,w=f.createTexture();return f.bindTexture(f.TEXTURE_2D,w),f.copyTexImage2D(f.TEXTURE_2D,0,f.RGBA,0,0,f.drawingBufferWidth,f.drawingBufferHeight,0),w}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const f=this.style&&this.style.fog;return!!f&&f.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const f=this._backgroundTiles,w=this._backgroundTiles={},I=this.transform.coveringTiles({tileSize:512});for(const R of I)w[R.key]=f[R.key]||new o.b3(R,512,this.transform.tileZoom,this,void 0,this.worldview);return w}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(f,w){return!(!f.is3D(!(!this.terrain||!this.terrain.enabled))||f.type!=="clip"&&f.type!=="building"&&(f.minzoom&&f.minzoom>this.transform.zoom||(this.style._clipLayerPresent||f.sourceLayer!=="building"&&f.sourceLayer!=="procedural_buildings")&&(!w||w.type!=="batched-model")))}isTileAffectedByFog(f){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let w=this._cachedTileFogOpacities[f.key];return w||(this._cachedTileFogOpacities[f.key]=w=this.style.fog.getOpacityForTile(f)),w[0]>=Sp||w[1]>=Sp}setupDepthForOcclusion(f,w,I){const R=this.context,q=R.gl,V=!!I;var Z;I||(I={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}),R.activeTexture.set(q.TEXTURE3),f&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),I.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],I.u_depth_range_unpack=[2/((Z=this.depthRangeFor3D)[1]-Z[0]),-1-2*Z[0]/(Z[1]-Z[0])],I.u_occluder_half_size=.5*this.occlusionParams.occluderSize,I.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),R.activeTexture.set(q.TEXTURE0),V||w.setTerrainUniformValues(R,I)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const f=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=f?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function rE(E,f){let w=!1,I=null;const R=()=>{I=null,w&&(E(),I=setTimeout(R,f),w=!1)};return()=>(w=!0,I||R(),I)}const nE=/(#.+)?$/;class rg{constructor(f){this._hashName=f&&encodeURIComponent(f),o.b0(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=rE(this._updateHashUnthrottled.bind(this),300)}addTo(f){return this._map=f,window.addEventListener("hashchange",this._onHashChange,!1),f.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 f=this._map;if(!f)return"";const w=$N(f);if(this._hashName){const I=this._hashName;let R=!1;const q=location.hash.slice(1).split("&").map(V=>{const Z=V.split("=")[0];return Z===I?(R=!0,`${Z}=${w}`):V}).filter(V=>V);return R||q.push(`${I}=${w}`),`#${q.join("&")}`}return`#${w}`}_getCurrentHash(){const f=location.hash.replace("#","");if(this._hashName){let w;return f.split("&").map(I=>I.split("=")).forEach(I=>{I[0]===this._hashName&&(w=I)}),(w&&w[1]||"").split("/")}return f.split("/")}_onHashChange(){const f=this._map;if(!f)return!1;const w=this._getCurrentHash();if(w.length>=3&&!w.some(I=>isNaN(Number(I)))){const I=f.dragRotate.isEnabled()&&f.touchZoomRotate.isEnabled()?+(w[3]||0):f.getBearing();return f.jumpTo({center:[+w[2],+w[1]],zoom:+w[0],bearing:I,pitch:+(w[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(nE,this.getHashString()))}}function $N(E,f){const w=E.getCenter(),I=Math.round(100*E.getZoom())/100,R=Math.ceil((I*Math.LN2+Math.log(512/360/.5))/Math.LN10),q=Math.pow(10,R),V=Math.round(w.lng*q)/q,Z=Math.round(w.lat*q)/q,te=E.getBearing(),le=E.getPitch();let pe=f?`/${V}/${Z}/${I}`:`${I}/${Z}/${V}`;return(te||le)&&(pe+="/"+Math.round(10*te)/10),le&&(pe+=`/${Math.round(le)}`),pe}const wl={linearity:.3,easing:o.eQ(0,0,.3,1)},Uf=Object.assign({deceleration:2500,maxSpeed:1400},wl),UN=Object.assign({deceleration:20,maxSpeed:1400},wl),Rye=Object.assign({deceleration:1e3,maxSpeed:360},wl),T6=Object.assign({deceleration:1e3,maxSpeed:90},wl);class r9{constructor(f){this._map=f,this.clear()}clear(){this._inertiaBuffer=[]}record(f){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:f})}_drainInertiaBuffer(){const f=this._inertiaBuffer,w=o.o.now();for(;f.length>0&&w-f[0].time>160;)f.shift()}_onMoveEnd(f){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const w={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:q}of this._inertiaBuffer)w.zoom+=q.zoomDelta||0,w.bearing+=q.bearingDelta||0,w.pitch+=q.pitchDelta||0,q.panDelta&&w.pan._add(q.panDelta),q.around&&(w.around=q.around),q.pinchAround&&(w.pinchAround=q.pinchAround);const I=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,R={};if(w.pan.mag()){const q=fw(w.pan.mag(),I,Object.assign({},Uf,f||{}));R.offset=w.pan.mult(q.amount/w.pan.mag()),R.center=this._map.transform.center,$0(R,q)}if(w.zoom){const q=fw(w.zoom,I,UN);R.zoom=this._map.transform.zoom+q.amount,$0(R,q)}if(w.bearing){const q=fw(w.bearing,I,Rye);R.bearing=this._map.transform.bearing+o.aB(q.amount,-179,179),$0(R,q)}if(w.pitch){const q=fw(w.pitch,I,T6);R.pitch=this._map.transform.pitch+q.amount,$0(R,q)}if(R.zoom||R.bearing){const q=w.pinchAround===void 0?w.around:w.pinchAround;R.around=q?this._map.unproject(q):this._map.getCenter()}return this.clear(),R.noMoveStart=!0,R}}function $0(E,f){(!E.duration||E.durationw.unproject(te)),Z=q.reduce((te,le,pe,Ae)=>te.add(le.div(Ae.length)),new o.P(0,0));super(f,{points:q,point:Z,lngLats:V,lngLat:w.unproject(Z),originalEvent:I}),this._defaultPrevented=!1}}class aE extends o.z{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(f,w){super("wheel",{originalEvent:w}),this._defaultPrevented=!1}}class qN{constructor(f,w){this._map=f,this._clickTolerance=w.clickTolerance}reset(){this._mousedownPos=void 0}wheel(f){return this._firePreventable(new aE(this._map,f))}mousedown(f,w){return this._mousedownPos=w,this._firePreventable(new $h(f.type,this._map,f))}mouseup(f){this._map.fire(new $h(f.type,this._map,f))}preclick(f){const w=new MouseEvent("preclick",f);this._map.fire(new $h(w.type,this._map,w))}click(f,w){this._mousedownPos&&this._mousedownPos.dist(w)>=this._clickTolerance||(this.preclick(f),this._map.fire(new $h(f.type,this._map,f)))}dblclick(f){return this._firePreventable(new $h(f.type,this._map,f))}mouseover(f){this._map.fire(new $h(f.type,this._map,f))}mouseout(f){this._map.fire(new $h(f.type,this._map,f))}touchstart(f){return this._firePreventable(new J1(f.type,this._map,f))}touchmove(f){this._map.fire(new J1(f.type,this._map,f))}touchend(f){this._map.fire(new J1(f.type,this._map,f))}touchcancel(f){this._map.fire(new J1(f.type,this._map,f))}_firePreventable(f){if(this._map.fire(f),f.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class vy{constructor(f){this._map=f}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(f){this._map.fire(new $h(f.type,this._map,f))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new $h("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(f){this._delayContextMenu?this._contextMenuEvent=f:this._map.fire(new $h(f.type,this._map,f)),this._map.listens("contextmenu")&&f.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class ng{constructor(f,w){this._map=f,this._el=f.getCanvasContainer(),this._container=f.getContainer(),this._clickTolerance=w.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(f,w){this.isEnabled()&&f.shiftKey&&f.button===0&&(D(),this._startPos=this._lastPos=w,this._active=!0)}mousemoveWindow(f,w){if(!this._active)return;const I=w,R=this._startPos,q=this._lastPos;if(!R||!q||q.equals(I)||!this._box&&I.dist(R){this._box&&(this._box.style.transform=`translate(${V}px,${te}px)`,this._box.style.width=Z-V+"px",this._box.style.height=le-te+"px")})}mouseupWindow(f,w){if(!this._active)return;const I=this._startPos,R=w;if(I&&f.button===0){if(this.reset(),F(),I.x!==R.x||I.y!==R.y)return this._map.fire(new o.z("boxzoomend",{originalEvent:f})),{cameraAnimation:q=>q.fitScreenCoordinates(I,R,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",f)}}keydown(f){this._active&&f.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",f))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),B(),delete this._startPos,delete this._lastPos}_fireEvent(f,w){return this._map.fire(new o.z(f,{originalEvent:w}))}}function qf(E,f){const w={};for(let I=0;Ithis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=f.timeStamp),I.length===this.numTouches&&(this.centroid=function(R){const q=new o.P(0,0);for(const V of R)q._add(V);return q.div(R.length)}(w),this.touches=qf(I,w)))}touchmove(f,w,I){if(this.aborted||!this.centroid)return;const R=qf(I,w);for(const q in this.touches){const V=R[q];(!V||V.dist(this.touches[q])>30)&&(this.aborted=!0)}}touchend(f,w,I){if((!this.centroid||f.timeStamp-this.startTime>500)&&(this.aborted=!0),I.length===0){const R=!this.aborted&&this.centroid;if(this.reset(),R)return R}}}class Xm{constructor(f){this.singleTap=new eb(f),this.numTaps=f.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(f,w,I){this.singleTap.touchstart(f,w,I)}touchmove(f,w,I){this.singleTap.touchmove(f,w,I)}touchend(f,w,I){const R=this.singleTap.touchend(f,w,I);if(R){const q=f.timeStamp-this.lastTime<500,V=!this.lastTap||this.lastTap.dist(R)<30;if(q&&V||this.reset(),this.count++,this.lastTime=f.timeStamp,this.lastTap=R,this.count===this.numTaps)return this.reset(),R}}}class Oye{constructor(){this._zoomIn=new Xm({numTouches:1,numTaps:2}),this._zoomOut=new Xm({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(f,w,I){this._zoomIn.touchstart(f,w,I),this._zoomOut.touchstart(f,w,I)}touchmove(f,w,I){this._zoomIn.touchmove(f,w,I),this._zoomOut.touchmove(f,w,I)}touchend(f,w,I){const R=this._zoomIn.touchend(f,w,I),q=this._zoomOut.touchend(f,w,I);return R?(this._active=!0,f.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:V=>V.easeTo({duration:300,zoom:V.getZoom()+1,around:V.unproject(R)},{originalEvent:f})}):q?(this._active=!0,f.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:V=>V.easeTo({duration:300,zoom:V.getZoom()-1,around:V.unproject(q)},{originalEvent:f})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Fye=0,Bye=2,zye={[Fye]:1,[Bye]:2},E6={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class mu{constructor(f){this.reset(),this._clickTolerance=f.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(f,w){return!1}_move(f,w){return{}}mousedown(f,w){if(this._lastPoint)return;const I=K(f);this._correctButton(f,I)&&(this._lastPoint=w,this._eventButton=I)}mousemoveWindow(f,w){const I=this._lastPoint;if(I){if(f.preventDefault(),this._eventButton!=null&&function(R,q){const V=zye[q];return R.buttons===void 0||(R.buttons&V)!==V}(f,this._eventButton))this.reset();else if(this._moved||!(w.dist(I)0&&(this._active=!0);const R=qf(I,w),q=new o.P(0,0),V=new o.P(0,0);let Z=0;for(const le in R){const pe=R[le],Ae=this._touches[le];Ae&&(q._add(pe),V._add(pe.sub(Ae)),Z++,R[le]=pe)}if(this._touches=R,Z{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class U0{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(f){}_move(f,w,I){return{}}touchstart(f,w,I){this._firstTwoTouches||I.length<2||(this._firstTwoTouches=[I[0].identifier,I[1].identifier],this._start([w[0],w[1]]))}touchmove(f,w,I){const R=this._firstTwoTouches;if(!R)return;f.preventDefault();const[q,V]=R,Z=ag(I,w,q),te=ag(I,w,V);if(!Z||!te)return;const le=this._aroundCenter?null:Z.add(te).div(2);return this._move([Z,te],le,f)}touchend(f,w,I){if(!this._firstTwoTouches)return;const[R,q]=this._firstTwoTouches,V=ag(I,w,R),Z=ag(I,w,q);V&&Z||(this._active&&F(),this.reset())}touchcancel(){this.reset()}enable(f){this._enabled=!0,this._aroundCenter=!!f&&f.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function ag(E,f,w){for(let I=0;IMath.abs(E.x)}class by extends U0{constructor(f){super(),this._map=f}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(f){this._lastPoints=f,VN(f[0].sub(f[1]))&&(this._valid=!1)}_move(f,w,I){const R=this._lastPoints;if(!R)return;const q=f[0].sub(R[0]),V=f[1].sub(R[1]);return this._map._cooperativeGestures&&!o.eR()&&I.touches.length<3||(this._valid=this.gestureBeginsVertically(q,V,I.timeStamp),!this._valid)?void 0:(this._lastPoints=f,this._active=!0,{pitchDelta:(q.y+V.y)/2*-.5})}gestureBeginsVertically(f,w,I){if(this._valid!==void 0)return this._valid;const R=f.mag()>=2,q=w.mag()>=2;if(!R&&!q)return;if(!R||!q)return this._firstMove==null&&(this._firstMove=I),I-this._firstMove<100&&void 0;const V=f.y>0==w.y>0;return VN(f)&&VN(w)&&V}}const ig={panStep:100,bearingStep:15,pitchStep:10};class ch{constructor(){const f=ig;this._panStep=f.panStep,this._bearingStep=f.bearingStep,this._pitchStep=f.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(f){if(f.altKey||f.ctrlKey||f.metaKey)return;let w=0,I=0,R=0,q=0,V=0;switch(f.keyCode){case 61:case 107:case 171:case 187:w=1;break;case 189:case 109:case 173:w=-1;break;case 37:f.shiftKey?I=-1:(f.preventDefault(),q=-1);break;case 39:f.shiftKey?I=1:(f.preventDefault(),q=1);break;case 38:f.shiftKey?R=1:(f.preventDefault(),V=-1);break;case 40:f.shiftKey?R=-1:(f.preventDefault(),V=1);break;default:return}return this._rotationDisabled&&(I=0,R=0),{cameraAnimation:Z=>{const te=Z.getZoom();Z.easeTo({duration:300,easeId:"keyboardHandler",easing:ym,zoom:w?Math.round(te)+w*(f.shiftKey?2:1):te,bearing:Z.getBearing()+I*this._bearingStep,pitch:Z.getPitch()+R*this._pitchStep,offset:[-q*this._panStep,-V*this._panStep],center:Z.getCenter()},{originalEvent:f})}}}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 ym(E){return E*(2-E)}const Xc=4.000244140625,M6=1/450,vm=/(Mac|iPad)/i;class n9{constructor(f,w){this._map=f,this._el=f.getCanvasContainer(),this._handler=w,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=M6,o.b0(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(f){this._defaultZoomRate=f}setWheelZoomRate(f){this._wheelZoomRate=f}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(f){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!f&&f.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(f){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(f.ctrlKey||f.metaKey||this.isZooming()||o.eR()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let w=f.deltaMode===WheelEvent.DOM_DELTA_LINE?40*f.deltaY:f.deltaY;const I=o.o.now(),R=I-(this._lastWheelEventTime||0);this._lastWheelEventTime=I,w!==0&&w%Xc===0?this._type="wheel":w!==0&&Math.abs(w)<4?this._type="trackpad":R>400?(this._type=null,this._lastValue=w,this._timeout=window.setTimeout(this._onTimeout,40,f)):this._type||(this._type=Math.abs(R*w)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,w+=this._lastValue)),f.shiftKey&&w&&(w/=4),this._type&&(this._lastWheelEvent=f,this._delta-=w,this._active||this._start(f)),f.preventDefault()}_onTimeout(f){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(f)}_start(f){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 w=$(this._el,f);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:w,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 f=this._map.transform;this._type==="wheel"&&f.projection.wrap&&(f._center.lng>=180||f._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const w=()=>f._terrainEnabled()&&this._aroundCoord?f.computeZoomRelativeTo(this._aroundCoord):f.zoom;if(this._delta!==0){const le=this._type==="wheel"&&Math.abs(this._delta)>Xc?this._wheelZoomRate:this._defaultZoomRate;let pe=2/(1+Math.exp(-Math.abs(this._delta*le)));this._delta<0&&pe!==0&&(pe=1/pe);const Ae=w(),_e=Math.pow(2,Ae),Le=typeof this._targetZoom=="number"?f.zoomScale(this._targetZoom):_e;this._targetZoom=Math.min(f.maxZoom,Math.max(f.minZoom,f.scaleZoom(Le*pe))),this._type==="wheel"&&(this._startZoom=Ae,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const I=typeof this._targetZoom=="number"?this._targetZoom:w(),R=this._startZoom,q=this._easing;let V,Z=!1;if(this._type==="wheel"&&R&&q){const le=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),pe=q(le);V=o.aj(R,I,pe),le<1?this._frameId||(this._frameId=!0):Z=!0}else V=I,Z=!0;this._active=!0,Z&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let te=V-w();return te*this._lastDelta<0&&(te=0),{noInertia:!0,needsRenderFrame:!Z,zoomDelta:te,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(f){let w=o.eS;if(this._prevEase){const I=this._prevEase,R=(o.o.now()-I.start)/I.duration,q=I.easing(R+.01)-I.easing(R),V=.27/Math.sqrt(q*q+1e-4)*.01,Z=Math.sqrt(.0729-V*V);w=o.eQ(V,Z,.25,1)}return this._prevEase={start:o.o.now(),duration:f,easing:w},w}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=N("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=vm.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 sb{constructor(f,w){this._clickZoom=f,this._tapZoom=w}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 a9{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(f,w){return f.preventDefault(),{cameraAnimation:I=>{I.easeTo({duration:300,zoom:I.getZoom()+(f.shiftKey?-1:1),around:I.unproject(w)},{originalEvent:f})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Jm{constructor(){this._tap=new Xm({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(f,w,I){this._swipePoint||(this._tapTime&&f.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?I.length>0&&(this._swipePoint=w[0],this._swipeTouch=I[0].identifier):this._tap.touchstart(f,w,I))}touchmove(f,w,I){if(this._tapTime){if(this._swipePoint){if(I[0].identifier!==this._swipeTouch)return;const R=w[0],q=R.y-this._swipePoint.y;return this._swipePoint=R,f.preventDefault(),this._active=!0,{zoomDelta:q/128}}}else this._tap.touchmove(f,w,I)}touchend(f,w,I){this._tapTime?this._swipePoint&&I.length===0&&this.reset():this._tap.touchend(f,w,I)&&(this._tapTime=f.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class fu{constructor(f,w,I){this._el=f,this._mousePan=w,this._touchPan=I}enable(f){this._inertiaOptions=f||{},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 I6{constructor(f,w,I){this._pitchWithRotate=f.pitchWithRotate,this._mouseRotate=w,this._mousePitch=I}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 i9{constructor(f,w,I,R){this._el=f,this._touchZoom=w,this._touchRotate=I,this._tapDragZoom=R,this._rotationDisabled=!1,this._enabled=!0}enable(f){this._touchZoom.enable(f),this._rotationDisabled||this._touchRotate.enable(f),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 xw=E=>E.zoom||E.drag||E.pitch||E.rotate;class $ye extends o.z{}class P6{constructor(){this.constants=[1,1,.01],this.radius=0}setup(f,w){const I=o.aw([],w,f);this.radius=o.af(I[2]<0?o.eU([],I,this.constants):[I[0],I[1],0])}projectRay(f){o.eU(f,f,this.constants),o.ax(f,f),o.eV(f,f,this.constants);const w=o.bN([],f,this.radius);if(w[2]>0){const I=o.bN([],[0,0,1],o.bk(w,[0,0,1])),R=o.bN([],o.ax([],[w[0],w[1],0]),this.radius),q=o.cX([],w,o.bN([],o.aw([],o.cX([],R,I),w),2));w[0]=q[0],w[1]=q[1]}return w}}function HN(E){return E.panDelta&&E.panDelta.mag()||E.zoomDelta||E.bearingDelta||E.pitchDelta}class Uye{constructor(f,w){this._map=f,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new r9(f),this._bearingSnap=w.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new P6,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(w),o.b0(["handleEvent","handleWindowEvent"],this);const I=this._el;this._listeners=[[I,"touchstart",{passive:!0}],[I,"touchmove",{passive:!1}],[I,"touchend",void 0],[I,"touchcancel",void 0],[I,"mousedown",void 0],[I,"mousemove",void 0],[I,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[I,"mouseover",void 0],[I,"mouseout",void 0],[I,"dblclick",void 0],[I,"click",void 0],[I,"keydown",{capture:!1}],[I,"keyup",void 0],[I,"wheel",{passive:!1}],[I,"contextmenu",void 0],[window,"blur",void 0]];for(const[R,q,V]of this._listeners){const Z=R===document?this.handleWindowEvent:this.handleEvent;R.addEventListener(q,Z,V)}}destroy(){for(const[f,w,I]of this._listeners){const R=f===document?this.handleWindowEvent:this.handleEvent;f.removeEventListener(w,R,I)}}_addDefaultHandlers(f){const w=this._map,I=w.getCanvasContainer();this._add("mapEvent",new qN(w,f));const R=w.boxZoom=new ng(w,f);this._add("boxZoom",R);const q=new Oye,V=new a9;w.doubleClickZoom=new sb(V,q),this._add("tapZoom",q),this._add("clickZoom",V);const Z=new Jm;this._add("tapDragZoom",Z);const te=w.touchPitch=new by(w);this._add("touchPitch",te);const le=new iE(f),pe=new Qm(f);w.dragRotate=new I6(f,le,pe),this._add("mouseRotate",le,["mousePitch"]),this._add("mousePitch",pe,["mouseRotate"]);const Ae=new pw(f),_e=new Vf(w,f);w.dragPan=new fu(I,Ae,_e),this._add("mousePan",Ae),this._add("touchPan",_e,["touchZoom","touchRotate"]);const Le=new q0,Ve=new A6;w.touchZoomRotate=new i9(I,Ve,Le,Z),this._add("touchRotate",Le,["touchPan","touchZoom"]),this._add("touchZoom",Ve,["touchPan","touchRotate"]),this._add("blockableMapEvent",new vy(w));const qe=w.scrollZoom=new n9(w,this);this._add("scrollZoom",qe,["mousePan"]);const Ze=w.keyboard=new ch;this._add("keyboard",Ze);for(const Xe of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])f.interactive&&f[Xe]&&w[Xe].enable(f[Xe])}_add(f,w,I){this._handlers.push({handlerName:f,handler:w,allowed:I}),this._handlersById[f]=w}stop(f){if(!this._updatingCamera){for(const{handler:w}of this._handlers)w.reset();this._inertia.clear(),this._fireEvents({},{},f),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:f}of this._handlers)if(f.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!xw(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(f,w,I){for(const R in f)if(!(R===I||w&&w.includes(R)))return!0;return!1}handleWindowEvent(f){this.handleEvent(f,`${f.type}Window`)}_getMapTouches(f){const w=[];for(const I of f)this._el.contains(I.target)&&w.push(I);return w}handleEvent(f,w){this._updatingCamera=!0;const I=f.type==="renderFrame",R=I?void 0:f,q={needsRenderFrame:!1},V={},Z={},te=f.touches?this._getMapTouches(f.touches):void 0,le=te?X(this._el,te):I?void 0:$(this._el,f);for(const{handlerName:_e,handler:Le,allowed:Ve}of this._handlers){if(!Le.isEnabled())continue;let qe;this._blockedByActive(Z,Ve,_e)?Le.reset():Le[w||f.type]&&(qe=Le[w||f.type](f,le,te),this.mergeHandlerResult(q,V,qe,_e,R),qe&&qe.needsRenderFrame&&this._triggerRenderFrame()),(qe||Le.isActive())&&(Z[_e]=Le)}const pe={};for(const _e in this._previousActiveHandlers)Z[_e]||(pe[_e]=R);this._previousActiveHandlers=Z,(Object.keys(pe).length||HN(q))&&(this._changes.push([q,V,pe]),this._triggerRenderFrame()),(Object.keys(Z).length||HN(q))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Ae}=q;Ae&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ae(this._map))}mergeHandlerResult(f,w,I,R,q){if(!I)return;Object.assign(f,I);const V={handlerName:R,originalEvent:I.originalEvent||q};I.zoomDelta!==void 0&&(w.zoom=V),I.panDelta!==void 0&&(w.drag=V),I.pitchDelta!==void 0&&(w.pitch=V),I.bearingDelta!==void 0&&(w.rotate=V)}_applyChanges(){const f={},w={},I={};for(const[R,q,V]of this._changes)R.panDelta&&(f.panDelta=(f.panDelta||new o.P(0,0))._add(R.panDelta)),R.zoomDelta&&(f.zoomDelta=(f.zoomDelta||0)+R.zoomDelta),R.bearingDelta&&(f.bearingDelta=(f.bearingDelta||0)+R.bearingDelta),R.pitchDelta&&(f.pitchDelta=(f.pitchDelta||0)+R.pitchDelta),R.around!==void 0&&(f.around=R.around),R.aroundCoord!==void 0&&(f.aroundCoord=R.aroundCoord),R.pinchAround!==void 0&&(f.pinchAround=R.pinchAround),R.noInertia&&(f.noInertia=R.noInertia),Object.assign(w,q),Object.assign(I,V);this._updateMapTransform(f,w,I),this._changes=[]}_updateMapTransform(f,w,I){const R=this._map,q=R.transform,V=ht=>[ht.x,ht.y,ht.z];if((()=>{const ht=this._eventsInProgress.drag;return ht&&!this._handlersById[ht.handlerName].isActive()})()&&!HN(f)){const ht=q.zoom;q.cameraElevationReference="sea",this._originalZoom!=null&&q._orthographicProjectionAtLowPitch&&q.projection.name!=="globe"&&q.pitch===0?(q.cameraElevationReference="ground",q.zoom=this._originalZoom):(q.recenterOnTerrain(),q.cameraElevationReference="ground"),ht!==q.zoom&&this._map._update(!0)}if(q._isCameraConstrained&&R._stop(!0),!HN(f))return void this._fireEvents(w,I,!0);let{panDelta:Z,zoomDelta:te,bearingDelta:le,pitchDelta:pe,around:Ae,aroundCoord:_e,pinchAround:Le}=f;q._isCameraConstrained&&(te>0&&(te=0),q._isCameraConstrained=!1),Le!==void 0&&(Ae=Le),(te||(ht=>w[ht]&&!this._eventsInProgress[ht])("drag"))&&Ae&&(this._dragOrigin=V(q.pointCoordinate3D(Ae)),this._originalZoom=q.zoom,this._trackingEllipsoid.setup(q._camera.position,this._dragOrigin)),q.cameraElevationReference="sea",R._stop(!0),Ae=Ae||R.transform.centerPoint,le&&(q.bearing+=le),pe&&(q.pitch+=pe),q._updateCameraState();const Ve=[0,0,0];if(Z)if(q.projection.name==="mercator"){const ht=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ae).dir),vt=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ae.sub(Z)).dir);Ve[0]=vt[0]-ht[0],Ve[1]=vt[1]-ht[1]}else{const ht=q.pointCoordinate(Ae);if(q.projection.name==="globe"){Z=Z.rotate(-q.angle);const vt=q._pixelsPerMercatorPixel/q.worldSize;Ve[0]=-Z.x*o.eT(o.bZ(ht.y))*vt,Ve[1]=-Z.y*o.eT(q.center.lat)*vt}else{const vt=q.pointCoordinate(Ae.sub(Z));ht&&vt&&(Ve[0]=vt.x-ht.x,Ve[1]=vt.y-ht.y)}}const qe=q.zoom,Ze=[0,0,0];if(te){const ht=V(_e||q.pointCoordinate3D(Ae)),vt={dir:o.ax([],o.aw([],ht,q._camera.position))};if(vt.dir[2]<0){const st=q.zoomDeltaToMovement(ht,te);o.bN(Ze,vt.dir,st)}}const Xe=o.cX(Ve,Ve,Ze);q._translateCameraConstrained(Xe),te&&Math.abs(q.zoom-qe)>1e-4&&q.recenterOnTerrain(),q.cameraElevationReference="ground",this._map._update(),f.noInertia||this._inertia.record(f),this._fireEvents(w,I,!0)}_fireEvents(f,w,I){const R=xw(this._eventsInProgress),q=xw(f),V={};for(const pe in f){const{originalEvent:Ae}=f[pe];this._eventsInProgress[pe]||(V[`${pe}start`]=Ae),this._eventsInProgress[pe]=f[pe]}!R&&q&&this._fireEvent("movestart",q.originalEvent);for(const pe in V)this._fireEvent(pe,V[pe]);q&&this._fireEvent("move",q.originalEvent);for(const pe in f){const{originalEvent:Ae}=f[pe];this._fireEvent(pe,Ae)}const Z={};let te;for(const pe in this._eventsInProgress){const{handlerName:Ae,originalEvent:_e}=this._eventsInProgress[pe];this._handlersById[Ae].isActive()||(delete this._eventsInProgress[pe],te=w[Ae]||_e,Z[`${pe}end`]=te)}for(const pe in Z)this._fireEvent(pe,Z[pe]);const le=xw(this._eventsInProgress);if(I&&(R||q)&&!le){this._updatingCamera=!0;const pe=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ae=_e=>_e!==0&&-this._bearingSnap<_e&&_e{this._frameId=void 0,this.handleEvent(new $ye("renderFrame",{timeStamp:f})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const bm="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Hf extends o.E{constructor(f,w){super(),this._moving=!1,this._zooming=!1,this.transform=f,this._bearingSnap=w.bearingSnap,this._respectPrefersReducedMotion=w.respectPrefersReducedMotion!==!1,o.b0(["_renderFrameCallback"],this)}getCenter(){return new o.aX(this.transform.center.lng,this.transform.center.lat)}setCenter(f,w){return this.jumpTo({center:f},w)}panBy(f,w,I){return f=o.P.convert(f).mult(-1),this.panTo(this.transform.center,Object.assign({offset:f},w),I)}panTo(f,w,I){return this.easeTo(Object.assign({center:f},w),I)}getZoom(){return this.transform.zoom}setZoom(f,w){return this.jumpTo({zoom:f},w),this}zoomTo(f,w,I){return this.easeTo(Object.assign({zoom:f},w),I)}zoomIn(f,w){return this.zoomTo(this.getZoom()+1,f,w),this}zoomOut(f,w){return this.zoomTo(this.getZoom()-1,f,w),this}getBearing(){return this.transform.bearing}setBearing(f,w){return this.jumpTo({bearing:f},w),this}getPadding(){return this.transform.padding}setPadding(f,w){return this.jumpTo({padding:f},w),this}rotateTo(f,w,I){return this.easeTo(Object.assign({bearing:f},w),I)}resetNorth(f,w){return this.rotateTo(0,Object.assign({duration:1e3},f),w),this}resetNorthPitch(f,w){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},f),w),this}snapToNorth(f,w){return Math.abs(this.getBearing())f.aspect?I/(2*Math.tan(.5*f.fovX)*f.aspect):R/(2*Math.tan(.5*f.fovY)*f.aspect)}_cameraForBoundsOnGlobe(f,w,I,R,q,V){const Z=f.clone(),te=this._extendCameraOptions(V);Z.bearing=R,Z.pitch=q;const le=o.aX.convert(w),pe=o.aX.convert(I),Ae=.5*(le.lat+pe.lat),_e=.5*(le.lng+pe.lng),Le=o.eW(Ae,_e),Ve=o.ax([],Le),qe=o.ax([],o.bj([],Ve,[0,1,0])),Ze=o.bj([],qe,Ve),Xe=[qe[0],qe[1],qe[2],0,Ze[0],Ze[1],Ze[2],0,Ve[0],Ve[1],Ve[2],0,0,0,0,1],ht=[Le,o.eW(le.lat,le.lng),o.eW(pe.lat,le.lng),o.eW(pe.lat,pe.lng),o.eW(le.lat,pe.lng),o.eW(Ae,le.lng),o.eW(Ae,pe.lng),o.eW(le.lat,_e),o.eW(pe.lat,_e)];let vt=o.cY.fromPoints(ht.map(Ms=>[o.bk(qe,Ms),o.bk(Ze,Ms),o.bk(Ve,Ms)]));const st=o.ae([],vt.center,Xe);o.eX(st)===0&&o.eY(st,0,0,1),o.ax(st,st),o.bN(st,st,o.aE),Z.center=o.eZ(st);const Ut=Z.getWorldToCameraMatrix(),Pt=o.ba(new Float64Array(16),Ut);vt=o.cY.applyTransform(vt,o.aC([],Ut,Xe));const Vt=this._extendAABB(vt,Z,te,R);if(!Vt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");vt=Vt,o.ae(st,st,Ut);const St=.5*(vt.max[2]-vt.min[2]),Ct=this._minimumAABBFrustumDistance(Z,vt),qt=o.bN([],[0,0,1],St),Zt=o.cX(qt,st,qt),Wt=Ct+(Z.pitch===0?0:o.bh(st,Zt)),hs=Z.globeCenterInViewSpace,ms=o.aw([],st,[hs[0],hs[1],hs[2]]);o.ax(ms,ms),o.bN(ms,ms,Wt);const Zs=o.cX([],st,ms);o.ae(Zs,Zs,Pt);const ts=o.eg/o.aE,Ns=o.af(Zs),rs=o.bY(Math.max(Ns*ts-o.eg,Number.EPSILON),0),Ps=Math.min(Z.zoomFromMercatorZAdjusted(rs),te.maxZoom);return Ps>.5*(o.cN+o.cx)?(Z.setProjection({name:"mercator"}),Z.zoom=Ps,this._cameraForBounds(Z,w,I,R,q,V)):{center:Z.center,zoom:Ps,bearing:R,pitch:q}}_extendAABB(f,w,I,R){const q=.5*((I.padding.left||0)+(I.padding.right||0)),V=.5*((I.padding.top||0)+(I.padding.bottom||0)),Z=V,te=q,le=q,pe=V,Ae=w.width-(te+le),_e=w.height-(Z+pe),Le=o.aw([],f.max,f.min),Ve=Math.min(Ae/Le[0],_e/Le[1]),qe=Math.min(w.scaleZoom(w.scale*Ve),I.maxZoom);if(isNaN(qe))return null;const Ze=w.scale/w.zoomScale(qe),Xe=new o.cY([f.min[0]-te*Ze,f.min[1]-pe*Ze,f.min[2]],[f.max[0]+le*Ze,f.max[1]+Z*Ze,f.max[2]]),ht=(typeof I.offset.x=="number"&&typeof I.offset.y=="number"?new o.P(I.offset.x,I.offset.y):o.P.convert(I.offset)).rotate(-o.am(R));return Xe.center[0]-=ht.x*Ze,Xe.center[1]+=ht.y*Ze,Xe}queryTerrainElevation(f,w){const I=this.transform.elevation;return I?(w=Object.assign({},{exaggerated:!0},w),I.getAtPoint(o.ad.fromLngLat(f),null,w.exaggerated)):null}_cameraForBounds(f,w,I,R,q,V){if(f.projection.name==="globe")return this._cameraForBoundsOnGlobe(f,w,I,R,q,V);const Z=f.clone(),te=this._extendCameraOptions(V);Z.bearing=R,Z.pitch=q;const le=o.aX.convert(w),pe=o.aX.convert(I),Ae=new o.aX(le.lng,pe.lat),_e=new o.aX(pe.lng,le.lat),Le=Z.project(le),Ve=Z.project(pe),qe=this.queryTerrainElevation(le),Ze=this.queryTerrainElevation(pe),Xe=this.queryTerrainElevation(Ae),ht=this.queryTerrainElevation(_e),vt=[[Le.x,Le.y,Math.min(qe||0,Ze||0,Xe||0,ht||0)],[Ve.x,Ve.y,Math.max(qe||0,Ze||0,Xe||0,ht||0)]];let st=o.cY.fromPoints(vt);const Ut=Z.getWorldToCameraMatrix(),Pt=o.ba(new Float64Array(16),Ut);st=o.cY.applyTransform(st,Ut);const Vt=this._extendAABB(st,Z,te,R);if(!Vt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");st=Vt;const St=.5*o.aw([],st.max,st.min)[2],Ct=this._minimumAABBFrustumDistance(Z,st),qt=[0,0,1,0];o.aD(qt,qt,Ut),o.e_(qt,qt);const Zt=o.bN([],qt,Ct+St),Wt=o.cX([],st.center,Zt);o.ae(st.center,st.center,Pt),o.ae(Wt,Wt,Pt);const hs=Z.unproject(new o.P(st.center[0],st.center[1])),ms=o.e$(Z.projection,hs),Zs=Math.pow(2,ms),ts=Math.min(Z._zoomFromMercatorZ(Wt[2]*Z.pixelsPerMeter*Zs/Z.worldSize),te.maxZoom);return Z.mercatorFromTransition&&ts<.5*(o.cN+o.cx)?(Z.setProjection({name:"globe"}),Z.zoom=ts,this._cameraForBounds(Z,w,I,R,q,V)):{center:hs,zoom:ts,bearing:R,pitch:q}}fitBounds(f,w,I){const R=this.cameraForBounds(f,w);return this._fitInternal(R,w,I)}fitScreenCoordinates(f,w,I,R,q){const V=o.P.convert(f),Z=o.P.convert(w),te=new o.P(Math.min(V.x,Z.x),Math.min(V.y,Z.y)),le=new o.P(Math.max(V.x,Z.x),Math.max(V.y,Z.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(V,Z))return this;const pe=this.transform.pointLocation3D(te),Ae=this.transform.pointLocation3D(le),_e=this.transform.pointLocation3D(new o.P(te.x,le.y)),Le=this.transform.pointLocation3D(new o.P(le.x,te.y)),Ve=[Math.min(pe.lng,Ae.lng,_e.lng,Le.lng),Math.min(pe.lat,Ae.lat,_e.lat,Le.lat)],qe=[Math.max(pe.lng,Ae.lng,_e.lng,Le.lng),Math.max(pe.lat,Ae.lat,_e.lat,Le.lat)],Ze=R&&R.pitch?R.pitch:this.getPitch(),Xe=this._cameraForBounds(this.transform,Ve,qe,I,Ze,R);return this._fitInternal(Xe,R,q)}_fitInternal(f,w,I){return f?(w=Object.assign(f,w)).linear?this.easeTo(w,I):this.flyTo(w,I):this}jumpTo(f,w){this.stop();const I=f.preloadOnly?this.transform.clone():this.transform;let R=!1,q=!1,V=!1;"zoom"in f&&I.zoom!==+f.zoom&&(R=!0,I.zoom=+f.zoom),f.center!==void 0&&(I.center=o.aX.convert(f.center)),"bearing"in f&&I.bearing!==+f.bearing&&(q=!0,I.bearing=+f.bearing),"pitch"in f&&I.pitch!==+f.pitch&&(V=!0,I.pitch=+f.pitch);const Z=typeof f.padding=="number"?this._extendPadding(f.padding):f.padding;if(f.padding!=null&&!I.isPaddingEqual(Z))if(f.retainPadding===!1){const te=I.clone();te.padding=Z,I.setLocationAtPoint(I.center,te.centerPoint)}else I.padding=Z;return f.preloadOnly?(this._preloadTiles(I),this):(this.fire(new o.z("movestart",w)).fire(new o.z("move",w)),R&&this.fire(new o.z("zoomstart",w)).fire(new o.z("zoom",w)).fire(new o.z("zoomend",w)),q&&this.fire(new o.z("rotatestart",w)).fire(new o.z("rotate",w)).fire(new o.z("rotateend",w)),V&&this.fire(new o.z("pitchstart",w)).fire(new o.z("pitch",w)).fire(new o.z("pitchend",w)),this.fire(new o.z("moveend",w)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(bm),this.transform.getFreeCameraOptions()}setFreeCameraOptions(f,w){const I=this.transform;if(!I.projection.supportsFreeCamera)return o.w(bm),this;this.stop();const R=I.zoom,q=I.pitch,V=I.bearing;I.setFreeCameraOptions(f);const Z=R!==I.zoom,te=q!==I.pitch,le=V!==I.bearing;return this.fire(new o.z("movestart",w)).fire(new o.z("move",w)),Z&&this.fire(new o.z("zoomstart",w)).fire(new o.z("zoom",w)).fire(new o.z("zoomend",w)),le&&this.fire(new o.z("rotatestart",w)).fire(new o.z("rotate",w)).fire(new o.z("rotateend",w)),te&&this.fire(new o.z("pitchstart",w)).fire(new o.z("pitch",w)).fire(new o.z("pitchend",w)),this.fire(new o.z("moveend",w)),this}easeTo(f,w){this._stop(!1,f.easeId),((f=Object.assign({offset:[0,0],duration:500,easing:o.eS},f)).animate===!1||this._prefersReducedMotion(f))&&(f.duration=0);const I=this.transform,R=this.getZoom(),q=this.getBearing(),V=this.getPitch(),Z=this.getPadding(),te="zoom"in f?+f.zoom:R,le="bearing"in f?this._normalizeBearing(f.bearing,q):q,pe="pitch"in f?+f.pitch:V,Ae=this._extendPadding(f.padding),_e=o.P.convert(f.offset);let Le,Ve,qe;if(I.projection.name==="globe"){const qt=o.ad.fromLngLat(I.center),Zt=_e.rotate(-I.angle);qt.x+=Zt.x/I.worldSize,qt.y+=Zt.y/I.worldSize;const Wt=qt.toLngLat(),hs=o.aX.convert(f.center||Wt);this._normalizeCenter(hs),Le=I.centerPoint.add(Zt),Ve=new o.P(qt.x,qt.y).mult(I.worldSize),qe=new o.P(o.aG(hs.lng),o.aJ(hs.lat)).mult(I.worldSize).sub(Ve)}else{Le=I.centerPoint.add(_e);const qt=I.pointLocation(Le),Zt=o.aX.convert(f.center||qt);this._normalizeCenter(Zt),Ve=I.project(qt),qe=I.project(Zt).sub(Ve)}const Ze=I.zoomScale(te-R);let Xe,ht;f.around&&(Xe=o.aX.convert(f.around),ht=I.locationPoint(Xe));const vt=this._zooming||te!==R,st=this._rotating||q!==le,Ut=this._pitching||pe!==V,Pt=!I.isPaddingEqual(Ae),Vt=f.retainPadding===!1?I.clone():I,St=qt=>Zt=>{if(vt&&(qt.zoom=o.aj(R,te,Zt)),st&&(qt.bearing=o.aj(q,le,Zt)),Ut&&(qt.pitch=o.aj(V,pe,Zt)),Pt&&(Vt.interpolatePadding(Z,Ae,Zt),Le=Vt.centerPoint.add(_e)),Xe)qt.setLocationAtPoint(Xe,ht);else{const Wt=qt.zoomScale(qt.zoom-R),hs=te>R?Math.min(2,Ze):Math.max(.5,Ze),ms=Math.pow(hs,1-Zt),Zs=qt.unproject(Ve.add(qe.mult(Zt*ms)).mult(Wt));qt.setLocationAtPoint(qt.renderWorldCopies?Zs.wrap():Zs,Le)}return f.preloadOnly||this._fireMoveEvents(w),qt};if(f.preloadOnly){const qt=this._emulate(St,f.duration,I);return this._preloadTiles(qt),this}const Ct={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=vt,this._rotating=st,this._pitching=Ut,this._padding=Pt,this._easeId=f.easeId,this._prepareEase(w,f.noMoveStart,Ct),this._ease(St(I),qt=>{I.cameraElevationReference==="sea"&&I.recenterOnTerrain(),this._afterEase(w,qt)},f),this}_prepareEase(f,w,I={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),w||I.moving||this.fire(new o.z("movestart",f)),this._zooming&&!I.zooming&&this.fire(new o.z("zoomstart",f)),this._rotating&&!I.rotating&&this.fire(new o.z("rotatestart",f)),this._pitching&&!I.pitching&&this.fire(new o.z("pitchstart",f))}_fireMoveEvents(f){this.fire(new o.z("move",f)),this._zooming&&this.fire(new o.z("zoom",f)),this._rotating&&this.fire(new o.z("rotate",f)),this._pitching&&this.fire(new o.z("pitch",f))}_afterEase(f,w){if(this._easeId&&w&&this._easeId===w)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const I=this._zooming,R=this._rotating,q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,I&&this.fire(new o.z("zoomend",f)),R&&this.fire(new o.z("rotateend",f)),q&&this.fire(new o.z("pitchend",f)),this.fire(new o.z("moveend",f))}flyTo(f,w){if(this._prefersReducedMotion(f)){const Ms=o.aK(f,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(Ms,w)}this.stop(),f=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eS},f);const I=this.transform,R=this.getZoom(),q=this.getBearing(),V=this.getPitch(),Z=this.getPadding(),te="zoom"in f?o.aB(+f.zoom,I.minZoom,I.maxZoom):R,le="bearing"in f?this._normalizeBearing(f.bearing,q):q,pe="pitch"in f?+f.pitch:V,Ae=this._extendPadding(f.padding),_e=I.zoomScale(te-R),Le=o.P.convert(f.offset);let Ve=I.centerPoint.add(Le);const qe=I.pointLocation(Ve),Ze=o.aX.convert(f.center||qe);this._normalizeCenter(Ze);const Xe=I.project(qe),ht=I.project(Ze).sub(Xe);let vt=f.curve;const st=Math.max(I.width,I.height),Ut=st/_e,Pt=ht.mag();if("minZoom"in f){const Ms=o.aB(Math.min(f.minZoom,R,te),I.minZoom,I.maxZoom),Rs=st/I.zoomScale(Ms-R);vt=Math.sqrt(Rs/Pt*2)}const Vt=vt*vt;function St(Ms){const Rs=(Ut*Ut-st*st+(Ms?-1:1)*Vt*Vt*Pt*Pt)/(2*(Ms?Ut:st)*Vt*Pt);return Math.log(Math.sqrt(Rs*Rs+1)-Rs)}function Ct(Ms){return(Math.exp(Ms)-Math.exp(-Ms))/2}function qt(Ms){return(Math.exp(Ms)+Math.exp(-Ms))/2}const Zt=St(0);let Wt=function(Ms){return qt(Zt)/qt(Zt+vt*Ms)},hs=function(Ms){return st*((qt(Zt)*(Ct(Rs=Zt+vt*Ms)/qt(Rs))-Ct(Zt))/Vt)/Pt;var Rs},ms=(St(1)-Zt)/vt;if(Math.abs(Pt)<1e-6||!isFinite(ms)){if(Math.abs(st-Ut)<1e-6)return this.easeTo(f,w);const Ms=Utf.maxDuration&&(f.duration=0);const Zs=q!==le,ts=pe!==V,Ns=!I.isPaddingEqual(Ae),rs=f.retainPadding===!1?I.clone():I,Ps=Ms=>Rs=>{const xr=Rs*ms,or=1/Wt(xr);Ms.zoom=Rs===1?te:R+Ms.scaleZoom(or),Zs&&(Ms.bearing=o.aj(q,le,Rs)),ts&&(Ms.pitch=o.aj(V,pe,Rs)),Ns&&(rs.interpolatePadding(Z,Ae,Rs),Ve=rs.centerPoint.add(Le));const Js=Rs===1?Ze:Ms.unproject(Xe.add(ht.mult(hs(xr))).mult(or));return Ms.setLocationAtPoint(Ms.renderWorldCopies?Js.wrap():Js,Ve),Ms._updateCameraOnTerrain(),f.preloadOnly||this._fireMoveEvents(w),Ms};if(f.preloadOnly){const Ms=this._emulate(Ps,f.duration,I);return this._preloadTiles(Ms),this}return this._zooming=!0,this._rotating=Zs,this._pitching=ts,this._padding=Ns,this._prepareEase(w,!1),this._ease(Ps(I),()=>this._afterEase(w),f),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(f){}_cancelRenderFrame(f){}_stop(f,w){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const I=this._onEaseEnd;this._onEaseEnd=void 0,I.call(this,w)}if(!f){const I=this.handlers;I&&I.stop(!1)}return this}_ease(f,w,I){I.animate===!1||I.duration===0?(f(1),w()):(this._easeStart=o.o.now(),this._easeOptions=I,this._onEaseFrame=f,this._onEaseEnd=w,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const f=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),w=this._onEaseFrame;w&&w(this._easeOptions.easing(f)),f<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(f,w){f=o.bv(f,-180,180);const I=Math.abs(f-w);return Math.abs(f-360-w)180?-360:I<-180?360:0}_prefersReducedMotion(f){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(f&&f.essential)}_emulate(f,w,I){const R=Math.ceil(15*w/1e3),q=[],V=f(I.clone());for(let Z=0;Z<=R;Z++){const te=V(Z/R);q.push(te.clone())}return q}_preloadTiles(f,w){}}const V0=/^(https?:|mailto:)/i;class o9{constructor(f={}){this.options=f,o.b0(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(f){const w=this.options&&this.options.compact,I=f._getUIString("AttributionControl.ToggleAttribution");this._map=f,this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=N("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",I);const R=N("span","mapboxgl-ctrl-icon",this._compactButton);return R.setAttribute("aria-hidden","true"),R.setAttribute("title",I),this._innerContainer=N("div","mapboxgl-ctrl-attrib-inner",this._container),w&&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),w===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 f=this._editLink;f||(f=this._editLink=this._container.querySelector(".mapbox-improve-map"));const w=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(f){const I=w.reduce((R,q,V)=>(q.value&&(R+=`${q.key}=${q.value}${VR.length-q.length),f=f.filter((R,q)=>{for(let V=q+1;Vfunction(q){const V=new DOMParser().parseFromString(q,"text/html");return Array.from(V.body.querySelectorAll("*")).reverse().forEach(Z=>{const te=Z.textContent||"";if(Z.tagName!=="A")return void Z.replaceWith(...Z.childNodes);const le=Z.getAttribute("href");if(!le||!V0.test(le))return void Z.replaceWith(V.createTextNode(te));const pe=V.createElement("a");pe.href=le,pe.textContent=te,pe.rel="noopener nofollow";const Ae=Z.getAttribute("class");Ae&&(pe.className=Ae),Z.replaceWith(pe)}),V.body.innerHTML}(R)).join(" | ");I!==this._attribHTML&&(this._attribHTML=I,f.length?(this._innerContainer.innerHTML=I,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 l9{constructor(){o.b0(["_updateLogo","_updateCompact"],this)}onAdd(f){this._map=f,this._container=N("div","mapboxgl-ctrl");const w=N("a","mapboxgl-ctrl-logo");return w.target="_blank",w.rel="noopener nofollow",w.href="https://www.mapbox.com/",w.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),w.setAttribute("rel","noopener nofollow"),this._container.appendChild(w),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(f){f&&f.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const f=this._map.style._sourceCaches;if(Object.entries(f).length===0)return!0;for(const w in f){const I=f[w].getSource();if(Object.hasOwn(I,"mapbox_logo")&&!I.mapbox_logo)return!1}return!0}_updateCompact(){const f=this._container.children;if(f.length){const w=f[0];this._map.getCanvasContainer().offsetWidth<250?w.classList.add("mapboxgl-compact"):w.classList.remove("mapboxgl-compact")}}}class c9{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(f){const w=++this._id;return this._queue.push({callback:f,id:w,cancelled:!1}),w}remove(f){const w=this._currentlyRunning,I=w?this._queue.concat(w):this._queue;for(const R of I)if(R.id===f)return void(R.cancelled=!0)}run(f=0){const w=this._currentlyRunning=this._queue;this._queue=[];for(const I of w)if(!I.cancelled&&(I.callback(f),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class qye{constructor(f){this.jumpTo(f)}getValue(f){if(f<=this._startTime)return this._start;if(f>=this._endTime)return this._end;const w=o.dr((f-this._startTime)/(this._endTime-this._startTime));return this._start*(1-w)+this._end*w}isEasing(f){return f>=this._startTime&&f<=this._endTime}jumpTo(f){this._startTime=-1/0,this._endTime=-1/0,this._start=f,this._end=f}easeTo(f,w,I){this._start=this.getValue(w),this._end=f,this._startTime=w,this._endTime=w+I}}const L6={"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 d9 extends o.z{constructor(f,w,I,R){const{point:q,lngLat:V,originalEvent:Z,target:te}=f;super(f.type,{point:q,lngLat:V,originalEvent:Z,target:te}),this.preventDefault=()=>{f.preventDefault()},this.id=w,this.interaction=I,this.feature=R}}class rb{constructor(f){this.map=f,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(f,w){if(this.typeById.has(f))throw new Error(`Interaction id "${f}" already exists.`);const I=w.filter;let R=w.type;I&&this.filters.set(f,o.dj(I)),R==="mouseover"&&(R="mouseenter"),R==="mouseout"&&(R="mouseleave");const q=this.interactionsByType.get(R)||new Map;R==="mouseenter"||R==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(f,w)):q.size===0&&this.map.on(R,this.handleType),q.size===0&&this.interactionsByType.set(R,q),q.set(f,w),this.typeById.set(f,R)}get(f){const w=this.typeById.get(f);if(!w)return;const I=this.interactionsByType.get(w);return I?I.get(f):void 0}remove(f){const w=this.typeById.get(f);if(!w)return;this.typeById.delete(f),this.filters.delete(f);const I=this.interactionsByType.get(w);I&&(I.delete(f),w==="mouseenter"||w==="mouseleave"?(this.delegatedInteractions.delete(f),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):I.size===0&&this.map.off(w,this.handleType))}queryTargets(f,w){const I=[];for(const[R,q]of w)q.target&&I.push({targetId:R,target:q.target,filter:this.filters.get(R)});return this.map.style.queryRenderedTargets(f,I,this.map.transform)}handleMove(f){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const w=this.queryTargets(f.point,Array.from(this.delegatedInteractions).reverse());w.length&&(f.type="mouseenter",this.handleType(f,w));const I=new Map;for(const[R,{feature:q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(R)||I.set(q.id,q);I.size&&(f.type="mouseleave",this.handleType(f,Array.from(I.values())))}handleOut(f){const w=Array.from(this.hoveredFeatures.values()).map(({feature:I})=>I);w.length&&(f.type="mouseleave",this.handleType(f,w)),this.hoveredFeatures.clear()}handleType(f,w){const I=f.type==="mouseenter";if(I&&!this.interactionsByType.has(f.type))return void o.w("mouseenter interaction required for mouseleave to work.");const R=Array.from(this.interactionsByType.get(f.type)).reverse(),q=!!w;w=w||this.queryTargets(f.point,R);let V=!1;const Z=new Set;for(const te of w){for(const[le,pe]of R){if(!pe.target)continue;const Ae=te.variants?te.variants[le]:null;if(Ae){for(const _e of Ae){if(Uz(_e,te,Z,le))continue;const Le=new o.dl(te,_e),Ve=$z(_e,te,le);q&&Le.id!==void 0&&(Le.state=this.map.getFeatureState(Le));const qe=I?this.prevHoveredFeatures.get(Ve):null,Ze=new d9(f,le,pe,Le),Xe=qe?qe.stop:pe.handler(Ze);if(I&&this.hoveredFeatures.set(Ve,{feature:te,stop:Xe}),Xe!==!1){V=!0;break}}if(V)break}}if(V)break}if(!V)for(const[te,le]of R){const{handler:pe,target:Ae}=le;if(!Ae&&pe(new d9(f,te,le,null))!==!1)break}}}function u9(E,f){if(Array.isArray(E)&&Array.isArray(f)){const w=new Set(E),I=new Set(f);return w.size===I.size&&E.every(R=>I.has(R))}return o.b9(E,f)}const Vye=/matrix.*\((.+)\)/,h9={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,fontstackCompositing:"client",transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1},Hye={showCompass:!0,showZoom:!0,visualizePitch:!1};class Gye{constructor(f,w,I=!1){this._clickTolerance=10,this.element=w,this.mouseRotate=new iE({clickTolerance:f.dragRotate._mouseRotate._clickTolerance}),this.map=f,I&&(this.mousePitch=new Qm({clickTolerance:f.dragRotate._mousePitch._clickTolerance})),o.b0(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),w.addEventListener("mousedown",this.mousedown),w.addEventListener("touchstart",this.touchstart,{passive:!1}),w.addEventListener("touchmove",this.touchmove),w.addEventListener("touchend",this.touchend),w.addEventListener("touchcancel",this.reset)}down(f,w){this.mouseRotate.mousedown(f,w),this.mousePitch&&this.mousePitch.mousedown(f,w),D()}move(f,w){const I=this.map,R=this.mouseRotate.mousemoveWindow(f,w),q=R&&R.bearingDelta;if(q&&I.setBearing(I.getBearing()+q),this.mousePitch){const V=this.mousePitch.mousemoveWindow(f,w),Z=V&&V.pitchDelta;Z&&I.setPitch(I.getPitch()+Z)}}off(){const f=this.element;f.removeEventListener("mousedown",this.mousedown),f.removeEventListener("touchstart",this.touchstart),f.removeEventListener("touchmove",this.touchmove),f.removeEventListener("touchend",this.touchend),f.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){B(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(f){this.down(Object.assign({},f,{button:f.button,type:f.type,ctrlKey:!0,preventDefault:()=>f.preventDefault()}),$(this.element,f)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(f){this.move(f,$(this.element,f))}mouseup(f){this.mouseRotate.mouseupWindow(f),this.mousePitch&&this.mousePitch.mouseupWindow(f),this.offTemp()}touchstart(f){f.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=X(this.element,f.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>f.preventDefault()},this._startPos))}touchmove(f){f.targetTouches.length!==1?this.reset():(this._lastPos=X(this.element,f.targetTouches)[0],this.move({buttons:1,preventDefault:()=>f.preventDefault()},this._lastPos))}touchend(f){f.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)w.width||f.y>w.height;w.locationPoint3D(I).distSqr(f)180;){const I=w.locationPoint3D(E);if(I.x>=0&&I.y>=0&&I.x<=w.width&&I.y<=w.height)break;E.lng>w.center.lng?E.lng-=360:E.lng+=360}return E}const D6={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%)"},R6=/\s+/,Gf={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class GN extends o.E{constructor(f,w){super(),(f instanceof HTMLElement||w)&&(f=Object.assign({element:f},w)),o.b0(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:I="center",color:R="#3FB1CE",scale:q=1,draggable:V=!1,clickTolerance:Z=0,rotation:te=Gf.rotation,rotationAlignment:le=Gf.rotationAlignment,pitchAlignment:pe=Gf.pitchAlignment,occludedOpacity:Ae=Gf.occludedOpacity,altitude:_e=Gf.altitude}=f||{};this._anchor=I,this._color=R,this._scale=q,this._draggable=V,this._clickTolerance=Z,this._rotation=te,this._rotationAlignment=le,this._pitchAlignment=pe,this._occludedOpacity=Ae,this._altitude=_e,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),f&&f.element?(this._element=f.element,this._offset=o.P.convert(f&&f.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(f&&f.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",qe=>{qe.preventDefault()}),this._element.addEventListener("mousedown",qe=>{qe.preventDefault()});const Le=this._element.classList;for(const qe in D6)Le.remove(`mapboxgl-marker-anchor-${qe}`);Le.add(`mapboxgl-marker-anchor-${this._anchor}`);const Ve=f&&f.className?f.className.trim().split(R6):[];Le.add(...Ve),this._popup=null}_createDefaultMarker(){const f=N("div"),w=S("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},f);if(this._altitude===0){const I=S("radialGradient",{id:"shadowGradient"},S("defs",{},w));S("stop",{offset:"10%","stop-opacity":.4},I),S("stop",{offset:"100%","stop-opacity":.05},I),S("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},w)}return S("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"},w),S("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"},w),S("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},w),f}addTo(f){return f===this._map||(this.remove(),this._map=f,f.getCanvasContainer().appendChild(this._element),f.on("move",this._updateMoving),f.on("moveend",this._update),f.on("remove",this._clearFadeTimer),f._addMarker(this),this.setDraggable(this._draggable),this._update(),f.on("click",this._onMapClick)),this}remove(){const f=this._map;return f&&(f.off("click",this._onMapClick),f.off("move",this._updateMoving),f.off("moveend",this._update),f.off("mousedown",this._addDragHandler),f.off("touchstart",this._addDragHandler),f.off("mouseup",this._onUp),f.off("touchend",this._onUp),f.off("mousemove",this._onMove),f.off("touchmove",this._onMove),f.off("remove",this._clearFadeTimer),f._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(f){return this._lngLat=o.aX.convert(f),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(f){return f===this._altitude||(this._defaultMarker&&(this._altitude===0&&f!==0||this._altitude!==0&&f===0)&&(this._element=this._createDefaultMarker()),this._altitude=f||Gf.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(f){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")),f){if(!("offset"in f.options)){const R=Math.sqrt(Math.pow(13.5,2)/2);f.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[R,-1*(38.1-13.5+R)],"bottom-right":[-R,-1*(38.1-13.5+R)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=f,f._marker=this,f._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(f){const w=f.code,I=f.charCode||f.keyCode;w!=="Space"&&w!=="Enter"&&I!==32&&I!==13||this.togglePopup()}_onMapClick(f){const w=f.originalEvent.target,I=this._element;this._popup&&(w===I||I.contains(w))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const f=this._popup;return f?(f.isOpen()?(f.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(f.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const f=this._map,w=this._pos;if(!f||!w)return!1;const I=f.unproject(w,this._altitude),R=f.getFreeCameraOptions();if(!R.position)return!1;const q=R.position.toLngLat();return q.distanceTo(I)<.9*q.distanceTo(this._lngLat)}_evaluateOpacity(){const f=this._map;if(!f)return;const w=this._pos;if(!w||w.x<0||w.x>f.transform.width||w.y<0||w.y>f.transform.height)return void this._clearFadeTimer();const I=f.unproject(w,this._altitude);let R;f._showingGlobe()&&o.f2(f.transform,this._lngLat)?R=0:(R=1-f._queryFogOpacity(I),f.transform._terrainEnabled()&&f.getTerrain()&&this._behindTerrain()&&(R*=this._occludedOpacity)),this._element.style.opacity=`${R}`,this._element.style.pointerEvents=R>0?"auto":"none",this._popup&&this._popup._setOpacity(R),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const f=this._pos;if(!f||!this._map)return;const w=this._offset.mult(this._scale);this._element.style.transform=` translate(${f.x}px,${f.y}px) ${D6[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${w.x}px,${w.y}px) `}_calculateXYTransform(){const f=this._pos,w=this._map,I=this.getPitchAlignment();if(!w||!f||I!=="map")return"";if(!w._showingGlobe()){const te=w.getPitch();return te?`rotateX(${te}deg)`:""}const R=o.cL(o.f3(w.transform,this._lngLat)),q=f.sub(o.f4(w.transform)),V=Math.abs(q.x)+Math.abs(q.y);if(V===0)return"";const Z=R/V;return`rotateX(${-q.y*Z}deg) rotateY(${q.x*Z}deg)`}_calculateZTransform(){const f=this._pos,w=this._map;if(!w||!f)return"";let I=0;const R=this.getRotationAlignment();if(R==="map")if(w._showingGlobe()){const q=w.project(new o.aX(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),V=w.project(new o.aX(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(q);I=o.cL(Math.atan2(V.y,V.x))-90}else I=-w.getBearing();else if(R==="horizon"){const q=o.ag(4,6,w.getZoom()),V=o.f4(w.transform);V.y+=q*w.transform.height;const Z=f.sub(V),te=o.cL(Math.atan2(Z.y,Z.x));I=(te>90?te-270:te+90)*(1-q)}return I+=this._rotation,I?`rotateZ(${I}deg)`:""}_update(f){cancelAnimationFrame(this._updateFrameId);const w=this._map;w&&(w.transform.renderWorldCopies&&(this._lngLat=og(this._lngLat,this._pos,w.transform)),this._pos=w.project(this._lngLat,this._altitude),f===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),w._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(w._showingGlobe()||w.getTerrain()||w.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(f){return this._offset=o.P.convert(f),this._update(),this}addClassName(f){return this._element.classList.add(f),this}removeClassName(f){return this._element.classList.remove(f),this}toggleClassName(f){return this._element.classList.toggle(f)}_onMove(f){const w=this._map;if(!w)return;const I=this._pointerdownPos,R=this._positionDelta;if(I&&R){if(!this._isDragging){const q=this._clickTolerance||w._clickTolerance;if(f.point.dist(I)E.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(E.minPitch!=null&&E.maxPitch!=null&&E.minPitch>E.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(E.minPitch!=null&&E.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(E.maxPitch!=null&&E.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");E.antialias&&o.f0(window)&&(E.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new X_(E.minZoom,E.maxZoom,E.minPitch,E.maxPitch,E.renderWorldCopies,null,null),E),this._repaint=!!E.repaint,this._interactive=E.interactive,this._minTileCacheSize=E.minTileCacheSize,this._maxTileCacheSize=E.maxTileCacheSize,this._failIfMajorPerformanceCaveat=E.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=E.preserveDrawingBuffer,this._antialias=E.antialias,this._trackResize=E.trackResize,this._bearingSnap=E.bearingSnap,this._refreshExpiredTiles=E.refreshExpiredTiles,this._fadeDuration=E.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=E.crossSourceCollisions,this._collectResourceTiming=E.collectResourceTiming,this._language=this._parseLanguage(E.language),this._worldview=E.worldview,this._renderTaskQueue=new c9,this._domRenderTaskQueue=new c9,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.an(),this._locale=Object.assign({},L6,E.locale),this._clickTolerance=E.clickTolerance,this._cooperativeGestures=E.cooperativeGestures,this._performanceMetricsCollection=E.performanceMetricsCollection,this._tessellationStep=E.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=E.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new qye(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=E.scaleFactor,this._requestManager=new oe(E.transformRequest,E.accessToken,E.testMode);const w=Pe(E.accessToken||o.g.ACCESS_TOKEN);if(w&&"atlas"in w&&typeof w.atlas=="number"&&(this._tokenExpiration=w.atlas),this._silenceAuthErrors=!!E.testMode,this._contextCreateOptions=E.contextCreateOptions?Object.assign({},E.contextCreateOptions):{},typeof E.container=="string"){const I=document.getElementById(E.container);if(!I)throw new Error(`Container '${E.container.toString()}' not found.`);this._container=I}else{if(!(E.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=E.container}if(this._container.childNodes.length>0&&o.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),E.maxBounds&&this.setMaxBounds(E.maxBounds),this._spriteFormat="auto",o.b0(["_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 Uye(this,E),this._localFontFamily=E.localFontFamily,this._localIdeographFontFamily=E.localIdeographFontFamily,this._fontstackCompositing=E.fontstackCompositing,(E.style||!E.testMode)&&this.setStyle(E.style||o.g.DEFAULT_STYLE,{config:E.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),E.projection&&this.setProjection(E.projection),E.hash&&(this._hash=new rg(typeof E.hash=="string"&&E.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){f.center==null&&f.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:E.center,zoom:E.zoom,bearing:E.bearing,pitch:E.pitch});const I=E.bounds;I&&(this.resize(),this.fitBounds(I,Object.assign({},E.fitBoundsOptions,{duration:0})))}this.resize(),E.attributionControl&&this.addControl(new o9({customAttribution:E.customAttribution})),this._logoControl=new l9,this.addControl(this._logoControl,E.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",I=>{this._update(I.dataType==="style"),this.fire(new o.z(`${I.dataType}data`,I))}),this.on("dataloading",I=>{this.fire(new o.z(`${I.dataType}dataloading`,I))}),this._interactions=new rb(this)}_getMapId(){return this._mapId}addControl(E,f){if(f===void 0&&(f=E.getDefaultPosition?E.getDefaultPosition():"top-right"),!E||!E.onAdd)return this.fire(new o.y(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const w=E.onAdd(this);this._controls.push(E);const I=this._controlPositions[f];return f.includes("bottom")?I.insertBefore(w,I.firstChild):I.appendChild(w),this}removeControl(E){if(!E||!E.onRemove)return this.fire(new o.y(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const f=this._controls.indexOf(E);return f>-1&&this._controls.splice(f,1),E.onRemove(this),this}hasControl(E){return this._controls.includes(E)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(E){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const f=!this._moving;return f&&this.fire(new o.z("movestart",E)).fire(new o.z("move",E)),this.fire(new o.z("resize",E)),f&&this.fire(new o.z("moveend",E)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(E){return this.transform.setMaxBounds(o.aI.convert(E)),this._update()}setMinZoom(E){if((E=E??-2)>=-2&&E<=this.transform.maxZoom)return this.transform.minZoom=E,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=E,this._update(),this.getZoom()>E?this.setZoom(E):this.fire(new o.z("zoomstart")).fire(new o.z("zoom")).fire(new o.z("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(E){if((E=E??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(E>=0&&E<=this.transform.maxPitch)return this.transform.minPitch=E,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(E>=this.transform.minPitch)return this.transform.maxPitch=E,this._update(),this.getPitch()>E?this.setPitch(E):this.fire(new o.z("pitchstart")).fire(new o.z("pitch")).fire(new o.z("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(E){return this._scaleFactor=E,this.painter.scaleFactor=E,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(f=>f.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(E){return this.transform.renderWorldCopies=E,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(E){return E==="auto"?navigator.language:Array.isArray(E)?E.length===0?void 0:E.map(f=>f==="auto"?navigator.language:f):E}setLanguage(E){const f=this._parseLanguage(E);if(!this.style||f===this._language)return this;this._language=f,this.style.reloadSources();for(const w of this._controls)w._setLanguage&&w._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(E){return this.style&&E!==this._worldview?(this._worldview=E,this._styleDirty=!0,this.style.setWorldview(E),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(E){return this._lazyInitEmptyStyle(),E?typeof E=="string"&&(E={name:E}):E=null,this._useExplicitProjection=!!E,this._prioritizeAndUpdateProjection(E,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const E=this.transform,f=E.projection.name;let w;f==="globe"&&E.zoom>=o.cx?(E.setMercatorFromTransition(),w=!0):f==="mercator"&&E.zoom=o.cx?this.transform.setMercatorFromTransition():this.transform.setProjection(E),this.style.applyProjectionUpdate();const I=this.transform.getProjection().name==="mercator"&&w!==this.transform.mercatorFromTransition;return(f||I)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(E,f){return this.transform.locationPoint3D(o.aX.convert(E),f)}unproject(E,f){return this.transform.pointLocation3D(o.P.convert(E),f)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(E,f,w){const I=R=>{let q=[];if(Array.isArray(f)){const V=f.filter(Z=>this.getLayer(Z));q=V.length?this.queryRenderedFeatures(R,{layers:V}):[]}else q=this.queryRenderedFeatures(R,{target:f});return q};if(E==="mouseenter"||E==="mouseover"){let R=!1;return{listener:w,targets:f,delegates:{mousemove:V=>{const Z=I(V.point);Z.length?R||(R=!0,w.call(this,new $h(E,this,V.originalEvent,{features:Z}))):R=!1},mouseout:()=>{R=!1}}}}if(E==="mouseleave"||E==="mouseout"){let R=!1;return{listener:w,targets:f,delegates:{mousemove:Z=>{I(Z.point).length?R=!0:R&&(R=!1,w.call(this,new $h(E,this,Z.originalEvent)))},mouseout:Z=>{R&&(R=!1,w.call(this,new $h(E,this,Z.originalEvent)))}}}}{const R=q=>{const V=I(q.point);V.length&&(q.features=V,w.call(this,q),delete q.features)};return{listener:w,targets:f,delegates:{[E]:R}}}}on(E,f,w){if(typeof f=="function"||w===void 0)return super.on(E,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const I=this._createDelegatedListener(E,f,w);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[E]=this._delegatedListeners[E]||[],this._delegatedListeners[E].push(I);for(const R in I.delegates)this.on(R,I.delegates[R]);return this}once(E,f,w){if(typeof f=="function"||w===void 0)return super.once(E,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const I=this._createDelegatedListener(E,f,w);for(const R in I.delegates)this.once(R,I.delegates[R]);return this}off(E,f,w){if(typeof f=="function"||w===void 0)return super.off(E,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const I=this._delegatedListeners?this._delegatedListeners[E]:void 0;return I&&(R=>{for(let q=0;q{if(w){const R=typeof w=="string"?w:w instanceof Error?w.message:w.error;o.w(`Unable to perform style diff: ${R}. Rebuilding the style from scratch.`),this._updateStyle(E,f)}else I&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=f.localIdeographFontFamily,this._localFontFamily=f.localFontFamily,this._fontstackCompositing=f.fontstackCompositing,this._updateStyle(E,f))}_getUIString(E){const f=this._locale[E];if(f==null)throw new Error(`Missing UI string '${E}'`);return f}_updateStyle(E,f){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),E){const w=Object.assign({},f);f&&f.config&&(w.initialConfig=f.config,delete w.config),this.style=new pm(this,w).load(E),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new pm(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(o.w("There is no style added to the map."),!1)}_isValidId(E){return E==null?(this.fire(new o.y(new Error("IDs can't be empty."))),!1):!o.de(E)||(this.fire(new o.y(new Error(`IDs can't contain special symbols: "${E}".`))),!1)}_isTargetValid(E){return"featuresetId"in E?this._isValidId("importId"in E?E.importId:E.featuresetId):"layerId"in E&&this._isValidId(E.layerId)}_areTargetsValid(E){if(Array.isArray(E)){for(const f of E)if(!this._isValidId(f))return!1;return!0}return this._isTargetValid(E)}addSource(E,f){return this._isValidId(E)?(this._lazyInitEmptyStyle(),this.style.addSource(E,f),this._update(!0)):this}isSourceLoaded(E){return!!this._isValidId(E)&&!!this.style&&this.style._isSourceCacheLoaded(E)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(E,f,w){this._lazyInitEmptyStyle(),this.style.addSourceType(E,f,w)}removeSource(E){return this._isValidId(E)?(this.style.removeSource(E),this._updateTerrain(),this._update(!0)):this}getSource(E){return this._isValidId(E)?this.style.getOwnSource(E):null}addImage(E,f,{pixelRatio:w=1,sdf:I=!1,stretchX:R,stretchY:q,content:V}={}){this._lazyInitEmptyStyle();const Z=o.I.from(E);if(f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap){const{width:te,height:le,data:pe}=o.o.getImageData(f);this.style.addImage(Z,{data:new o.q({width:te,height:le},pe),pixelRatio:w,stretchX:R,stretchY:q,content:V,sdf:I,version:0,usvg:!1})}else if(f.width===void 0||f.height===void 0)this.fire(new o.y(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:te,height:le}=f,pe=f;this.style.addImage(Z,{data:new o.q({width:te,height:le},new Uint8Array(pe.data)),pixelRatio:w,stretchX:R,stretchY:q,content:V,sdf:I,usvg:!1,version:0,userImage:pe}),pe.onAdd&&pe.onAdd(this,E)}}updateImage(E,f){this._lazyInitEmptyStyle();const w=o.I.from(E),I=this.style.getImage(w);if(!I)return void this.fire(new o.y(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const R=f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap?o.o.getImageData(f):f,{width:q,height:V,data:Z}=R;if(q===void 0||V===void 0)return void this.fire(new o.y(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(q!==(I.usvg?I.icon.usvg_tree.width:I.data.width)||V!==(I.usvg?I.icon.usvg_tree.height:I.data.height))return void this.fire(new o.y(new Error(`The width and height of the updated image (${q}, ${V}) must be that same as the previous version of the image (${I.data.width}, ${I.data.height})`)));const te=!(f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap);let le=!1;I.usvg?(I.data=new o.q({width:q,height:V},new Uint8Array(Z)),I.usvg=!1,I.icon=void 0,le=!0):I.data.replace(Z,te),this.style.updateImage(w,I,le)}hasImage(E){return E?!!this.style&&!!this.style.getImage(o.I.from(E)):(this.fire(new o.y(new Error("Missing required image id"))),!1)}removeImage(E){this.style.removeImage(o.I.from(E))}loadImage(E,f){o.n(this._requestManager.transformRequest(E,o.R.Image),(w,I)=>{f(w,I)})}listImages(){return this.style.listImages().map(E=>E.name)}addModel(E,f){this._lazyInitEmptyStyle(),this.style.addModel(E,f)}hasModel(E){return E?this.style.hasModel(E):(this.fire(new o.y(new Error("Missing required model id"))),!1)}removeModel(E){this.style.removeModel(E)}listModels(){return this.style.listModels()}addLayer(E,f){return this._isValidId(E.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(E,f),this._update(!0)):this}getSlot(E){const f=this.getLayer(E);return f&&f.slot||null}setSlot(E,f){return this.style.setSlot(E,f),this.style.mergeLayers(),this._update(!0)}addImport(E,f){return this.style.addImport(E,f).catch(w=>this.fire(new o.y(new Error("Failed to add import",w)))),this}updateImport(E,f){return typeof f!="string"&&f.id!==E?(this.removeImport(E),this.addImport(f)):(this.style.updateImport(E,f),this._update(!0))}removeImport(E){return this.style.removeImport(E),this}moveImport(E,f){return this.style.moveImport(E,f),this._update(!0)}moveLayer(E,f){return this._isValidId(E)?(this.style.moveLayer(E,f),this._update(!0)):this}removeLayer(E){return this._isValidId(E)?(this.style.removeLayer(E),this._update(!0)):this}getLayer(E){if(!this._isValidId(E))return null;const f=this.style.getOwnLayer(E);return f?f.type==="custom"?f.implementation:f.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(E,f,w){return this._isValidId(E)?(this.style.setLayerZoomRange(E,f,w),this._update(!0)):this}setFilter(E,f,w={}){return this._isValidId(E)?(this.style.setFilter(E,f,w),this._update(!0)):this}getFilter(E){return this._isValidId(E)?this.style.getFilter(E):null}setPaintProperty(E,f,w,I={}){return this._isValidId(E)?(this.style.setPaintProperty(E,f,w,I),this._update(!0)):this}getPaintProperty(E,f){return this._isValidId(E)?this.style.getPaintProperty(E,f):null}setLayoutProperty(E,f,w,I={}){return this._isValidId(E)?(this.style.setLayoutProperty(E,f,w,I),this._update(!0)):this}getLayoutProperty(E,f){return this._isValidId(E)?this.style.getLayoutProperty(E,f):null}setLayerProperty(E,f,w,I={}){return this._isValidId(E)?(f==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(E,f,w,I),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(E){return this.style.setGlyphsUrl(E),this._update(!0)}getSchema(E){return this.style.getSchema(E)}setSchema(E,f){return this.style.setSchema(E,f),this._update(!0)}getConfig(E){return this.style.getConfig(E)}setConfig(E,f){return this.style.setConfig(E,f),this._update(!0)}getConfigProperty(E,f){return this.style.getConfigProperty(E,f)}setConfigProperty(E,f,w){return this.style.setConfigProperty(E,f,w),this._update(!0)}getFeaturesetDescriptors(E){return this.style.getFeaturesetDescriptors(E)}setLights(E){if(this._lazyInitEmptyStyle(),E&&E.length===1&&E[0].type==="flat"){const f=E[0];f.properties?this.style.setFlatLight(f.properties,f.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(E),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const E=this.style.getLights()||[];return E.length===0&&E.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),E}setLight(E,f={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:E}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(E){return this._lazyInitEmptyStyle(),!E&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(E),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(E){return this._lazyInitEmptyStyle(),this.style.setFog(E),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(E){return this._lazyInitEmptyStyle(),this.style.setSnow(E),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(E){return this._lazyInitEmptyStyle(),this.style.setRain(E),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(E){return this._lazyInitEmptyStyle(),this.style.setColorTheme(E),this._update(!0)}setImportColorTheme(E,f){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(E,f),this._update(!0)}setCamera(E){return this.style.setCamera(E),this._triggerCameraUpdate(E)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(E){const f=this.transform.nearClipOffset!==E;return this.transform.nearClipOffset=E,this._update(f)}_triggerCameraUpdate(E){return this._update(this.transform.setOrthographicProjectionAtLowPitch(E["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(E){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aX.convert(E),this.transform):0}setFeatureState(E,f){return E.source&&!this._isValidId(E.source)?this:(this.style.setFeatureState(E,f),this._update())}removeFeatureState(E,f){return E.source&&!this._isValidId(E.source)?this:(this.style.removeFeatureState(E,f),this._update())}getFeatureState(E){return E.source&&!this._isValidId(E.source)?null:this.style.getFeatureState(E)}_selectIndoorFloor(E){this.style.indoorManager.selectFloor(E)}_setIndoorActiveFloorsVisibility(E){this.style.indoorManager.setActiveFloorsVisibility(E)}getIndoorTileOptions(E,f){return this.style&&this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(E,f):null}_updateContainerDimensions(){if(!this._container)return;const E=this._container.getBoundingClientRect().width||400,f=this._container.getBoundingClientRect().height||300;let w,I,R,q=this._container;for(;q&&(!I||!R);){const V=window.getComputedStyle(q).transform;V&&V!=="none"&&(w=V.match(Vye)[1].split(", "),w[0]&&w[0]!=="0"&&w[0]!=="1"&&(I=w[0]),w[3]&&w[3]!=="0"&&w[3]!=="1"&&(R=w[3])),q=q.parentElement}this._containerWidth=I?Math.abs(E/I):E,this._containerHeight=R?Math.abs(f/R):f}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&o.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const E=this._container;E.classList.add("mapboxgl-map"),(this._missingCSSCanary=N("div","mapboxgl-canary",E)).style.visibility="hidden",this._detectMissingCSS();const f=this._canvasContainer=N("div","mapboxgl-canvas-container",E);this._canvas=N("canvas","mapboxgl-canvas",f),this._interactive&&(f.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 w=this._controlContainer=N("div","mapboxgl-control-container",E),I=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(R=>{I[R]=N("div",`mapboxgl-ctrl-${R}`,w)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(E,f){const w=o.o.devicePixelRatio||1;this._canvas.width=w*Math.ceil(E),this._canvas.height=w*Math.ceil(f),this._canvas.style.width=`${E}px`,this._canvas.style.height=`${f}px`}_addMarker(E){this._markers.push(E)}_removeMarker(E){const f=this._markers.indexOf(E);f!==-1&&this._markers.splice(f,1)}_addPopup(E){this._popups.push(E)}_removePopup(E){const f=this._popups.indexOf(E);f!==-1&&this._popups.splice(f,1)}_setupPainter(){const E=Object.assign({},v.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),f=this._canvas.getContext("webgl2",E);f?(Ft(f,!0),this.painter=new s9(f,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",w=>{if(w.dataType==="source"){const I=this.transform.elevation?this.transform.elevation._source():null;I&&w.sourceCacheId===I.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(f)):this.fire(new o.y(new Error("Failed to initialize WebGL")))}_contextLost(E){E.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new o.z("webglcontextlost",{originalEvent:E}))}_contextRestored(E){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.z("webglcontextrestored",{originalEvent:E}))}_onMapScroll(E){if(E.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(E){return this.style?(this._styleDirty=this._styleDirty||E,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(E){return this._update(),this._renderTaskQueue.add(E)}_cancelRenderFrame(E){this._renderTaskQueue.remove(E)}_requestDomTask(E){!this.loaded()||this.loaded()&&!this.isMoving()?E():this._domRenderTaskQueue.add(E)}_render(E){let f;this.fire(new o.z("renderstart")),++this._frameId;const w=this.painter.context.extTimerQuery,I=o.o.now(),R=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(f=R.createQuery(),R.beginQuery(w.TIME_ELAPSED_EXT,f)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(E),this._domRenderTaskQueue.run(E),this._removed)return;this._updateProjectionTransition();const q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const te=this.transform.zoom,le=this.transform.pitch,pe=o.o.now(),Ae=new o.ab(te,{now:pe,fadeDuration:q,pitch:le,transition:this.style.transition,worldview:this._worldview});this.style.update(Ae)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let V=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),V=this._updateAverageElevation(I),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):V=this._updateAverageElevation(I),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,q,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:q,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.z("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,h.mark(d.load),this.fire(new o.z("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(),f){const te=o.o.now()-I;R.endQuery(w.TIME_ELAPSED_EXT),setTimeout(()=>{const le=R.getQueryParameter(f,R.QUERY_RESULT)/1e6;R.deleteQuery(f),this.fire(new o.z("gpu-timing-frame",{cpuTime:te,gpuTime:le}))},50)}if(this.listens("gpu-timing-layer")){const te=this.painter.collectGpuTimers();setTimeout(()=>{const le=this.painter.queryGpuTimers(te);this.fire(new o.z("gpu-timing-layer",{layerTimes:le}))},50)}if(this.listens("gpu-timing-deferred-render")){const te=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const le=this.painter.queryGpuTimeDeferredRender(te);this.fire(new o.z("gpu-timing-deferred-render",{gpuTime:le}))},50)}const Z=this._sourcesDirty||this._styleDirty||this._placementDirty||V;if(Z||this._repaint)this.triggerRepaint();else{const te=this.idle();if(te&&(V=this._updateAverageElevation(I,!0)),V)this.triggerRepaint();else{if(this._triggerFrame(!1),te&&(this.fire(new o.z("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const le=this._calculateSpeedIndex();this.fire(new o.z("speedindexcompleted",{speedIndex:le})),this.speedIndexTiming=!1}te&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||Z||(this._fullyLoaded=!0,h.mark(d.fullLoad),this._performanceMetricsCollection&&$t(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(E){for(const f of this._markers)E&&!this.getRenderWorldCopies()&&(f._lngLat=f._lngLat.wrap()),f._update();for(const f of this._popups)!E||this.getRenderWorldCopies()||f._trackPointer||(f._lngLat=f._lngLat.wrap()),f._update()}_updateAverageElevation(E,f=!1){const w=R=>(this.transform.averageElevation=R,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&w(0);const I=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(I||(f||E-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(E)){const R=this.transform.averageElevation;let q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(q)?q=0:this._averageElevationLastSampledAt=E;const V=Math.abs(R-q);if(V>1){if(this._isInitialLoad||I)return this._averageElevation.jumpTo(q),w(q);this._averageElevation.easeTo(q,E,300)}else if(V>1e-4)return this._averageElevation.jumpTo(q),w(q)}return!!this._averageElevation.isEasing(E)&&w(this._averageElevation.getValue(E))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const E=this.painter.context.gl;Ft(E,!1),this._logoControl instanceof l9&&this._logoControl._updateLogo(),E&&E.clear(E.DEPTH_BUFFER_BIT|E.COLOR_BUFFER_BIT|E.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.y(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(){it(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,E=>{E&&(E.message!==me&&E.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),ct(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&rt(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Qe(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){Ce(this._requestManager._customAccessToken)}_updateTerrain(){const E=this._isDragging();this.painter.updateTerrain(this.style,E)}_calculateSpeedIndex(){const E=this.painter.canvasCopy(),f=this.painter.getCanvasCopiesAndTimestamps();f.timeStamps.push(performance.now());const w=this.painter.context.gl,I=w.createFramebuffer();function R(q){w.framebufferTexture2D(w.FRAMEBUFFER,w.COLOR_ATTACHMENT0,w.TEXTURE_2D,q,0);const V=new Uint8Array(w.drawingBufferWidth*w.drawingBufferHeight*4);return w.readPixels(0,0,w.drawingBufferWidth,w.drawingBufferHeight,w.RGBA,w.UNSIGNED_BYTE,V),V}return w.bindFramebuffer(w.FRAMEBUFFER,I),this._canvasPixelComparison(R(E),f.canvasCopies.map(R),f.timeStamps)}_canvasPixelComparison(E,f,w){let I=w[1]-w[0];const R=E.length/4;for(let q=0;q{const w=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,w&&this._render(f)}))}_preloadTiles(E){const f=this.style?this.style.getSourceCaches():[];return o.ao(f,(w,I)=>w._preloadTiles(E,I),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(E){this._trackResize&&this.resize({originalEvent:E})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(E){this._showTileBoundaries!==E&&(this._showTileBoundaries=E,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(E){this._showParseStatus!==E&&(this._showParseStatus=E,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(E){this._showTerrainWireframe!==E&&(this._showTerrainWireframe=E,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(E){this._showLayers2DWireframe!==E&&(this._showLayers2DWireframe=E,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(E){this._showLayers3DWireframe!==E&&(this._showLayers3DWireframe=E,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(E){this.painter&&this.painter._debugParams.showElevationIdDebug!==E&&(this.painter._debugParams.showElevationIdDebug=E,this.style&&E?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(E){this._speedIndexTiming!==E&&(this._speedIndexTiming=E,this._update())}get showPadding(){return!!this._showPadding}set showPadding(E){this._showPadding!==E&&(this._showPadding=E,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(E){this._showCollisionBoxes!==E&&(this._showCollisionBoxes=E,this.style&&E?this.style._reloadSources():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(E){this._showOverdrawInspector!==E&&(this._showOverdrawInspector=E,this._update())}get repaint(){return!!this._repaint}set repaint(E){this._repaint!==E&&(this._repaint=E,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(E){this._vertices=E,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(E){this._showTileAABBs!==E&&(this._showTileAABBs=E,E&&this._update())}_setCacheLimits(E,f){o.f1(E,f)}get version(){return c}},NavigationControl:class{constructor(E={}){this.options=Object.assign({},Hye,E),this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",f=>f.preventDefault()),this.options.showZoom&&(o.b0(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",f=>{this._map&&this._map.zoomIn({},{originalEvent:f})}),N("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",f=>{this._map&&this._map.zoomOut({},{originalEvent:f})}),N("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.b0(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",f=>{const w=this._map;w&&(this.options.visualizePitch?w.resetNorthPitch({},{originalEvent:f}):w.resetNorth({},{originalEvent:f}))}),this._compassIcon=N("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const E=this._map;if(!E)return;const f=E.getZoom(),w=f===E.getMaxZoom(),I=f===E.getMinZoom();this._zoomInButton.disabled=w,this._zoomOutButton.disabled=I,this._zoomInButton.setAttribute("aria-disabled",w.toString()),this._zoomOutButton.setAttribute("aria-disabled",I.toString())}_rotateCompassArrow(){const E=this._map;if(!E)return;const f=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(E.transform.pitch*(Math.PI/180)),.5)}) rotateX(${E.transform.pitch}deg) rotateZ(${E.transform.angle*(180/Math.PI)}deg)`:`rotate(${E.transform.angle*(180/Math.PI)}deg)`;E._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=f)})}onAdd(E){return this._map=E,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),E.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&E.on("pitch",this._rotateCompassArrow),E.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Gye(E,this._compass,this.options.visualizePitch)),this._container}onRemove(){const E=this._map;E&&(this._container.remove(),this.options.showZoom&&E.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&E.off("pitch",this._rotateCompassArrow),E.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(E,f){const w=N("button",E,this._container);return w.type="button",w.addEventListener("click",f),w}_setButtonTitle(E,f){if(!this._map)return;const w=this._map._getUIString(`NavigationControl.${f}`);E.setAttribute("aria-label",w),E.firstElementChild&&E.firstElementChild.setAttribute("title",w)}},GeolocateControl:class extends o.E{constructor(E={}){super();const f=navigator.geolocation;this.options=Object.assign({geolocation:f},O6,E),o.b0(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=rE(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(E){return this._map=E,this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(E){const f=(w=!!this.options.geolocation)=>{this._supportsGeolocation=w,E(w)};this._supportsGeolocation!==void 0?E(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(w=>f(w.state!=="denied")).catch(()=>f()):f()}_isOutOfMapMaxBounds(E){const f=this._map.getMaxBounds(),w=E.coords;return!!f&&(w.longitudef.getEast()||w.latitudef.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(E){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(E))return this._setErrorState(),this.fire(new o.z("outofmaxbounds",E)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=E,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(E),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(E),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.z("geolocate",Object.assign({coords:E.coords,timestamp:E.timestamp},E.toJSON?{toJSON:E.toJSON.bind(E)}:{}))),this._finish()}}_updateCamera(E){const f=new o.aX(E.coords.longitude,E.coords.latitude),w=E.coords.accuracy,I=this._map.getBearing(),R=Object.assign({bearing:I},this.options.fitBoundsOptions);this._map.fitBounds(f.toBounds(w),R,{geolocateSource:!0})}_updateMarker(E){if(E){const f=new o.aX(E.coords.longitude,E.coords.latitude);this._accuracyCircleMarker.setLngLat(f).addTo(this._map),this._userLocationDotMarker.setLngLat(f).addTo(this._map),this._accuracy=E.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const E=this._map.transform,f=o.bY(1,E._center.lat)*E.worldSize,w=Math.ceil(2*this._accuracy*f);this._circleElement.style.width=`${w}px`,this._circleElement.style.height=`${w}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(E){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(E.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const f=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",f),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",f),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(E.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.z("error",{code:E.code,message:E.message,PERMISSION_DENIED:E.PERMISSION_DENIED,POSITION_UNAVAILABLE:E.POSITION_UNAVAILABLE,TIMEOUT:E.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const E=this.options.positionOptions.timeout;E&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},E))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(E){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",f=>f.preventDefault()),this._geolocateButton=N("button","mapboxgl-ctrl-geolocate",this._container),N("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",E===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const f=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",f),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",f)}else{const f=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",f),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",f)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=N("div","mapboxgl-user-location"),this._dotElement.appendChild(N("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(N("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new GN({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=N("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new GN({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",f=>{f.geolocateSource||this._watchState!=="ACTIVE_LOCK"||f.originalEvent&&f.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.z("trackuserlocationend")))})}}_onDeviceOrientation(E){this._userLocationDotMarker&&(E.webkitCompassHeading?this._heading=E.webkitCompassHeading:E.absolute===!0&&(this._heading=-1*E.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new o.z("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.z("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.z("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let E;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(E={maximumAge:6e5,timeout:0},this._noTimeout=!0):(E=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,E),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(E){return this.options.followUserLocation=E??O6.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.z("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.z("trackuserlocationend")))),this}_addDeviceOrientationListener(){const E=()=>{const f="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(f,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(f=>{f==="granted"&&E()}).catch(console.error):E()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:o9,ScaleControl:class{constructor(E={}){this.options=Object.assign({},Wye,E),o.b0(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const E=this.options.maxWidth||100,f=this._map,w=f._containerHeight/2,I=f._containerWidth/2-E/2,R=f.unproject([I,w]),q=f.unproject([I+E,w]),V=R.distanceTo(q);if(this.options.unit==="imperial"){const Z=3.2808*V;Z>5280?this._setScale(E,Z/5280,"mile"):this._setScale(E,Z,"foot")}else this.options.unit==="nautical"?this._setScale(E,V/1852,"nautical-mile"):V>=1e3?this._setScale(E,V/1e3,"kilometer"):this._setScale(E,V,"meter")}_setScale(E,f,w){this._map._requestDomTask(()=>{const I=function(q){const V=Math.pow(10,`${Math.floor(q)}`.length-1);let Z=q/V;return Z=Z>=10?10:Z>=5?5:Z>=3?3:Z>=2?2:Z>=1?1:function(te){const le=Math.pow(10,Math.ceil(-Math.log(te)/Math.LN10));return Math.round(te*le)/le}(Z),V*Z}(f),R=I/f;this._container.innerHTML=w!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:w}).format(I):`${I} ${m9[w]}`,this._container.style.width=E*R+"px"})}onAdd(E){return this._map=E,this._language=E.getLanguage(),this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-scale",E.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(E){this._language=E,this._update()}setUnit(E){this.options.unit=E,this._update()}},FullscreenControl:class{constructor(E={}){this._fullscreen=!1,E&&E.container&&(E.container instanceof HTMLElement?this._container=E.container:o.w("Full screen control 'container' must be a DOM element.")),o.b0(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(E){return this._map=E,this._container||(this._container=this._map.getContainer()),this._controlContainer=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const E=this._fullscreenButton=N("button","mapboxgl-ctrl-fullscreen",this._controlContainer);N("span","mapboxgl-ctrl-icon",E).setAttribute("aria-hidden","true"),E.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const E=this._getTitle();this._fullscreenButton.setAttribute("aria-label",E),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",E)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){o.b0(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(E){return this._map=E,this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const E=this._map.style.indoorManager;E.off("selector-update",this._onIndoorUpdate),E.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(E.getControlState())}}_createButton(E,f){const w=N("button",E,this._container);return w.type="button",w.addEventListener("click",f),w}_setButtonTitle(E,f){E.setAttribute("aria-label",f),E.textContent=f}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(E){if(!E||!E.floors||E.floors.length===0)return this._model=E,void(this._container.style.display="none");const f=this._model;this._model=E,this._container.style.display="inline-block";const w=!f||f.floors.length!==E.floors.length||f.floors.some((I,R)=>I.id!==E.floors[R].id);if(w&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),E.selectedFloorId){if(E.selectedFloorId!==this._lastSelectedFloorId||w){const I=E.floors.findIndex(R=>R.id===E.selectedFloorId);if(I!==-1){const R=E.floors.length;let q,V;R<=5?(q=0,V=R-1):this._visibleFloorStart===0?(q=0,V=3):this._visibleFloorStart>=R-3?(q=R-3-1,V=R-1):(q=this._visibleFloorStart,V=this._visibleFloorStart+3-1),IV&&(this._visibleFloorStart=I-2)}}this._lastSelectedFloorId=E.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const E=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);N("span","mapboxgl-ctrl-icon",E).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||E.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(E);const f=this._model.floors,w=f.length;if(w<=5)return void f.forEach(V=>this._createFloorButton(V));const I=this._visibleFloorStart===0,R=this._visibleFloorStart>=w-3;if(I)this._createFloorButton(f[0]);else{const V=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);N("span","mapboxgl-ctrl-icon",V).setAttribute("aria-hidden","true"),this._container.appendChild(V)}let q=[];if(q=I?f.slice(1,4):R?f.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):f.slice(this._visibleFloorStart,this._visibleFloorStart+3),q.forEach(V=>this._createFloorButton(V)),R)this._createFloorButton(f[w-1]);else{const V=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);N("span","mapboxgl-ctrl-icon",V).setAttribute("aria-hidden","true"),this._container.appendChild(V)}}_createFloorButton(E){const f=this._createButton("mapboxgl-ctrl-level-button",()=>{const q=E.id;this._model&&this._model.selectedFloorId===q&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(q))}),w=(E.name||"").trim(),I=E.zIndex.toString(),R=w?Array.from(w).slice(0,3).join(""):I;this._setButtonTitle(f,R),this._model&&this._model.activeFloorsVisible&&E.id===this._model.selectedFloorId&&f.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(f)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const E=this._model&&this._model.floors||[];if(E.length>3){const f=E.length-3;this._visibleFloorStart===f-1&&(this._visibleFloorStart=f-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const E=this._model.floors.length-3;this._visibleFloorStartE&&(this._visibleFloorStart=E),this._render())}}},Popup:class extends o.E{constructor(E){super(),this.options=Object.assign(Object.create(F6),E),this._altitude=this.options.altitude,o.b0(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(E&&E.className?E.className.trim().split(f9):[])}addTo(E){return this._map&&this.remove(),this._map=E,this.options.closeOnClick&&E.on("preclick",this._onClose),this.options.closeOnMove&&E.on("move",this._onClose),E.on("remove",this.remove),this._update(),E._addPopup(this),this._focusFirstElement(),this._trackPointer?(E.on("mousemove",this._onMouseEvent),E.on("mouseup",this._onMouseEvent),E._canvasContainer.classList.add("mapboxgl-track-pointer")):E.on("move",this._update),this.fire(new o.z("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const E=this._map;return E&&(E.off("move",this._update),E.off("move",this._onClose),E.off("preclick",this._onClose),E.off("click",this._onClose),E.off("remove",this.remove),E.off("mousemove",this._onMouseEvent),E.off("mouseup",this._onMouseEvent),E.off("drag",this._onMouseEvent),E._canvasContainer&&E._canvasContainer.classList.remove("mapboxgl-track-pointer"),E._removePopup(this),this._map=void 0),this.fire(new o.z("close")),this}getLngLat(){return this._lngLat}setLngLat(E){this._lngLat=o.aX.convert(E),this._pos=null,this._trackPointer=!1,this._update();const f=this._map;return f&&(f.on("move",this._update),f.off("mousemove",this._onMouseEvent),f._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(E){return this._altitude=E,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const E=this._map;return E&&(E.off("move",this._update),E.on("mousemove",this._onMouseEvent),E.on("drag",this._onMouseEvent),E._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(E){return this.setDOMContent(document.createTextNode(E))}setHTML(E){const f=document.createDocumentFragment(),w=document.createElement("body");let I;for(w.innerHTML=E;I=w.firstChild,I;)f.appendChild(I);return this.setDOMContent(f)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(E){return this.options.maxWidth=E,this._update(),this}setDOMContent(E){let f=this._content;if(f)for(;f.hasChildNodes();)f.firstChild&&f.removeChild(f.firstChild);else f=this._content=N("div","mapboxgl-popup-content",this._container||void 0);if(f.appendChild(E),this.options.closeButton){const w=this._closeButton=N("button","mapboxgl-popup-close-button",f);w.type="button",w.setAttribute("aria-label","Close popup"),w.innerHTML='',w.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(E){return this._classList.add(E),this._updateClassList(),this}removeClassName(E){return this._classList.delete(E),this._updateClassList(),this}setOffset(E){return this.options.offset=E,this._update(),this}toggleClassName(E){let f;return this._classList.delete(E)?f=!1:(this._classList.add(E),f=!0),this._updateClassList(),f}_onMouseEvent(E){this._update(E.point)}_getAnchor(E){if(this.options.anchor)return this.options.anchor;const f=this._map,w=this._container,I=this._pos;if(!f||!w||!I)return"bottom";const R=w.offsetWidth,q=w.offsetHeight,V=I.xf.transform.width-R/2;if(I.y+Ef.transform.height-q){if(V)return"bottom-left";if(Z)return"bottom-right"}return V?"left":Z?"right":"bottom"}_updateClassList(){const E=this._container;if(!E)return;const f=[...this._classList];f.push("mapboxgl-popup"),this._anchor&&f.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&f.push("mapboxgl-popup-track-pointer"),E.className=f.join(" ")}_update(E){const f=this._map,w=this._content;if(!f||!this._lngLat&&!this._trackPointer||!w)return;let I=this._container;if(I||(I=this._container=N("div","mapboxgl-popup",f.getContainer()),this._tip=N("div","mapboxgl-popup-tip",I),I.appendChild(w)),this.options.maxWidth&&I.style.maxWidth!==this.options.maxWidth&&(I.style.maxWidth=this.options.maxWidth),f.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=og(this._lngLat,this._pos,f.transform)),!this._trackPointer||E){const R=this._pos=this._trackPointer&&E instanceof o.P?E:f.project(this._lngLat,this._altitude),q=B6(this.options.offset),V=this._anchor=this._getAnchor(q.y),Z=B6(this.options.offset,V),te=R.add(Z).round();f._requestDomTask(()=>{this._container&&V&&(this._container.style.transform=`${D6[V]} translate(${te.x}px,${te.y}px)`)})}if(!this._marker&&f._showingGlobe()){const R=o.f2(f.transform,this._lngLat)?0:1;this._setOpacity(R)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const E=this._container.querySelector(So);E&&E.focus()}_onClose(){this.remove()}_setOpacity(E){this._container&&(this._container.style.opacity=`${E}`),this._content&&(this._content.style.pointerEvents=E?"auto":"none")}},Marker:GN,Style:pm,LngLat:o.aX,LngLatBounds:o.aI,Point:o.P,MercatorCoordinate:o.ad,FreeCameraOptions:kL,Evented:o.E,config:o.g,prewarm:function(){q_().acquire(z_)},clearPrewarmedResources:function(){const E=A0;E&&(E.isPreloaded()&&E.numActive()===1?(E.release(z_),A0=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(E){o.g.ACCESS_TOKEN=E},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(E){o.g.API_URL=E},get workerCount(){return Wx.workerCount},set workerCount(E){Wx.workerCount=E},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(E){o.g.MAX_PARALLEL_IMAGE_REQUESTS=E},clearStorage(E){o.fb(E)},get workerUrl(){return Gd.workerUrl},set workerUrl(E){Gd.workerUrl=E},get workerClass(){return Gd.workerClass},set workerClass(E){Gd.workerClass=E},get workerParams(){return Gd.workerParams},set workerParams(E){Gd.workerParams=E},get dracoUrl(){return o.fa()},set dracoUrl(E){o.g.DRACO_URL=o.o.resolveURL(E)},get meshoptUrl(){return o.f9()},set meshoptUrl(E){const f=o.o.resolveURL(E);o.g.MESHOPT_URL=f,o.g.MESHOPT_SIMD_URL=f},get buildingGenUrl(){return o.f8()},set buildingGenUrl(E){o.g.BUILDING_GEN_URL=o.o.resolveURL(E)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(qJe);var FAt=qJe.exports;const El=Io(FAt);function Vs({className:s,...t}){return e.jsx("div",{className:Bt("animate-pulse rounded-md bg-muted",s),...t})}const xOe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},gOe={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 BAt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function zAt({listings:s,isLoading:t}){const r=vr(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),[l,o]=k.useState(""),[c,d]=k.useState(!0);return k.useEffect(()=>{(async()=>{d(!0);try{const{data:x}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();x!=null&&x.value&&o(x.value)}catch(x){console.error("Error fetching mapbox token:",x)}d(!1)})()},[]),k.useEffect(()=>{if(!n.current||!l||a.current)return;El.accessToken=l;const m=s.filter(v=>v.latitude!=null&&v.longitude!=null);let x=[-98.5795,39.8283],g=4;if(m.length>0){const v=m.reduce((b,N)=>b+N.longitude,0)/m.length,j=m.reduce((b,N)=>b+N.latitude,0)/m.length;x=[v,j],g=m.length===1?12:10}return a.current=new El.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:g,center:x}),a.current.addControl(new El.NavigationControl,"top-right"),()=>{var v;(v=a.current)==null||v.remove(),a.current=null}},[l]),k.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(x=>x.remove()),i.current=[];const m=s.filter(x=>x.latitude!=null&&x.longitude!=null);if(m.forEach(x=>{var A,P,D;const g=xOe[x.status]||"#10B981",v=((A=x.photos)==null?void 0:A.find(B=>B.is_primary))||((P=x.photos)==null?void 0:P[0]),b=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${x.slug||x.id}`:`/public/listing/${x.slug||x.id}`,N=document.createElement("div");N.className="cursor-pointer",N.innerHTML=`

`;const S=new El.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${v!=null&&v.photo_url?``:""}
${BAt(x.price)}
${x.property_address||""}
${x.city}, ${x.state}
${gOe[x.status]||x.status} ${x.bedrooms?`${x.bedrooms} bed`:""} ${x.bathrooms?`${x.bathrooms} bath`:""}
${(D=x.agent)!=null&&D.name?`
Listed by ${x.agent.name}
`:""}
Click to view details →
`),T=new El.Marker(N).setLngLat([x.longitude,x.latitude]).setPopup(S).addTo(a.current);i.current.push(T)}),m.length>1){const x=new El.LngLatBounds;m.forEach(g=>x.extend([g.longitude,g.latitude])),a.current.fitBounds(x,{padding:60,maxZoom:13})}else m.length===1&&a.current.flyTo({center:[m[0].longitude,m[0].latitude],zoom:12})},[s,l]),k.useEffect(()=>(window.__navigateToPublicListing__=m=>{r(m)},()=>{delete window.__navigateToPublicListing__}),[r]),c||t?e.jsx(Vs,{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(xOe).map(([m,x])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:x}}),e.jsx("span",{className:"text-xs text-gray-600",children:gOe[m]})]},m))}),e.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}function tF(s,[t,r]){return Math.min(r,Math.max(t,s))}function HB(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 $At=[" ","Enter","ArrowUp","ArrowDown"],UAt=[" ","Enter"],g5="Select",[ype,vpe,qAt]=TB(g5),[K5]=yd(g5,[qAt,x1]),bpe=x1(),[VAt,q2]=K5(g5),[HAt,GAt]=K5(g5),WAt="SelectProvider";function HJe(s){const{__scopeSelect:t,children:r,open:n,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:h,autoComplete:m,disabled:x,required:g,form:v,internal_do_not_use_render:j}=s,b=bpe(t),[N,S]=k.useState(null),[T,A]=k.useState(null),[P,D]=k.useState(!1),B=$2(d),[z,F]=Lh({prop:n,defaultProp:a??!1,onChange:i,caller:g5}),[$,X]=Lh({prop:l,defaultProp:o,onChange:c,caller:g5}),K=k.useRef(null),Q=N?!!v||!!N.closest("form"):!0,[Y,ne]=k.useState(new Set),de=Qu(),ce=Array.from(Y).map(oe=>oe.props.value).join(";"),ae=k.useCallback(oe=>{ne(ge=>new Set(ge).add(oe))},[]),ie=k.useCallback(oe=>{ne(ge=>{const be=new Set(ge);return be.delete(oe),be})},[]),me={required:g,trigger:N,onTriggerChange:S,valueNode:T,onValueNodeChange:A,valueNodeHasChildren:P,onValueNodeHasChildrenChange:D,contentId:de,value:$,onValueChange:X,open:z,onOpenChange:F,dir:B,triggerPointerDownPosRef:K,disabled:x,name:h,autoComplete:m,form:v,nativeOptions:Y,nativeSelectKey:ce,isFormControl:Q};return e.jsx(IB,{...b,children:e.jsx(VAt,{scope:t,...me,children:e.jsx(ype.Provider,{scope:t,children:e.jsx(HAt,{scope:t,onNativeOptionAdd:ae,onNativeOptionRemove:ie,children:lMt(j)?j(me):r})})})})}HJe.displayName=WAt;var GJe=s=>{const{__scopeSelect:t,children:r,...n}=s;return e.jsx(HJe,{__scopeSelect:t,...n,internal_do_not_use_render:({isFormControl:a})=>e.jsxs(e.Fragment,{children:[r,a?e.jsx(fet,{__scopeSelect:t}):null]})})};GJe.displayName=g5;var WJe="SelectTrigger",r3e=k.forwardRef((s,t)=>{const{__scopeSelect:r,disabled:n=!1,...a}=s,i=bpe(r),l=q2(WJe,r),o=l.disabled||n,c=Qa(t,l.onTriggerChange),d=vpe(r),h=k.useRef("touch"),[m,x,g]=pet(j=>{const b=d().filter(T=>!T.disabled),N=b.find(T=>T.value===l.value),S=xet(b,j,N);S!==void 0&&l.onValueChange(S.value)}),v=j=>{o||(l.onOpenChange(!0),g()),j&&(l.triggerPointerDownPosRef.current={x:Math.round(j.pageX),y:Math.round(j.pageY)})};return e.jsx(bP,{asChild:!0,...i,children:e.jsx(pn.button,{type:"button",role:"combobox","aria-controls":l.open?l.contentId:void 0,"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":u3e(l.value)?"":void 0,...a,ref:c,onClick:Or(a.onClick,j=>{j.currentTarget.focus(),h.current!=="mouse"&&v(j)}),onPointerDown:Or(a.onPointerDown,j=>{h.current=j.pointerType;const b=j.target;b.hasPointerCapture(j.pointerId)&&b.releasePointerCapture(j.pointerId),j.button===0&&j.ctrlKey===!1&&j.pointerType==="mouse"&&(v(j),j.preventDefault())}),onKeyDown:Or(a.onKeyDown,j=>{const b=m.current!=="";!(j.ctrlKey||j.altKey||j.metaKey)&&j.key.length===1&&x(j.key),!(b&&j.key===" ")&&$At.includes(j.key)&&(v(),j.preventDefault())})})})});r3e.displayName=WJe;var KJe="SelectValue",YJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,children:i,placeholder:l="",...o}=s,c=q2(KJe,r),{onValueNodeHasChildrenChange:d}=c,h=i!==void 0,m=Qa(t,c.onValueNodeChange);fd(()=>{d(h)},[d,h]);const x=u3e(c.value);return e.jsx(pn.span,{...o,asChild:x?!1:o.asChild,ref:m,style:{pointerEvents:"none"},children:e.jsx(k.Fragment,{children:x?l:i},x?"placeholder":"value")})});YJe.displayName=KJe;var KAt="SelectIcon",ZJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,children:n,...a}=s;return e.jsx(pn.span,{"aria-hidden":!0,...a,ref:t,children:n||"▼"})});ZJe.displayName=KAt;var XJe="SelectPortal",[YAt,ZAt]=K5(XJe,{forceMount:void 0}),QJe=s=>{const{__scopeSelect:t,forceMount:r,...n}=s;return e.jsx(YAt,{scope:s.__scopeSelect,forceMount:r,children:e.jsx(xP,{asChild:!0,...n})})};QJe.displayName=XJe;var w2="SelectContent",n3e=k.forwardRef((s,t)=>{const r=ZAt(w2,s.__scopeSelect),{forceMount:n=r.forceMount,...a}=s,i=q2(w2,s.__scopeSelect),[l,o]=k.useState();return fd(()=>{o(new DocumentFragment)},[]),e.jsx(qd,{present:n||i.open,children:({present:c})=>c?e.jsx(tet,{...a,ref:t}):e.jsx(JJe,{...a,fragment:l})})});n3e.displayName=w2;var JJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,children:n,fragment:a}=s;return a?pf.createPortal(e.jsx(eet,{scope:r,children:e.jsx(ype.Slot,{scope:r,children:e.jsx("div",{ref:t,children:n})})}),a):null});JJe.displayName="SelectContentFragment";var Py=10,[eet,V2]=K5(w2),XAt="SelectContentImpl",QAt=v2("SelectContent.RemoveScroll"),tet=k.forwardRef((s,t)=>{const{__scopeSelect:r}=s,{position:n="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:x,collisionPadding:g,sticky:v,hideWhenDetached:j,avoidCollisions:b,...N}=s,S=q2(w2,r),[T,A]=k.useState(null),[P,D]=k.useState(null),B=Qa(t,Ee=>A(Ee)),[z,F]=k.useState(null),[$,X]=k.useState(null),K=vpe(r),[Q,Y]=k.useState(!1),ne=k.useRef(!1);k.useEffect(()=>{if(T)return dpe(T)},[T]),ope();const de=k.useCallback(Ee=>{const[$e,...Se]=K().map(ye=>ye.ref.current),[ze]=Se.slice(-1),Te=document.activeElement;for(const ye of Ee)if(ye===Te||(ye==null||ye.scrollIntoView({block:"nearest"}),ye===$e&&P&&(P.scrollTop=0),ye===ze&&P&&(P.scrollTop=P.scrollHeight),ye==null||ye.focus(),document.activeElement!==Te))return},[K,P]),ce=k.useCallback(()=>de([z,T]),[de,z,T]);k.useEffect(()=>{Q&&ce()},[Q,ce]);const{onOpenChange:ae,triggerPointerDownPosRef:ie}=S;k.useEffect(()=>{if(T){let Ee={x:0,y:0};const $e=ze=>{var Te,ye;Ee={x:Math.abs(Math.round(ze.pageX)-(((Te=ie.current)==null?void 0:Te.x)??0)),y:Math.abs(Math.round(ze.pageY)-(((ye=ie.current)==null?void 0:ye.y)??0))}},Se=ze=>{Ee.x<=10&&Ee.y<=10?ze.preventDefault():ze.composedPath().includes(T)||ae(!1),document.removeEventListener("pointermove",$e),ie.current=null};return ie.current!==null&&(document.addEventListener("pointermove",$e),document.addEventListener("pointerup",Se,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$e),document.removeEventListener("pointerup",Se,{capture:!0})}}},[T,ae,ie]),k.useEffect(()=>{const Ee=()=>ae(!1);return window.addEventListener("blur",Ee),window.addEventListener("resize",Ee),()=>{window.removeEventListener("blur",Ee),window.removeEventListener("resize",Ee)}},[ae]);const[me,oe]=pet(Ee=>{const $e=K().filter(Te=>!Te.disabled),Se=$e.find(Te=>Te.ref.current===document.activeElement),ze=xet($e,Ee,Se);ze&&setTimeout(()=>ze.ref.current.focus())}),ge=k.useCallback((Ee,$e,Se)=>{const ze=!ne.current&&!Se;(S.value!==void 0&&S.value===$e||ze)&&(F(Ee),ze&&(ne.current=!0))},[S.value]),be=k.useCallback(()=>T==null?void 0:T.focus(),[T]),Oe=k.useCallback((Ee,$e,Se)=>{const ze=!ne.current&&!Se;(S.value!==void 0&&S.value===$e||ze)&&X(Ee)},[S.value]),Me=n==="popper"?e2e:set,Pe=Me===e2e?{side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:x,collisionPadding:g,sticky:v,hideWhenDetached:j,avoidCollisions:b}:{};return e.jsx(eet,{scope:r,content:T,viewport:P,onViewportChange:D,itemRefCallback:ge,selectedItem:z,onItemLeave:be,itemTextRefCallback:Oe,focusSelectedItem:ce,selectedItemText:$,position:n,isPositioned:Q,searchRef:me,children:e.jsx(BB,{as:QAt,allowPinchZoom:!0,children:e.jsx(OB,{asChild:!0,trapped:S.open,onMountAutoFocus:Ee=>{Ee.preventDefault()},onUnmountAutoFocus:Or(a,Ee=>{var $e;($e=S.trigger)==null||$e.focus({preventScroll:!0}),Ee.preventDefault()}),children:e.jsx(F2,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Ee=>Ee.preventDefault(),onDismiss:()=>S.onOpenChange(!1),children:e.jsx(Me,{role:"listbox",id:S.contentId,"data-state":S.open?"open":"closed",dir:S.dir,onContextMenu:Ee=>Ee.preventDefault(),...N,...Pe,onPlaced:()=>Y(!0),ref:B,style:{display:"flex",flexDirection:"column",outline:"none",...N.style},onKeyDown:Or(N.onKeyDown,Ee=>{const $e=Ee.ctrlKey||Ee.altKey||Ee.metaKey;if(Ee.key==="Tab"&&Ee.preventDefault(),!$e&&Ee.key.length===1&&oe(Ee.key),["ArrowUp","ArrowDown","Home","End"].includes(Ee.key)){let ze=K().filter(Te=>!Te.disabled).map(Te=>Te.ref.current);if(["ArrowUp","End"].includes(Ee.key)&&(ze=ze.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ee.key)){const Te=Ee.target,ye=ze.indexOf(Te);ze=ze.slice(ye+1)}setTimeout(()=>de(ze)),Ee.preventDefault()}})})})})})})});tet.displayName=XAt;var JAt="SelectItemAlignedPosition",set=k.forwardRef((s,t)=>{const{__scopeSelect:r,onPlaced:n,...a}=s,i=q2(w2,r),l=V2(w2,r),[o,c]=k.useState(null),[d,h]=k.useState(null),m=Qa(t,B=>h(B)),x=vpe(r),g=k.useRef(!1),v=k.useRef(!0),{viewport:j,selectedItem:b,selectedItemText:N,focusSelectedItem:S}=l,T=k.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&j&&b&&N){const B=i.trigger.getBoundingClientRect(),z=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),$=N.getBoundingClientRect();if(i.dir!=="rtl"){const Te=$.left-z.left,ye=F.left-Te,ct=B.left-ye,ve=B.width+ct,rt=Math.max(ve,z.width),Re=window.innerWidth-Py,Qe=tF(ye,[Py,Math.max(Py,Re-rt)]);o.style.minWidth=ve+"px",o.style.left=Qe+"px"}else{const Te=z.right-$.right,ye=window.innerWidth-F.right-Te,ct=window.innerWidth-B.right-ye,ve=B.width+ct,rt=Math.max(ve,z.width),Re=window.innerWidth-Py,Qe=tF(ye,[Py,Math.max(Py,Re-rt)]);o.style.minWidth=ve+"px",o.style.right=Qe+"px"}const X=x(),K=window.innerHeight-Py*2,Q=j.scrollHeight,Y=window.getComputedStyle(d),ne=parseInt(Y.borderTopWidth,10),de=parseInt(Y.paddingTop,10),ce=parseInt(Y.borderBottomWidth,10),ae=parseInt(Y.paddingBottom,10),ie=ne+de+Q+ae+ce,me=Math.min(b.offsetHeight*5,ie),oe=window.getComputedStyle(j),ge=parseInt(oe.paddingTop,10),be=parseInt(oe.paddingBottom,10),Oe=B.top+B.height/2-Py,Me=K-Oe,Pe=b.offsetHeight/2,Ee=b.offsetTop+Pe,$e=ne+de+Ee,Se=ie-$e;if($e<=Oe){const Te=X.length>0&&b===X[X.length-1].ref.current;o.style.bottom="0px";const ye=d.clientHeight-j.offsetTop-j.offsetHeight,ct=Math.max(Me,Pe+(Te?be:0)+ye+ce),ve=$e+ct;o.style.height=ve+"px"}else{const Te=X.length>0&&b===X[0].ref.current;o.style.top="0px";const ct=Math.max(Oe,ne+j.offsetTop+(Te?ge:0)+Pe)+Se;o.style.height=ct+"px",j.scrollTop=$e-Oe+j.offsetTop}o.style.margin=`${Py}px 0`,o.style.minHeight=me+"px",o.style.maxHeight=K+"px",n==null||n(),requestAnimationFrame(()=>g.current=!0)}},[x,i.trigger,i.valueNode,o,d,j,b,N,i.dir,n]);fd(()=>T(),[T]);const[A,P]=k.useState();fd(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const D=k.useCallback(B=>{B&&v.current===!0&&(T(),S==null||S(),v.current=!1)},[T,S]);return e.jsx(tMt,{scope:r,contentWrapper:o,shouldExpandOnScrollRef:g,onScrollButtonChange:D,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(pn.div,{...a,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});set.displayName=JAt;var eMt="SelectPopperPosition",e2e=k.forwardRef((s,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:a=Py,...i}=s,l=bpe(r);return e.jsx(PB,{...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)"}})});e2e.displayName=eMt;var[tMt,a3e]=K5(w2,{}),t2e="SelectViewport",ret=k.forwardRef((s,t)=>{const{__scopeSelect:r,nonce:n,...a}=s,i=V2(t2e,r),l=a3e(t2e,r),o=Qa(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(ype.Slot,{scope:r,children:e.jsx(pn.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Or(a.onScroll,d=>{const h=d.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:x}=l;if(x!=null&&x.current&&m){const g=Math.abs(c.current-h.scrollTop);if(g>0){const v=window.innerHeight-Py*2,j=parseFloat(m.style.minHeight),b=parseFloat(m.style.height),N=Math.max(j,b);if(N0?A:0,m.style.justifyContent="flex-end")}}}c.current=h.scrollTop})})})]})});ret.displayName=t2e;var net="SelectGroup",[sMt,rMt]=K5(net),nMt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=Qu();return e.jsx(sMt,{scope:r,id:a,children:e.jsx(pn.div,{role:"group","aria-labelledby":a,...n,ref:t})})});nMt.displayName=net;var aet="SelectLabel",i3e=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=rMt(aet,r);return e.jsx(pn.div,{id:a.id,...n,ref:t})});i3e.displayName=aet;var Aue="SelectItem",[aMt,iet]=K5(Aue),o3e=k.forwardRef((s,t)=>{const{__scopeSelect:r,value:n,disabled:a=!1,textValue:i,...l}=s,o=q2(Aue,r),c=V2(Aue,r),d=o.value===n,[h,m]=k.useState(i??""),[x,g]=k.useState(!1),v=Qa(t,S=>{var T;return(T=c.itemRefCallback)==null?void 0:T.call(c,S,n,a)}),j=Qu(),b=k.useRef("touch"),N=()=>{a||(o.onValueChange(n),o.onOpenChange(!1))};if(n==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(aMt,{scope:r,value:n,disabled:a,textId:j,isSelected:d,onItemTextChange:k.useCallback(S=>{m(T=>T||((S==null?void 0:S.textContent)??"").trim())},[]),children:e.jsx(ype.ItemSlot,{scope:r,value:n,disabled:a,textValue:h,children:e.jsx(pn.div,{role:"option","aria-labelledby":j,"data-highlighted":x?"":void 0,"aria-selected":d&&x,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:v,onFocus:Or(l.onFocus,()=>g(!0)),onBlur:Or(l.onBlur,()=>g(!1)),onClick:Or(l.onClick,()=>{b.current!=="mouse"&&N()}),onPointerUp:Or(l.onPointerUp,()=>{b.current==="mouse"&&N()}),onPointerDown:Or(l.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Or(l.onPointerMove,S=>{var T;b.current=S.pointerType,a?(T=c.onItemLeave)==null||T.call(c):b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Or(l.onPointerLeave,S=>{var T;S.currentTarget===document.activeElement&&((T=c.onItemLeave)==null||T.call(c))}),onKeyDown:Or(l.onKeyDown,S=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&S.key===" "||(UAt.includes(S.key)&&N(),S.key===" "&&S.preventDefault())})})})})});o3e.displayName=Aue;var bR="SelectItemText",oet=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,...i}=s,l=q2(bR,r),o=V2(bR,r),c=iet(bR,r),d=GAt(bR,r),[h,m]=k.useState(null),x=Qa(t,N=>m(N),c.onItemTextChange,N=>{var S;return(S=o.itemTextRefCallback)==null?void 0:S.call(o,N,c.value,c.disabled)}),g=h==null?void 0:h.textContent,v=k.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:g},c.value),[c.disabled,c.value,g]),{onNativeOptionAdd:j,onNativeOptionRemove:b}=d;return fd(()=>(j(v),()=>b(v)),[j,b,v]),e.jsxs(e.Fragment,{children:[e.jsx(pn.span,{id:c.textId,...i,ref:x}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?pf.createPortal(i.children,l.valueNode):null]})});oet.displayName=bR;var cet="SelectItemIndicator",det=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return iet(cet,r).isSelected?e.jsx(pn.span,{"aria-hidden":!0,...n,ref:t}):null});det.displayName=cet;var s2e="SelectScrollUpButton",l3e=k.forwardRef((s,t)=>{const r=V2(s2e,s.__scopeSelect),n=a3e(s2e,s.__scopeSelect),[a,i]=k.useState(!1),l=Qa(t,n.onScrollButtonChange);return fd(()=>{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(uet,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});l3e.displayName=s2e;var r2e="SelectScrollDownButton",c3e=k.forwardRef((s,t)=>{const r=V2(r2e,s.__scopeSelect),n=a3e(r2e,s.__scopeSelect),[a,i]=k.useState(!1),l=Qa(t,n.onScrollButtonChange);return fd(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,h=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(uet,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});c3e.displayName=r2e;var uet=k.forwardRef((s,t)=>{const{__scopeSelect:r,onAutoScroll:n,...a}=s,i=V2("SelectScrollButton",r),l=k.useRef(null),o=vpe(r),c=k.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return k.useEffect(()=>()=>c(),[c]),fd(()=>{var h;const d=o().find(m=>m.ref.current===document.activeElement);(h=d==null?void 0:d.ref.current)==null||h.scrollIntoView({block:"nearest"})},[o]),e.jsx(pn.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Or(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(n,50))}),onPointerMove:Or(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(n,50))}),onPointerLeave:Or(a.onPointerLeave,()=>{c()})})}),iMt="SelectSeparator",d3e=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return e.jsx(pn.div,{"aria-hidden":!0,...n,ref:t})});d3e.displayName=iMt;var het="SelectArrow",oMt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=bpe(r);return V2(het,r).position==="popper"?e.jsx(LB,{...a,...n,ref:t}):null});oMt.displayName=het;var met="SelectBubbleInput",fet=k.forwardRef(({__scopeSelect:s,...t},r)=>{const n=q2(met,s),{value:a,onValueChange:i,required:l,disabled:o,name:c,autoComplete:d,form:h}=n,{nativeOptions:m,nativeSelectKey:x}=n,g=k.useRef(null),v=Qa(r,g),j=a??"",b=HB(j);return k.useEffect(()=>{const N=g.current;if(!N)return;const S=window.HTMLSelectElement.prototype,A=Object.getOwnPropertyDescriptor(S,"value").set;if(b!==j&&A){const P=new Event("change",{bubbles:!0});A.call(N,j),N.dispatchEvent(P)}},[b,j]),e.jsxs(pn.select,{"aria-hidden":!0,required:l,tabIndex:-1,name:c,autoComplete:d,disabled:o,form:h,onChange:N=>i(N.target.value),...t,style:{...KYe,...t.style},ref:v,defaultValue:j,children:[u3e(a)?e.jsx("option",{value:""}):null,Array.from(m)]},x)});fet.displayName=met;function lMt(s){return typeof s=="function"}function u3e(s){return s===""||s===void 0}function pet(s){const t=Ld(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 xet(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=cMt(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 cMt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}const zs=GJe,Us=YJe,Os=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(r3e,{ref:n,className:Bt("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(ZJe,{asChild:!0,children:e.jsx(so,{className:"h-4 w-4 opacity-50"})})]}));Os.displayName=r3e.displayName;const get=k.forwardRef(({className:s,...t},r)=>e.jsx(l3e,{ref:r,className:Bt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(xp,{className:"h-4 w-4"})}));get.displayName=l3e.displayName;const yet=k.forwardRef(({className:s,...t},r)=>e.jsx(c3e,{ref:r,className:Bt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(so,{className:"h-4 w-4"})}));yet.displayName=c3e.displayName;const Fs=k.forwardRef(({className:s,children:t,position:r="popper",...n},a)=>e.jsx(QJe,{children:e.jsxs(n3e,{ref:a,className:Bt("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(get,{}),e.jsx(ret,{className:Bt("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(yet,{})]})}));Fs.displayName=n3e.displayName;const dMt=k.forwardRef(({className:s,...t},r)=>e.jsx(i3e,{ref:r,className:Bt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));dMt.displayName=i3e.displayName;const mt=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(o3e,{ref:n,className:Bt("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(det,{children:e.jsx(Hn,{className:"h-4 w-4"})})}),e.jsx(oet,{children:t})]}));mt.displayName=o3e.displayName;const uMt=k.forwardRef(({className:s,...t},r)=>e.jsx(d3e,{ref:r,className:Bt("-mx-1 my-1 h-px bg-muted",s),...t}));uMt.displayName=d3e.displayName;const hMt=s=>gt({queryKey:["public-listings",s],queryFn:async()=>{let t=H.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city&&(t=t.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:r,error:n}=await t;if(n)throw n;return r}}),vet=s=>gt({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=H.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?r=r.eq("id",s):r=r.eq("slug",s);const{data:n,error:a}=await r.single();if(a)throw a;return n},enabled:!!s}),bet=()=>Lt({mutationFn:async({listingId:s,agentId:t,firstName:r,lastName:n,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:h,message:m})=>{let x=null,g=null;if(l){const{data:N}=await H.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();N&&(x=N.id,g=N.sharing_agent_id)}const{data:v,error:j}=await H.from("listing_leads").insert({listing_id:s,agent_id:g||t,first_name:r,last_name:n,email:a,phone:i,share_id:x,referred_by_agent_id:g,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:h||null,message:m||null}).select().single();if(j)throw j;const{error:b}=await H.functions.invoke("process-listing-lead",{body:{leadId:v.id}});return b&&console.error("Error processing lead:",b),v}}),mMt=()=>Lt({mutationFn:async s=>{const{error:t}=await H.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),fMt={active:"bg-emerald-500",coming_soon:"bg-blue-600",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},yOe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},pMt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function _et(){const[s,t]=k.useState(""),[r,n]=k.useState(!1),[a,i]=k.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:l,isLoading:o}=hMt({city:s||void 0,status:a.status||void 0,propertyType:a.propertyType||void 0,minPrice:a.minPrice?Number(a.minPrice):void 0,maxPrice:a.maxPrice?Number(a.maxPrice):void 0}),c=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(m),d=()=>{i({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},h=s||a.status||a.propertyType||a.minPrice||a.maxPrice;return e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsx("title",{children:"LevelUp Listings - Find Your Dream Home | Real Estate for Sale"}),e.jsx("meta",{name:"description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, condos, townhouses, and luxury properties. View photos, prices, and connect with agents."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{property:"og:description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, view photos, and connect with agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{name:"twitter:description",content:"Browse exclusive property listings from LevelUp real estate agents."}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"keywords",content:"homes for sale, real estate, property listings, houses, condos, townhouses, luxury homes, LevelUp"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com",description:"Browse exclusive property listings from LevelUp real estate agents",potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:"https://listings.relevelup.com?q={search_term_string}"},"query-input":"required name=search_term_string"}})}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:"LevelUp",url:"https://relevelup.com",logo:"https://listings.relevelup.com/assets/levelup-logo-color.png"})})]}),e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"bg-white border-b border-gray-200 sticky top-0 z-50",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Kn,{to:"/public/listings",className:"flex items-center",children:e.jsx("img",{src:t3e,alt:"LevelUp",className:"h-8"})}),e.jsx("nav",{className:"hidden md:flex items-center gap-6",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors",children:"About LevelUp"})})]})})}),e.jsxs("section",{className:"relative bg-cover bg-center py-20 md:py-32",style:{backgroundImage:`url(${OAt})`},children:[e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-4",children:[e.jsx("h1",{className:"text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-3 text-center drop-shadow-lg",children:"Find Your Perfect Home"}),e.jsx("p",{className:"text-white/90 text-center mb-10 text-lg md:text-xl drop-shadow",children:"Exclusive listings from LevelUp agents"}),e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex gap-0 shadow-2xl rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"relative flex-1 bg-white",children:[e.jsx(fn,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400"}),e.jsx(ke,{placeholder:"Enter an address, neighborhood, city, or ZIP code",value:s,onChange:m=>t(m.target.value),className:"pl-12 h-14 md:h-16 text-base md:text-lg border-0 focus-visible:ring-0 rounded-none bg-white"})]}),e.jsx(G,{className:"h-14 md:h-16 px-6 md:px-8 rounded-none bg-blue-600 hover:bg-blue-700",children:e.jsx(fn,{className:"h-5 w-5 md:h-6 md:w-6"})})]}),e.jsx("div",{className:"flex justify-center mt-6",children:e.jsxs(G,{variant:"secondary",size:"sm",onClick:()=>n(!r),className:"gap-2 bg-white/90 hover:bg-white text-gray-700 shadow-lg",children:[e.jsx(H3,{className:"h-4 w-4"}),r?"Hide Filters":"More Filters"]})}),r&&e.jsxs("div",{className:"mt-4 p-6 bg-white rounded-lg shadow-xl",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Status"}),e.jsxs(zs,{value:a.status||"all",onValueChange:m=>i({...a,status:m==="all"?"":m}),children:[e.jsx(Os,{className:"bg-white",children:e.jsx(Us,{placeholder:"Any status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"Any status"}),Object.entries(yOe).map(([m,x])=>e.jsx(mt,{value:m,children:x},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Property Type"}),e.jsxs(zs,{value:a.propertyType||"all",onValueChange:m=>i({...a,propertyType:m==="all"?"":m}),children:[e.jsx(Os,{className:"bg-white",children:e.jsx(Us,{placeholder:"Any type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"Any type"}),Object.entries(pMt).map(([m,x])=>e.jsx(mt,{value:m,children:x},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Min Price"}),e.jsx(ke,{type:"number",placeholder:"No min",value:a.minPrice,onChange:m=>i({...a,minPrice:m.target.value}),className:"bg-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Max Price"}),e.jsx(ke,{type:"number",placeholder:"No max",value:a.maxPrice,onChange:m=>i({...a,maxPrice:m.target.value}),className:"bg-white"})]})]}),h&&e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:d,className:"gap-1 text-gray-500",children:[e.jsx(_r,{className:"h-4 w-4"}),"Clear all"]})})]})]})]})]}),l&&l.length>0&&e.jsx("section",{className:"py-8 bg-white border-b border-gray-200",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Explore on Map"}),e.jsx(zAt,{listings:l,isLoading:o})]})}),e.jsx("section",{className:"py-8",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:o?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:[...Array(8)].map((m,x)=>e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm",children:[e.jsx(Vs,{className:"aspect-[4/3]"}),e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx(Vs,{className:"h-7 w-28"}),e.jsx(Vs,{className:"h-4 w-full"}),e.jsx(Vs,{className:"h-4 w-3/4"})]})]},x))}):l&&l.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("h2",{className:"text-xl font-semibold text-gray-900",children:[l.length," ",l.length===1?"Home":"Homes"," Available"]})}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:l.map(m=>{var j,b,N;const x=((j=m.photos)==null?void 0:j.find(S=>S.is_primary))||((b=m.photos)==null?void 0:b[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`;return e.jsx(Kn,{to:v,children:e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-lg transition-shadow cursor-pointer group border border-gray-100",children:[e.jsxs("div",{className:"aspect-[4/3] relative overflow-hidden bg-gray-100",children:[x?e.jsx("img",{src:x.photo_url,alt:m.property_address||m.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Cn,{className:"h-12 w-12 text-gray-300"})}),e.jsx(Ge,{className:`absolute top-2 left-2 ${fMt[m.status]} text-white border-0 text-xs font-medium px-2 py-0.5`,children:yOe[m.status]}),e.jsx("button",{className:"absolute top-2 right-2 p-2 rounded-full bg-white/80 hover:bg-white transition-colors",onClick:S=>S.preventDefault(),children:e.jsx(hi,{className:"h-5 w-5 text-gray-600"})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xl font-bold text-gray-900 mb-1",children:c(m.price)}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-700 mb-2",children:[m.bedrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bedrooms}),e.jsx("span",{className:"text-gray-500",children:"bds"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.bathrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bathrooms}),e.jsx("span",{className:"text-gray-500",children:"ba"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.square_footage&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.square_footage.toLocaleString()}),e.jsx("span",{className:"text-gray-500",children:"sqft"})]})]}),m.property_address&&e.jsx("p",{className:"text-sm text-gray-700 truncate",children:m.property_address}),e.jsxs("p",{className:"text-sm text-gray-500 truncate",children:[m.city,", ",m.state]}),m.agent&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 truncate",children:m.agent.name}),((N=m.agent.brokerage)==null?void 0:N.name)&&e.jsx("p",{className:"text-xs text-gray-400 truncate",children:m.agent.brokerage.name})]})]})]})},m.id)})})]}):e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center",children:e.jsx(Cn,{className:"h-10 w-10 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No listings found"}),e.jsx("p",{className:"text-gray-500 mb-6",children:h?"Try adjusting your search or filters":"Check back soon for new listings"}),h&&e.jsx(G,{variant:"outline",onClick:d,children:"Clear filters"})]})})}),e.jsx("footer",{className:"bg-gray-900 text-white py-10 mt-auto",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("img",{src:s3e,alt:"LevelUp",className:"h-6"})}),e.jsxs("p",{className:"text-gray-400 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-white text-sm transition-colors",children:"relevelup.com"})]})})})]})]})}const Ne=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Bt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));Ne.displayName="Card";const Ot=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Bt("flex flex-col space-y-1.5 p-6",s),...t}));Ot.displayName="CardHeader";const zt=k.forwardRef(({className:s,...t},r)=>e.jsx("h3",{ref:r,className:Bt("text-2xl font-semibold leading-none tracking-tight",s),...t}));zt.displayName="CardTitle";const Nr=k.forwardRef(({className:s,...t},r)=>e.jsx("p",{ref:r,className:Bt("text-sm text-muted-foreground",s),...t}));Nr.displayName="CardDescription";const De=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Bt("p-6 pt-0",s),...t}));De.displayName="CardContent";const HO=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Bt("flex items-center p-6 pt-0",s),...t}));HO.displayName="CardFooter";var xMt="Label",wet=k.forwardRef((s,t)=>e.jsx(pn.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())}}));wet.displayName=xMt;var jet=wet;const gMt=V5("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),he=k.forwardRef(({className:s,...t},r)=>e.jsx(jet,{ref:r,className:Bt(gMt(),s),...t}));he.displayName=jet.displayName;const Mue="/assets/levelup-logo-color-D3mY9gCJ.png";function yMt(){const s=sc(),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(_et,{}):n.startsWith("public/")?null:e.jsx(vMt,{slug:n})}function vMt({slug:s}){return e.jsx(wMt,{slug:s})}const bMt={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"},_Mt={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},vOe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function wMt({slug:s}){var F,$;const{data:t,isLoading:r}=vet(s),n=bet(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(null),S=X=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(X),T=async X=>{if(X.preventDefault(),!(!a.trim()||!c.trim()||!t)){g(!0);try{await n.mutateAsync({listingId:t.id,agentId:t.agent_id,firstName:a.trim(),lastName:l.trim(),email:c.trim(),phone:h.trim()}),j(!0),ue.success("Thanks! The agent will be in touch soon.")}catch(K){console.error("Lead submission error:",K),ue.error(`Failed to submit: ${K.message||"Please try again"}`)}finally{g(!1)}}},A=(t==null?void 0:t.photos)||[],P=A.find(X=>X.is_primary)||A[0],D=()=>{b!==null&&N(b===0?A.length-1:b-1)},B=()=>{b!==null&&N(b===A.length-1?0:b+1)};if(r)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Vs,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Vs,{className:"h-10 w-48 mb-6"}),e.jsx(Vs,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Vs,{className:"h-12 w-48"}),e.jsx(Vs,{className:"h-6 w-full"}),e.jsx(Vs,{className:"h-6 w-3/4"})]}),e.jsx(Vs,{className:"h-64"})]})]})]});if(!t)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:Mue,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(Cn,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing may no longer be available."}),e.jsx(G,{asChild:!0,children:e.jsx("a",{href:"/",children:"Browse All Listings"})})]})]});const z=t.property_address?`${t.property_address} - ${t.city}, ${t.state}`:`${t.city}, ${t.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsxs("title",{children:[z," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${S(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA ${t.square_footage?t.square_footage.toLocaleString()+" sqft":""} ${vOe[t.property_type]} in ${t.city}, ${t.state}. ${((F=t.description)==null?void 0:F.slice(0,150))||""}`}),e.jsx("meta",{property:"og:title",content:z}),e.jsx("meta",{property:"og:description",content:`${S(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA in ${t.city}, ${t.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),P&&e.jsx("meta",{property:"og:image",content:P.photo_url})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:Mue,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs("a",{href:"/",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),A.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>N(0),children:e.jsx("img",{src:P==null?void 0:P.photo_url,alt:"Primary",className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:A.slice(1,5).map((X,K)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>N(K+1),children:[e.jsx("img",{src:X.photo_url,alt:`Photo ${K+2}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),K===3&&A.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",A.length-5," more"]})]},X.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Ge,{className:`${bMt[t.status]} text-white border-0`,children:_Mt[t.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:S(t.price)}),t.property_address&&e.jsx("p",{className:"text-xl font-medium",children:t.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ja,{className:"h-4 w-4"}),t.city,", ",t.state,t.neighborhood&&` • ${t.neighborhood}`]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[t.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(e0,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),t.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(fp,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),t.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx($g,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),t.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(rn,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),vOe[t.property_type]]}),t.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",t.lot_size]}),t.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),t.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})]}),t.agent_notes&&t.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.agent_notes})]}),t.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:t.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[t.agent&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bi,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"font-semibold text-lg",children:t.agent.name}),(($=t.agent.brokerage)==null?void 0:$.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:t.agent.brokerage.name})]})]}),e.jsxs(Ne,{className:"border-primary",children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(De,{children:v?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(Qs,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The listing agent will contact you soon."})]}):e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"firstName",children:"First Name *"}),e.jsx(ke,{id:"firstName",type:"text",placeholder:"John",value:a,onChange:X=>i(X.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ke,{id:"lastName",type:"text",placeholder:"Doe",value:l,onChange:X=>o(X.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email *"}),e.jsx(ke,{id:"email",type:"email",placeholder:"you@example.com",value:c,onChange:X=>d(X.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(ke,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:h,onChange:X=>m(X.target.value)})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:x,children:x?"Submitting...":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})})]})]})]})]}),e.jsx(vs,{open:b!==null,onOpenChange:()=>N(null),children:e.jsxs(ys,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(js,{className:"sr-only",children:e.jsx(bs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>N(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(_r,{className:"h-5 w-5"})}),b!==null&&A[b]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:A[b].photo_url,alt:`Photo ${b+1}`,className:"w-full max-h-[80vh] object-contain"}),A.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:D,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(Vo,{className:"h-6 w-6"})}),e.jsx("button",{onClick:B,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(ya,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[b+1," / ",A.length]})]})]})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function _pe({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 Net=s=>gt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:r}=await H.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(r)throw r;const{data:n}=await H.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 H.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 H.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 H.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=H.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}),jMt=()=>gt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await H.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),NMt=s=>gt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),ket=()=>{const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("agent_cards").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ue.success("Agent card created")},onError:t=>ue.error(t.message)})},Cet=()=>{const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("agent_cards").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ue.success("Agent card updated")},onError:t=>ue.error(t.message)})},fo=async(s,t,r,n)=>{const a=new URLSearchParams(window.location.search);await H.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:{}})},kMt=async(s,t)=>{const{error:r}=await H.from("agent_card_leads").insert({card_id:s,...t});if(r)throw r},Tet=s=>gt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 H.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 wpe({open:s,onOpenChange:t,cardId:r,type:n,agentName:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(!1),N=async S=>{if(S.preventDefault(),!i.trim()){ue.error("Please enter your name");return}b(!0);try{await kMt(r,{lead_type:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:g.trim()||void 0,intent:m||void 0}),fo(r,"lead_submitted",n),H.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:g.trim()||void 0,intent:m||void 0}}).catch(T=>console.error("Card lead notify failed:",T)),ue.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),h(""),x(""),v("")}catch{ue.error("Something went wrong. Please try again.")}finally{b(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(js,{children:[e.jsx(bs,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Fr,{children:n==="booking"?`Let ${a} know you'd like to connect.`:n==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-name",children:"Name *"}),e.jsx(ke,{id:"lead-name",value:i,onChange:S=>l(S.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(ke,{id:"lead-phone",type:"tel",value:d,onChange:S=>h(S.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-email",children:"Email"}),e.jsx(ke,{id:"lead-email",type:"email",value:o,onChange:S=>c(S.target.value),placeholder:"you@example.com"})]}),n==="booking"&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select one"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"buy",children:"Buy a home"}),e.jsx(mt,{value:"sell",children:"Sell my home"}),e.jsx(mt,{value:"both",children:"Buy & Sell"}),e.jsx(mt,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(ke,{id:"lead-message",value:g,onChange:S=>v(S.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(G,{type:"submit",className:"w-full rounded-2xl",disabled:j,children:j?"Sending...":"Submit"})]})]})})}const SMt=s=>gt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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}),CMt=s=>gt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),TMt=()=>{const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("card_blocks").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["card-blocks",r.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),ue.success("Block added")},onError:t=>ue.error(t.message)})},EMt=()=>{const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("card_blocks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ue.success("Block updated")},onError:t=>ue.error(t.message)})},AMt=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("card_blocks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ue.success("Block removed")},onError:t=>ue.error(t.message)})};function MMt(s){const t=s.match(/(?:iframe\.mediadelivery\.net\/embed\/|video\.bunnycdn\.com\/play\/)(\d+)\/([a-f0-9-]+)/i);return t?`https://iframe.mediadelivery.net/embed/${t[1]}/${t[2]}?autoplay=false&responsive=true`:(s.includes("iframe.mediadelivery.net"),s)}function IMt(s){const t=s.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/);return t?`https://www.youtube.com/embed/${t[1]}`:null}const PMt={standard:"rounded-2xl overflow-hidden mb-6 bg-slate-100",luxury:"rounded-xl overflow-hidden mb-6 bg-[#1e2636] border border-[#c9a84c]/10",bold:"rounded-2xl overflow-hidden mb-6",classic:"rounded-lg overflow-hidden mb-6 border border-[#d4cfc5] shadow-sm"};function LMt({block:s,variant:t}){const r=s.config;if(!r.video_url)return null;const n=r.video_url.includes("mediadelivery.net")||r.video_url.includes("bunnycdn.com"),a=IMt(r.video_url),i=n||!!a,l=n?MMt(r.video_url):a||r.video_url;return e.jsx("div",{className:PMt[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 DMt={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 RMt({block:s,variant:t}){const n=s.config.testimonials||[],[a,i]=k.useState(0);if(n.length===0)return null;const l=DMt[t],o=n[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(z3,{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(Vo,{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(ya,{className:"h-4 w-4"})})]})]})}const OMt={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 FMt({block:s,variant:t}){const n=s.config.tags||[];if(n.length===0)return null;const a=OMt[t];return e.jsx("div",{className:a.container,children:n.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const BMt={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 zMt({block:s,cardId:t,variant:r}){const a=s.config.links||[];if(a.length===0)return null;const i=BMt[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:()=>fo(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Yr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const n2e={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 $Mt({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 UMt={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 qMt({block:s,cardId:t,variant:r}){const a=s.config.platforms||[],i=UMt[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=n2e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>fo(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx($Mt,{path:c.icon,color:c.color})},o)})})]})}function jpe({cardId:s,variant:t}){const{data:r}=SMt(s);if(!r||r.length===0)return null;const n=r.filter(l=>l.block_type==="social_media"&&l.is_visible),a=r.filter(l=>l.block_type!=="social_media"),i=n.length>0?{...n[0],config:{platforms:n.flatMap(l=>l.config.platforms||[])}}:null;return r.findIndex(l=>l.block_type==="social_media"),e.jsxs(e.Fragment,{children:[a.map(l=>{switch(l.block_type){case"video_intro":return e.jsx(LMt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(RMt,{block:l,variant:t},l.id);case"specialties":return e.jsx(FMt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(zMt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(qMt,{block:i,cardId:s,variant:t})]})}async function VMt(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 HMt(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 Npe(s){const{first:t,last:r}=HMt(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 VMt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}n.push("END:VCARD");const a=new Blob([n.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),ue.success("Contact saved!")}function GMt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{fo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),fo(s.id,"button_click","book"))},x=()=>{var S,T;fo(s.id,"contact_saved"),Npe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},g=async()=>{fo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),fo(s.id,"button_click","refer")},j=()=>{a("connect"),r(!0),fo(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(vn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ga,{src:s.avatar_url||void 0,alt:i}),e.jsx(bn,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:l})]}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',s.positioning_statement,'"']})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs(G,{onClick:c,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Nn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(G,{onClick:d,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(bi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(G,{onClick:h,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Qs,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(G,{onClick:m,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(rn,{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(Qn,{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(_pe,{card:s,variant:"standard"}),e.jsx(jpe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(G,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Xa,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(G,{variant:"ghost",onClick:()=>{fo(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(Qn,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(G,{variant:"ghost",onClick:v,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(fr,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(G,{variant:"ghost",onClick:j,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(nl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(G,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Pc,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>fo(s.id,"button_click",`social_${S.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(wpe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function WMt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{fo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),fo(s.id,"button_click","book"))},x=()=>{var S,T;fo(s.id,"contact_saved"),Npe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},g=async()=>{fo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),fo(s.id,"button_click","refer")},j=()=>{a("connect"),r(!0),fo(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(vn,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(ga,{src:s.avatar_url||void 0,alt:i}),e.jsx(bn,{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:Nn,label:"Call",handler:c},{icon:bi,label:"Text",handler:d},{icon:Qs,label:"Email",handler:h}].map(({icon:S,label:T,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(S,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:T})]},T))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(rn,{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(Qn,{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(_pe,{card:s,variant:"luxury"}),e.jsx(jpe,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Xa,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{fo(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(Qn,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(fr,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:j,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(nl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Pc,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>fo(s.id,"button_click",`social_${S.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(wpe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function KMt({card:s}){var T,A,P,D;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((T=s.profile)==null?void 0:T.name)||"Agent",l=i.split(" ").map(B=>B[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((P=s.bold_theme_colors)==null?void 0:P.dark)||"#1a1a2e",button:((D=s.bold_theme_colors)==null?void 0:D.button)||"#ff5722"},c=(B,z)=>{const F=parseInt(B.replace("#",""),16),$=Math.max(0,(F>>16)-z),X=Math.max(0,(F>>8&255)-z),K=Math.max(0,(F&255)-z);return`#${($<<16|X<<8|K).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(B,z)=>{fo(s.id,"button_click",B),z()},h=()=>d("call",()=>{var B;(B=s.profile)!=null&&B.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),m=()=>d("text",()=>{var B;(B=s.profile)!=null&&B.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),x=()=>d("email",()=>{var B;(B=s.profile)!=null&&B.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),g=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),fo(s.id,"button_click","book"))},v=()=>{var B,z;fo(s.id,"contact_saved"),Npe({name:i,phone:(B=s.profile)==null?void 0:B.phone,email:(z=s.profile)==null?void 0:z.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},j=async()=>{fo(s.id,"share_event");const B=`https://cards.relevelup.com/${s.slug}`,z="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:z,url:B})}catch{}else await navigator.clipboard.writeText(B),ue.success("Link copied!")},b=()=>{a("referral"),r(!0),fo(s.id,"button_click","refer")},N=()=>{a("connect"),r(!0),fo(s.id,"button_click","connect")},S={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen",style:{backgroundColor:o.accent},children:[e.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:o.dark},children:[s.show_photo&&e.jsxs(vn,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(ga,{src:s.avatar_url||void 0,alt:i}),e.jsx(bn,{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:Nn,label:"Call",handler:h},{icon:bi,label:"Text",handler:m},{icon:Qs,label:"Email",handler:x}].map(({icon:B,label:z,handler:F})=>e.jsxs("button",{onClick:F,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(B,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:z})]},z))}),e.jsxs("button",{onClick:g,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(rn,{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(Qn,{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(_pe,{card:s,variant:"bold"}),e.jsx(jpe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Xa,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{fo(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(Qn,{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(fr,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:N,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(nl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),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(Pc,{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((B,z)=>e.jsx("a",{href:B.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>fo(s.id,"button_click",`social_${B.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:S[B.platform.toLowerCase()]||"🔗"},z))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(wpe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function YMt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{fo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),fo(s.id,"button_click","book"))},x=()=>{var S,T;fo(s.id,"contact_saved"),Npe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},g=async()=>{fo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),fo(s.id,"button_click","refer")},j=()=>{a("connect"),r(!0),fo(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(vn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ga,{src:s.avatar_url||void 0,alt:i}),e.jsx(bn,{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:Nn,label:"Call",handler:c},{icon:bi,label:"Text",handler:d},{icon:Qs,label:"Email",handler:h}].map(({icon:S,label:T,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(S,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:T})]},T))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(rn,{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(Qn,{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(_pe,{card:s,variant:"classic"}),e.jsx(jpe,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Xa,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{fo(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(Qn,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(fr,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:j,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(nl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Pc,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>fo(s.id,"button_click",`social_${S.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(wpe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function h3e({card:s}){switch(s.theme){case"luxury":return e.jsx(WMt,{card:s});case"bold":return e.jsx(KMt,{card:s});case"classic":return e.jsx(YMt,{card:s});case"standard":default:return e.jsx(GMt,{card:s})}}function ZMt(){const s=sc();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(XMt,{slug:t})}function XMt({slug:s}){return e.jsx(QMt,{slug:s})}function QMt({slug:s}){var i;const{data:t,isLoading:r,error:n}=Net(s);if(k.useEffect(()=>{t!=null&&t.id&&fo(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(Vs,{className:"h-28 w-28 rounded-full"}),e.jsx(Vs,{className:"h-6 w-48"}),e.jsx(Vs,{className:"h-4 w-36"})]}),e.jsx(Vs,{className:"h-12 w-full"}),e.jsx(Vs,{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(il,{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(h3e,{card:t})]})}function Eet({presentationId:s,ctaLabel:t,agentName:r,prefillName:n,prefillEmail:a,prefillPhone:i}){const[l,o]=k.useState(n||""),[c,d]=k.useState(a||""),[h,m]=k.useState(i||""),[x,g]=k.useState(""),[v,j]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=async P=>{if(P.preventDefault(),!l.trim()){ue.error("Please enter your name");return}N(!0);try{const{error:D}=await H.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:h.trim()||null,intent:x||null,message:v.trim()||null});if(D)throw D;try{await H.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{}H.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:h.trim()||void 0,intent:x||void 0,message:v.trim()||void 0}}).catch(B=>console.error("Presentation lead notify failed:",B)),T(!0)}catch{ue.error("Something went wrong. Please try again.")}finally{N(!1)}};return S?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(Hn,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(ke,{id:"pres-lead-name",value:l,onChange:P=>o(P.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(ke,{id:"pres-lead-phone",type:"tel",value:h,onChange:P=>m(P.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(ke,{id:"pres-lead-email",type:"email",value:c,onChange:P=>d(P.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(zs,{value:x,onValueChange:g,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select one"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"buy",children:"Buy a home"}),e.jsx(mt,{value:"sell",children:"Sell my home"}),e.jsx(mt,{value:"both",children:"Buy & Sell"}),e.jsx(mt,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(ke,{id:"pres-lead-message",value:v,onChange:P=>j(P.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(G,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:b,children:b?"Sending...":t})]})}function JMt(){const s=sc();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(eIt,{shareToken:t})}function eIt({shareToken:s}){var v;const[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>{d()},[s]);const d=async()=>{const{data:j,error:b}=await H.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!j){c(!0),a(!1);return}const{data:N}=await H.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",j.owner_user_id).single();let S;if(N!=null&&N.brokerage_id){const{data:A}=await H.from("brokerages").select("name").eq("id",N.brokerage_id).single();S=(A==null?void 0:A.name)||void 0}let T=null;if(j.contact_id){const{data:A}=await H.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",j.contact_id).single();T=A}r({...j,owner_name:N==null?void 0:N.name,owner_email:N==null?void 0:N.email,owner_phone:N==null?void 0:N.phone,owner_avatar:N==null?void 0:N.avatar_url,owner_title:(N==null?void 0:N.title)||void 0,brokerage_name:S,contact_name:T?[T.first_name,T.last_name].filter(Boolean).join(" "):void 0,contact_email:(T==null?void 0:T.email)||void 0,contact_phone:(T==null?void 0:T.phone)||void 0}),a(!1);try{await H.rpc("log_presentation_view",{p_presentation_id:j.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await H.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=j=>{const b=j.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(j.includes("iframe.mediadelivery.net/play/")){const T=j.replace("/play/","/embed/"),A=T.includes("?")?"&":"?";return`${T}${A}responsive=true`}if(j.includes("iframe.mediadelivery.net")){const T=j.includes("?")?"&":"?";return`${j}${T}responsive=true`}const N=j.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(N)return`https://www.loom.com/embed/${N[1]}`;const S=j.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return S?`https://iframe.mediadelivery.net/embed/${S[1]}/${S[2]}?responsive=true`:j};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(Vs,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Vs,{className:"h-64 w-full"}),e.jsx(Vs,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const x=t.sections.filter(j=>j.is_visible!==!1),g=x[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[g!=null&&g.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(g.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"})}):g!=null&&g.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:g.image_url,alt:g.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:g==null?void 0:g.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:g==null?void 0:g.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:g==null?void 0:g.description})]}),(g==null?void 0:g.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:g.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:x.map((j,b)=>e.jsx("button",{onClick:()=>l(b),className:Bt("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:j.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:j.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:j.description})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(v=t.cta_url)!=null&&v.trim()?e.jsxs(G,{size:"lg",onClick:h,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Yr,{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(Eet,{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 Xg=()=>{const s=na();return gt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:r}=await H.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 H.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 tIt(){const{user:s}=As(),t=na(),{data:r}=Xg();return gt({queryKey:["open-houses",t,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:a}=await H.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 H.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 H.from("profiles").select("id, name").in("id",c);m==null||m.forEach(x=>{x.name&&(d[x.id]=x.name)})}const h=l.map(m=>({...m,agent_name:d[m.agent_id]||void 0}));i=[...i,...h]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function GUs(s){const{user:t}=As();return gt({queryKey:["open-house",s],queryFn:async()=>{const{data:r,error:n}=await H.from("open_houses").select("*").eq("id",s).single();if(n)throw n;return r},enabled:!!t&&!!s})}function Aet(s){const{user:t}=As(),r=es();return k.useEffect(()=>{if(!s)return;const n=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=H.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()=>{H.removeChannel(a)}},[s,r]),gt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:n,error:a}=await H.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 sIt(){const s=es(),t=na();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.from("open_houses").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),nn({title:"Open house created!"})},onError:r=>{nn({title:"Error",description:r.message,variant:"destructive"})}})}function Met(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{error:n}=await H.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 rIt(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("open_houses").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),nn({title:"Open house deleted"})}})}function nIt(s){return gt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:r}=await H.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 H.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 aIt(s){const{user:t}=As();return gt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:r,error:n}=await H.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;return r},enabled:!!t&&!!s})}function iIt(s){return gt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:r}=await H.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 oIt(){return Lt({mutationFn:async s=>{const{error:t}=await H.from("open_house_survey_responses").insert(s);if(t)throw t}})}function lIt(s){const{user:t}=As();return gt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:r,error:n}=await H.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 H.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 cIt(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 dIt(){const s=es();return Lt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await H.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 uIt(){const s=es();return Lt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await H.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 hIt(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.rpc("seed_default_survey_questions",{_open_house_id:t});if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r]})}})}function mIt(){return Lt({mutationFn:async s=>{const{data:t,error:r}=await H.from("open_house_visitors").insert(s).select("id").single();if(r)throw r;return t}})}function fIt(){return Lt({mutationFn:async({visitor_id:s,...t})=>{const{error:r}=await H.from("open_house_visitors").update(t).eq("id",s);if(r)throw r}})}function pIt(){return Lt({mutationFn:async s=>{await H.rpc("increment_open_house_scan",{_slug:s})}})}async function Iet(s){const{data:t,error:r}=await H.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 H.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var h;const d=c;(o[h=d.room_id]||(o[h]=[])).push(d)}),n.map(c=>({...c,media:o[c.id]||[]}))}function xIt(s){const{user:t}=As();return gt({queryKey:["open-house-rooms",s],queryFn:()=>Iet(s),enabled:!!t&&!!s})}function gIt(s){return gt({queryKey:["public-open-house-rooms",s],queryFn:()=>Iet(s),enabled:!!s})}function yIt(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 vIt(){const s=es();return Lt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await H.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 bIt(){const s=es();return Lt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await H.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 _It(){const s=es();return Lt({mutationFn:async({open_house_id:t,...r})=>{const{data:n,error:a}=await H.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 wIt(){const s=es();return Lt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await H.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 jIt(s){const{user:t}=As();return gt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:r,error:n}=await H.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 NIt(){const s=es();return Lt({mutationFn:async({id:t,status:r,open_house_id:n})=>{const{error:a}=await H.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 kpe="Switch",[kIt]=yd(kpe),[SIt,m3e]=kIt(kpe);function CIt(s){const{__scopeSwitch:t,checked:r,children:n,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:h="on",internal_do_not_use_render:m}=s,[x,g]=Lh({prop:r,defaultProp:a??!1,onChange:c,caller:kpe}),[v,j]=k.useState(null),[b,N]=k.useState(null),S=k.useRef(!1),T=v?!!l||!!v.closest("form"):!0,A={checked:x,setChecked:g,disabled:i,control:v,setControl:j,name:o,form:l,value:h,hasConsumerStoppedPropagationRef:S,required:d,defaultChecked:a,isFormControl:T,bubbleInput:b,setBubbleInput:N};return e.jsx(SIt,{scope:t,...A,children:TIt(m)?m(A):n})}var Pet="SwitchTrigger",Let=k.forwardRef(({__scopeSwitch:s,onClick:t,...r},n)=>{const{value:a,disabled:i,checked:l,required:o,setControl:c,setChecked:d,hasConsumerStoppedPropagationRef:h,isFormControl:m,bubbleInput:x}=m3e(Pet,s),g=Qa(n,c);return e.jsx(pn.button,{type:"button",role:"switch","aria-checked":l,"aria-required":o,"data-state":Bet(l),"data-disabled":i?"":void 0,disabled:i,value:a,...r,ref:g,onClick:Or(t,v=>{d(j=>!j),x&&m&&(h.current=v.isPropagationStopped(),h.current||v.stopPropagation())})})});Let.displayName=Pet;var f3e=k.forwardRef((s,t)=>{const{__scopeSwitch:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:h,...m}=s;return e.jsx(CIt,{__scopeSwitch:r,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:n,form:h,value:c,internal_do_not_use_render:({isFormControl:x})=>e.jsxs(e.Fragment,{children:[e.jsx(Let,{...m,ref:t,__scopeSwitch:r}),x&&e.jsx(Fet,{__scopeSwitch:r})]})})});f3e.displayName=kpe;var Det="SwitchThumb",Ret=k.forwardRef((s,t)=>{const{__scopeSwitch:r,...n}=s,a=m3e(Det,r);return e.jsx(pn.span,{"data-state":Bet(a.checked),"data-disabled":a.disabled?"":void 0,...n,ref:t})});Ret.displayName=Det;var Oet="SwitchBubbleInput",Fet=k.forwardRef(({__scopeSwitch:s,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:h,form:m,bubbleInput:x,setBubbleInput:g}=m3e(Oet,s),v=Qa(r,g),j=HB(i),b=MB(n);k.useEffect(()=>{const S=x;if(!S)return;const T=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(T,"checked").set,D=!a.current;if(j!==i&&P){const B=new Event("click",{bubbles:D});P.call(S,i),S.dispatchEvent(B)}},[x,j,i,a]);const N=k.useRef(i);return e.jsx(pn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??N.current,required:o,disabled:c,name:d,value:h,form:m,...t,tabIndex:-1,ref:v,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Fet.displayName=Oet;function TIt(s){return typeof s=="function"}function Bet(s){return s?"checked":"unchecked"}const br=k.forwardRef(({className:s,...t},r)=>e.jsx(f3e,{className:Bt("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(Ret,{className:Bt("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")})}));br.displayName=f3e.displayName;function ua(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 Tl(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Hl(s,t){const r=ua(s);return isNaN(t)?Tl(s,NaN):(t&&r.setDate(r.getDate()+t),r)}function Cf(s,t){const r=ua(s);if(isNaN(t))return Tl(s,NaN);if(!t)return r;const n=r.getDate(),a=Tl(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 zet(s,t){const r=+ua(s);return Tl(s,r+t)}const p3e=6048e5,EIt=864e5,Spe=6e4,GB=36e5,AIt=1e3,J$=43200,bOe=1440;function _Oe(s,t){return zet(s,t*GB)}let MIt={};function H2(){return MIt}function Fm(s,t){var o,c,d,h;const r=H2(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=ua(s),i=a.getDay(),l=(i=a.getTime()?r+1:t.getTime()>=l.getTime()?r:r-1}function Tf(s){const t=ua(s);return t.setHours(0,0,0,0),t}function j2(s){const t=ua(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 fx(s,t){const r=Tf(s),n=Tf(t),a=+r-j2(r),i=+n-j2(n);return Math.round((a-i)/EIt)}function IIt(s){const t=$et(s),r=Tl(s,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),v_(r)}function EA(s,t){return zet(s,t*Spe)}function U4(s,t){const r=t*7;return Hl(s,r)}function PIt(s,t){return Cf(s,t*12)}function LIt(s){let t;return s.forEach(function(r){const n=ua(r);(t===void 0||t{const n=ua(r);(!t||t>n||isNaN(+n))&&(t=n)}),t||new Date(NaN)}function mde(s,t){const r=ua(s),n=ua(t),a=r.getTime()-n.getTime();return a<0?-1:a>0?1:a}function x3e(s){return Tl(s,Date.now())}function $l(s,t){const r=Tf(s),n=Tf(t);return+r==+n}function g3e(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function a2e(s){if(!g3e(s)&&typeof s!="number")return!1;const t=ua(s);return!isNaN(Number(t))}function hI(s,t){const r=ua(s),n=ua(t),a=r.getFullYear()-n.getFullYear(),i=r.getMonth()-n.getMonth();return a*12+i}function RIt(s,t,r){const n=Fm(s,r),a=Fm(t,r),i=+n-j2(n),l=+a-j2(a);return Math.round((i-l)/p3e)}function Kg(s,t){const r=ua(s),n=ua(t),a=wOe(r,n),i=Math.abs(fx(r,n));r.setDate(r.getDate()-a*i);const l=+(wOe(r,n)===-a),o=a*(i-l);return o===0?0:o}function wOe(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 Uet(s){return t=>{const n=(s?Math[s]:Math.trunc)(t);return n===0?0:n}}function qet(s,t){return+ua(s)-+ua(t)}function OIt(s,t,r){const n=qet(s,t)/GB;return Uet(r==null?void 0:r.roundingMethod)(n)}function FIt(s){const t=ua(s);return t.setHours(23,59,59,999),t}function jg(s){const t=ua(s),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function BIt(s){const t=ua(s);return+FIt(t)==+jg(t)}function zIt(s,t){const r=ua(s),n=ua(t),a=mde(r,n),i=Math.abs(hI(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=mde(r,n)===-a;BIt(ua(s))&&i===1&&mde(s,n)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function $It(s,t,r){const n=qet(s,t)/1e3;return Uet(r==null?void 0:r.roundingMethod)(n)}function UIt(s,t){const r=ua(s.start),n=ua(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(ua(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Hc(s){const t=ua(s);return t.setDate(1),t.setHours(0,0,0,0),t}function Vet(s){const t=ua(s),r=Tl(s,0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}function Cpe(s,t){var o,c,d,h;const r=H2(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=ua(s),i=a.getDay(),l=(i{let n;const a=qIt[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 g1e(s){return(t={})=>{const r=t.width?String(t.width):s.defaultWidth;return s.formats[r]||s.formats[s.defaultWidth]}}const HIt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},GIt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},WIt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},KIt={date:g1e({formats:HIt,defaultWidth:"full"}),time:g1e({formats:GIt,defaultWidth:"full"}),dateTime:g1e({formats:WIt,defaultWidth:"full"})},YIt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ZIt=(s,t,r,n)=>YIt[s];function FD(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 XIt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},QIt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},JIt={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"]},ePt={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"]},tPt={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"}},sPt={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"}},rPt=(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"},nPt={ordinalNumber:rPt,era:FD({values:XIt,defaultWidth:"wide"}),quarter:FD({values:QIt,defaultWidth:"wide",argumentCallback:s=>s-1}),month:FD({values:JIt,defaultWidth:"wide"}),day:FD({values:ePt,defaultWidth:"wide"}),dayPeriod:FD({values:tPt,defaultWidth:"wide",formattingValues:sPt,defaultFormattingWidth:"wide"})};function BD(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)?iPt(o,m=>m.test(l)):aPt(o,m=>m.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=r.valueCallback?r.valueCallback(d):d;const h=t.slice(l.length);return{value:d,rest:h}}}function aPt(s,t){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)&&t(s[r]))return r}function iPt(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 lPt=/^(\d+)(th|st|nd|rd)?/i,cPt=/\d+/i,dPt={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},uPt={any:[/^b/i,/^(a|c)/i]},hPt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},mPt={any:[/1/i,/2/i,/3/i,/4/i]},fPt={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},pPt={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]},xPt={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},gPt={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]},yPt={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},vPt={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}},bPt={ordinalNumber:oPt({matchPattern:lPt,parsePattern:cPt,valueCallback:s=>parseInt(s,10)}),era:BD({matchPatterns:dPt,defaultMatchWidth:"wide",parsePatterns:uPt,defaultParseWidth:"any"}),quarter:BD({matchPatterns:hPt,defaultMatchWidth:"wide",parsePatterns:mPt,defaultParseWidth:"any",valueCallback:s=>s+1}),month:BD({matchPatterns:fPt,defaultMatchWidth:"wide",parsePatterns:pPt,defaultParseWidth:"any"}),day:BD({matchPatterns:xPt,defaultMatchWidth:"wide",parsePatterns:gPt,defaultParseWidth:"any"}),dayPeriod:BD({matchPatterns:yPt,defaultMatchWidth:"any",parsePatterns:vPt,defaultParseWidth:"any"})},Tpe={code:"en-US",formatDistance:VIt,formatLong:KIt,formatRelative:ZIt,localize:nPt,match:bPt,options:{weekStartsOn:0,firstWeekContainsDate:1}};function _Pt(s){const t=ua(s);return fx(t,Vet(t))+1}function y3e(s){const t=ua(s),r=+v_(t)-+IIt(t);return Math.round(r/p3e)+1}function v3e(s,t){var h,m,x,g;const r=ua(s),n=r.getFullYear(),a=H2(),i=(t==null?void 0:t.firstWeekContainsDate)??((m=(h=t==null?void 0:t.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??a.firstWeekContainsDate??((g=(x=a.locale)==null?void 0:x.options)==null?void 0:g.firstWeekContainsDate)??1,l=Tl(s,0);l.setFullYear(n+1,0,i),l.setHours(0,0,0,0);const o=Fm(l,t),c=Tl(s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=Fm(c,t);return r.getTime()>=o.getTime()?n+1:r.getTime()>=d.getTime()?n:n-1}function wPt(s,t){var o,c,d,h;const r=H2(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??r.firstWeekContainsDate??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,a=v3e(s,t),i=Tl(s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),Fm(i,t)}function b3e(s,t){const r=ua(s),n=+Fm(r,t)-+wPt(r,t);return Math.round(n/p3e)+1}function Sl(s,t){const r=s<0?"-":"",n=Math.abs(s).toString().padStart(t,"0");return r+n}const Iw={y(s,t){const r=s.getFullYear(),n=r>0?r:1-r;return Sl(t==="yy"?n%100:n,t.length)},M(s,t){const r=s.getMonth();return t==="M"?String(r+1):Sl(r+1,2)},d(s,t){return Sl(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 Sl(s.getHours()%12||12,t.length)},H(s,t){return Sl(s.getHours(),t.length)},m(s,t){return Sl(s.getMinutes(),t.length)},s(s,t){return Sl(s.getSeconds(),t.length)},S(s,t){const r=t.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,r-3));return Sl(a,t.length)}},RE={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},jOe={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 Iw.y(s,t)},Y:function(s,t,r,n){const a=v3e(s,n),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Sl(l,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):Sl(i,t.length)},R:function(s,t){const r=$et(s);return Sl(r,t.length)},u:function(s,t){const r=s.getFullYear();return Sl(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 Sl(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 Sl(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 Iw.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 Sl(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=b3e(s,n);return t==="wo"?r.ordinalNumber(a,{unit:"week"}):Sl(a,t.length)},I:function(s,t,r){const n=y3e(s);return t==="Io"?r.ordinalNumber(n,{unit:"week"}):Sl(n,t.length)},d:function(s,t,r){return t==="do"?r.ordinalNumber(s.getDate(),{unit:"date"}):Iw.d(s,t)},D:function(s,t,r){const n=_Pt(s);return t==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Sl(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 Sl(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 Sl(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 Sl(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=RE.noon:n===0?a=RE.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=RE.evening:n>=12?a=RE.afternoon:n>=4?a=RE.morning:a=RE.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 Iw.h(s,t)},H:function(s,t,r){return t==="Ho"?r.ordinalNumber(s.getHours(),{unit:"hour"}):Iw.H(s,t)},K:function(s,t,r){const n=s.getHours()%12;return t==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Sl(n,t.length)},k:function(s,t,r){let n=s.getHours();return n===0&&(n=24),t==="ko"?r.ordinalNumber(n,{unit:"hour"}):Sl(n,t.length)},m:function(s,t,r){return t==="mo"?r.ordinalNumber(s.getMinutes(),{unit:"minute"}):Iw.m(s,t)},s:function(s,t,r){return t==="so"?r.ordinalNumber(s.getSeconds(),{unit:"second"}):Iw.s(s,t)},S:function(s,t){return Iw.S(s,t)},X:function(s,t,r){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return kOe(n);case"XXXX":case"XX":return S4(n);case"XXXXX":case"XXX":default:return S4(n,":")}},x:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"x":return kOe(n);case"xxxx":case"xx":return S4(n);case"xxxxx":case"xxx":default:return S4(n,":")}},O:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+NOe(n,":");case"OOOO":default:return"GMT"+S4(n,":")}},z:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+NOe(n,":");case"zzzz":default:return"GMT"+S4(n,":")}},t:function(s,t,r){const n=Math.trunc(s.getTime()/1e3);return Sl(n,t.length)},T:function(s,t,r){const n=s.getTime();return Sl(n,t.length)}};function NOe(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+Sl(i,2)}function kOe(s,t){return s%60===0?(s>0?"-":"+")+Sl(Math.abs(s)/60,2):S4(s,t)}function S4(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=Sl(Math.trunc(n/60),2),i=Sl(n%60,2);return r+a+t+i}const SOe=(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"})}},Get=(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"})}},jPt=(s,t)=>{const r=s.match(/(P+)(p+)?/)||[],n=r[1],a=r[2];if(!a)return SOe(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}}",SOe(n,t)).replace("{{time}}",Get(a,t))},i2e={p:Get,P:jPt},NPt=/^D+$/,kPt=/^Y+$/,SPt=["D","DD","YY","YYYY"];function Wet(s){return NPt.test(s)}function Ket(s){return kPt.test(s)}function o2e(s,t,r){const n=CPt(s,t,r);if(console.warn(n),SPt.includes(s))throw new RangeError(n)}function CPt(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 TPt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,EPt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,APt=/^'([^]*?)'?$/,MPt=/''/g,IPt=/[a-zA-Z]/;function Ss(s,t,r){var h,m,x,g,v,j,b,N;const n=H2(),a=(r==null?void 0:r.locale)??n.locale??Tpe,i=(r==null?void 0:r.firstWeekContainsDate)??((m=(h=r==null?void 0:r.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??n.firstWeekContainsDate??((g=(x=n.locale)==null?void 0:x.options)==null?void 0:g.firstWeekContainsDate)??1,l=(r==null?void 0:r.weekStartsOn)??((j=(v=r==null?void 0:r.locale)==null?void 0:v.options)==null?void 0:j.weekStartsOn)??n.weekStartsOn??((N=(b=n.locale)==null?void 0:b.options)==null?void 0:N.weekStartsOn)??0,o=ua(s);if(!a2e(o))throw new RangeError("Invalid time value");let c=t.match(EPt).map(S=>{const T=S[0];if(T==="p"||T==="P"){const A=i2e[T];return A(S,a.formatLong)}return S}).join("").match(TPt).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const T=S[0];if(T==="'")return{isToken:!1,value:PPt(S)};if(jOe[T])return{isToken:!0,value:S};if(T.match(IPt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+T+"`");return{isToken:!1,value:S}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(S=>{if(!S.isToken)return S.value;const T=S.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&Ket(T)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&Wet(T))&&o2e(T,t,String(s));const A=jOe[T[0]];return A(o,T,a.localize,d)}).join("")}function PPt(s){const t=s.match(APt);return t?t[1].replace(MPt,"'"):s}function LPt(s,t,r){const n=H2(),a=(r==null?void 0:r.locale)??n.locale??Tpe,i=2520,l=mde(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=ua(t),d=ua(s)):(c=ua(s),d=ua(t));const h=$It(d,c),m=(j2(d)-j2(c))/1e3,x=Math.round((h-m)/60);let g;if(x<2)return r!=null&&r.includeSeconds?h<5?a.formatDistance("lessThanXSeconds",5,o):h<10?a.formatDistance("lessThanXSeconds",10,o):h<20?a.formatDistance("lessThanXSeconds",20,o):h<40?a.formatDistance("halfAMinute",0,o):h<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):x===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",x,o);if(x<45)return a.formatDistance("xMinutes",x,o);if(x<90)return a.formatDistance("aboutXHours",1,o);if(xn.getTime()}function v5(s,t){const r=ua(s),n=ua(t);return+r<+n}function $Pt(s){return+ua(s)>Date.now()}function UPt(s,t){const r=t instanceof Date?Tl(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 qPt=10;class Yet{constructor(){Vn(this,"subPriority",0)}validate(t,r){return!0}}class VPt extends Yet{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 HPt extends Yet{constructor(){super(...arguments);Vn(this,"priority",qPt);Vn(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:Tl(r,UPt(r,Date))}}class xl{run(t,r,n,a){const i=this.parse(t,r,n,a);return i?{setter:new VPt(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,n){return!0}}class GPt extends xl{constructor(){super(...arguments);Vn(this,"priority",140);Vn(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 ru={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}/},kv={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 nu(s,t){return s&&{value:t(s.value),rest:s.rest}}function cd(s,t){const r=t.match(s);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function Sv(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*GB+i*Spe+l*AIt),rest:t.slice(r[0].length)}}function Zet(s){return cd(ru.anyDigitsSigned,s)}function $d(s,t){switch(s){case 1:return cd(ru.singleDigit,t);case 2:return cd(ru.twoDigits,t);case 3:return cd(ru.threeDigits,t);case 4:return cd(ru.fourDigits,t);default:return cd(new RegExp("^\\d{1,"+s+"}"),t)}}function Iue(s,t){switch(s){case 1:return cd(ru.singleDigitSigned,t);case 2:return cd(ru.twoDigitsSigned,t);case 3:return cd(ru.threeDigitsSigned,t);case 4:return cd(ru.fourDigitsSigned,t);default:return cd(new RegExp("^-?\\d{1,"+s+"}"),t)}}function _3e(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 Xet(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 Qet(s){return s%400===0||s%4===0&&s%100!==0}class WPt extends xl{constructor(){super(...arguments);Vn(this,"priority",130);Vn(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 nu($d(4,r),i);case"yo":return nu(a.ordinalNumber(r,{unit:"year"}),i);default:return nu($d(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=Xet(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 KPt extends xl{constructor(){super(...arguments);Vn(this,"priority",130);Vn(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 nu($d(4,r),i);case"Yo":return nu(a.ordinalNumber(r,{unit:"year"}),i);default:return nu($d(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a,i){const l=v3e(r,i);if(a.isTwoDigitYear){const c=Xet(a.year,l);return r.setFullYear(c,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),Fm(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),Fm(r,i)}}class YPt extends xl{constructor(){super(...arguments);Vn(this,"priority",130);Vn(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return Iue(n==="R"?4:n.length,r)}set(r,n,a){const i=Tl(r,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),v_(i)}}class ZPt extends xl{constructor(){super(...arguments);Vn(this,"priority",130);Vn(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return Iue(n==="u"?4:n.length,r)}set(r,n,a){return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}class XPt extends xl{constructor(){super(...arguments);Vn(this,"priority",120);Vn(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 $d(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 QPt extends xl{constructor(){super(...arguments);Vn(this,"priority",120);Vn(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 $d(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 JPt extends xl{constructor(){super(...arguments);Vn(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Vn(this,"priority",110)}parse(r,n,a){const i=l=>l-1;switch(n){case"M":return nu(cd(ru.month,r),i);case"MM":return nu($d(2,r),i);case"Mo":return nu(a.ordinalNumber(r,{unit:"month"}),i);case"MMM":return a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(r,{width:"wide",context:"formatting"})||a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}class eLt extends xl{constructor(){super(...arguments);Vn(this,"priority",110);Vn(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 nu(cd(ru.month,r),i);case"LL":return nu($d(2,r),i);case"Lo":return nu(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 tLt(s,t,r){const n=ua(s),a=b3e(n,r)-t;return n.setDate(n.getDate()-a*7),n}class sLt extends xl{constructor(){super(...arguments);Vn(this,"priority",100);Vn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,a){switch(n){case"w":return cd(ru.week,r);case"wo":return a.ordinalNumber(r,{unit:"week"});default:return $d(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a,i){return Fm(tLt(r,a,i),i)}}function rLt(s,t){const r=ua(s),n=y3e(r)-t;return r.setDate(r.getDate()-n*7),r}class nLt extends xl{constructor(){super(...arguments);Vn(this,"priority",100);Vn(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 cd(ru.week,r);case"Io":return a.ordinalNumber(r,{unit:"week"});default:return $d(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a){return v_(rLt(r,a))}}const aLt=[31,28,31,30,31,30,31,31,30,31,30,31],iLt=[31,29,31,30,31,30,31,31,30,31,30,31];class oLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(this,"subPriority",1);Vn(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"d":return cd(ru.date,r);case"do":return a.ordinalNumber(r,{unit:"date"});default:return $d(n.length,r)}}validate(r,n){const a=r.getFullYear(),i=Qet(a),l=r.getMonth();return i?n>=1&&n<=iLt[l]:n>=1&&n<=aLt[l]}set(r,n,a){return r.setDate(a),r.setHours(0,0,0,0),r}}class lLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(this,"subpriority",1);Vn(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 cd(ru.dayOfYear,r);case"Do":return a.ordinalNumber(r,{unit:"date"});default:return $d(n.length,r)}}validate(r,n){const a=r.getFullYear();return Qet(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 w3e(s,t,r){var m,x,g,v;const n=H2(),a=(r==null?void 0:r.weekStartsOn)??((x=(m=r==null?void 0:r.locale)==null?void 0:m.options)==null?void 0:x.weekStartsOn)??n.weekStartsOn??((v=(g=n.locale)==null?void 0:g.options)==null?void 0:v.weekStartsOn)??0,i=ua(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,h=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return Hl(i,h)}class cLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(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=w3e(r,a,i),r.setHours(0,0,0,0),r}}class dLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(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 nu($d(n.length,r),l);case"eo":return nu(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=w3e(r,a,i),r.setHours(0,0,0,0),r}}class uLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(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 nu($d(n.length,r),l);case"co":return nu(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=w3e(r,a,i),r.setHours(0,0,0,0),r}}function hLt(s,t){const r=ua(s),n=OPt(r),a=t-n;return Hl(r,a)}class mLt extends xl{constructor(){super(...arguments);Vn(this,"priority",90);Vn(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 $d(n.length,r);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return nu(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 nu(a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiiii":return nu(a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiii":default:return nu(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=hLt(r,a),r.setHours(0,0,0,0),r}}class fLt extends xl{constructor(){super(...arguments);Vn(this,"priority",80);Vn(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(_3e(a),0,0,0),r}}class pLt extends xl{constructor(){super(...arguments);Vn(this,"priority",80);Vn(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(_3e(a),0,0,0),r}}class xLt extends xl{constructor(){super(...arguments);Vn(this,"priority",80);Vn(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(_3e(a),0,0,0),r}}class gLt extends xl{constructor(){super(...arguments);Vn(this,"priority",70);Vn(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,a){switch(n){case"h":return cd(ru.hour12h,r);case"ho":return a.ordinalNumber(r,{unit:"hour"});default:return $d(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 yLt extends xl{constructor(){super(...arguments);Vn(this,"priority",70);Vn(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,a){switch(n){case"H":return cd(ru.hour23h,r);case"Ho":return a.ordinalNumber(r,{unit:"hour"});default:return $d(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,a){return r.setHours(a,0,0,0),r}}class vLt extends xl{constructor(){super(...arguments);Vn(this,"priority",70);Vn(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,a){switch(n){case"K":return cd(ru.hour11h,r);case"Ko":return a.ordinalNumber(r,{unit:"hour"});default:return $d(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 bLt extends xl{constructor(){super(...arguments);Vn(this,"priority",70);Vn(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,a){switch(n){case"k":return cd(ru.hour24h,r);case"ko":return a.ordinalNumber(r,{unit:"hour"});default:return $d(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 _Lt extends xl{constructor(){super(...arguments);Vn(this,"priority",60);Vn(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"m":return cd(ru.minute,r);case"mo":return a.ordinalNumber(r,{unit:"minute"});default:return $d(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setMinutes(a,0,0),r}}class wLt extends xl{constructor(){super(...arguments);Vn(this,"priority",50);Vn(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"s":return cd(ru.second,r);case"so":return a.ordinalNumber(r,{unit:"second"});default:return $d(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setSeconds(a,0),r}}class jLt extends xl{constructor(){super(...arguments);Vn(this,"priority",30);Vn(this,"incompatibleTokens",["t","T"])}parse(r,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return nu($d(n.length,r),a)}set(r,n,a){return r.setMilliseconds(a),r}}class NLt extends xl{constructor(){super(...arguments);Vn(this,"priority",10);Vn(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Sv(kv.basicOptionalMinutes,r);case"XX":return Sv(kv.basic,r);case"XXXX":return Sv(kv.basicOptionalSeconds,r);case"XXXXX":return Sv(kv.extendedOptionalSeconds,r);case"XXX":default:return Sv(kv.extended,r)}}set(r,n,a){return n.timestampIsSet?r:Tl(r,r.getTime()-j2(r)-a)}}class kLt extends xl{constructor(){super(...arguments);Vn(this,"priority",10);Vn(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Sv(kv.basicOptionalMinutes,r);case"xx":return Sv(kv.basic,r);case"xxxx":return Sv(kv.basicOptionalSeconds,r);case"xxxxx":return Sv(kv.extendedOptionalSeconds,r);case"xxx":default:return Sv(kv.extended,r)}}set(r,n,a){return n.timestampIsSet?r:Tl(r,r.getTime()-j2(r)-a)}}class SLt extends xl{constructor(){super(...arguments);Vn(this,"priority",40);Vn(this,"incompatibleTokens","*")}parse(r){return Zet(r)}set(r,n,a){return[Tl(r,a*1e3),{timestampIsSet:!0}]}}class CLt extends xl{constructor(){super(...arguments);Vn(this,"priority",20);Vn(this,"incompatibleTokens","*")}parse(r){return Zet(r)}set(r,n,a){return[Tl(r,a),{timestampIsSet:!0}]}}const TLt={G:new GPt,y:new WPt,Y:new KPt,R:new YPt,u:new ZPt,Q:new XPt,q:new QPt,M:new JPt,L:new eLt,w:new sLt,I:new nLt,d:new oLt,D:new lLt,E:new cLt,e:new dLt,c:new uLt,i:new mLt,a:new fLt,b:new pLt,B:new xLt,h:new gLt,H:new yLt,K:new vLt,k:new bLt,m:new _Lt,s:new wLt,S:new jLt,X:new NLt,x:new kLt,t:new SLt,T:new CLt},ELt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,ALt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,MLt=/^'([^]*?)'?$/,ILt=/''/g,PLt=/\S/,LLt=/[a-zA-Z]/;function j3e(s,t,r,n){var j,b,N,S;const a=RPt(),i=a.locale??Tpe,l=a.firstWeekContainsDate??((b=(j=a.locale)==null?void 0:j.options)==null?void 0:b.firstWeekContainsDate)??1,o=a.weekStartsOn??((S=(N=a.locale)==null?void 0:N.options)==null?void 0:S.weekStartsOn)??0;if(t==="")return s===""?ua(r):Tl(r,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new HPt],h=t.match(ALt).map(T=>{const A=T[0];if(A in i2e){const P=i2e[A];return P(T,i.formatLong)}return T}).join("").match(ELt),m=[];for(let T of h){Ket(T)&&o2e(T,t,s),Wet(T)&&o2e(T,t,s);const A=T[0],P=TLt[A];if(P){const{incompatibleTokens:D}=P;if(Array.isArray(D)){const z=m.find(F=>D.includes(F.token)||F.token===A);if(z)throw new RangeError(`The format string mustn't contain \`${z.fullToken}\` and \`${T}\` at the same time`)}else if(P.incompatibleTokens==="*"&&m.length>0)throw new RangeError(`The format string mustn't contain \`${T}\` and any other token at the same time`);m.push({token:A,fullToken:T});const B=P.run(s,T,i.match,c);if(!B)return Tl(r,NaN);d.push(B.setter),s=B.rest}else{if(A.match(LLt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(T==="''"?T="'":A==="'"&&(T=DLt(T)),s.indexOf(T)===0)s=s.slice(T.length);else return Tl(r,NaN)}}if(s.length>0&&PLt.test(s))return Tl(r,NaN);const x=d.map(T=>T.priority).sort((T,A)=>A-T).filter((T,A,P)=>P.indexOf(T)===A).map(T=>d.filter(A=>A.priority===T).sort((A,P)=>P.subPriority-A.subPriority)).map(T=>T[0]);let g=ua(r);if(isNaN(g.getTime()))return Tl(r,NaN);const v={};for(const T of x){if(!T.validate(g,c))return Tl(r,NaN);const A=T.set(g,v,c);Array.isArray(A)?(g=A[0],Object.assign(v,A[1])):g=A}return Tl(r,g)}function DLt(s){return s.match(MLt)[1].replace(ILt,"'")}function Xv(s){return+ua(s)i-l);return r>=n&&r<=a}function fde(s,t){return Hl(s,-t)}function ff(s,t){const n=ULt(s);let a;if(n.date){const c=qLt(n.date,2);a=VLt(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=HLt(n.time),isNaN(l)))return new Date(NaN);if(n.timezone){if(o=GLt(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 eU={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},BLt=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,zLt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,$Lt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function ULt(s){const t={},r=s.split(eU.dateTimeDelimiter);let n;if(r.length>2)return t;if(/:/.test(r[0])?n=r[0]:(t.date=r[0],n=r[1],eU.timeZoneDelimiter.test(t.date)&&(t.date=s.split(eU.timeZoneDelimiter)[0],n=s.substr(t.date.length,s.length))),n){const a=eU.timezone.exec(n);a?(t.time=n.replace(a[1],""),t.timezone=a[1]):t.time=n}return t}function qLt(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 VLt(s,t){if(t===null)return new Date(NaN);const r=s.match(BLt);if(!r)return new Date(NaN);const n=!!r[4],a=zD(r[1]),i=zD(r[2])-1,l=zD(r[3]),o=zD(r[4]),c=zD(r[5])-1;if(n)return XLt(t,o,c)?WLt(t,o,c):new Date(NaN);{const d=new Date(0);return!YLt(t,i,l)||!ZLt(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function zD(s){return s?parseInt(s):1}function HLt(s){const t=s.match(zLt);if(!t)return NaN;const r=y1e(t[1]),n=y1e(t[2]),a=y1e(t[3]);return QLt(r,n,a)?r*GB+n*Spe+a*1e3:NaN}function y1e(s){return s&&parseFloat(s.replace(",","."))||0}function GLt(s){if(s==="Z")return 0;const t=s.match($Lt);if(!t)return 0;const r=t[1]==="+"?-1:1,n=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return JLt(n,a)?r*(n*GB+a*Spe):NaN}function WLt(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 KLt=[31,null,31,30,31,30,31,31,30,31,30,31];function Jet(s){return s%400===0||s%4===0&&s%100!==0}function YLt(s,t,r){return t>=0&&t<=11&&r>=1&&r<=(KLt[t]||(Jet(s)?29:28))}function ZLt(s,t){return t>=1&&t<=(Jet(s)?366:365)}function XLt(s,t,r){return t>=1&&t<=53&&r>=0&&r<=6}function QLt(s,t,r){return s===24?t===0&&r===0:r>=0&&r<60&&t>=0&&t<60&&s>=0&&s<25}function JLt(s,t){return t>=0&&t<=59}function v1e(s,t){const r=ua(s),n=r.getFullYear(),a=r.getDate(),i=Tl(s,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);const l=DPt(i);return r.setMonth(t,Math.min(a,l)),r}function GO(s,t){const r=ua(s);return r.setHours(t),r}function WO(s,t){const r=ua(s);return r.setMinutes(t),r}function TOe(s,t){const r=ua(s);return isNaN(+r)?Tl(s,NaN):(r.setFullYear(t),r)}function q4(s,t){return Cf(s,-t)}var el;(function(s){s.assertEqual=a=>{};function t(a){}s.assertIs=t;function r(a){throw new Error}s.assertNever=r,s.arrayToEnum=a=>{const i={};for(const l of a)i[l]=l;return i},s.getValidEnumValues=a=>{const i=s.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),l={};for(const o of i)l[o]=a[o];return s.objectValues(l)},s.objectValues=a=>s.objectKeys(a).map(function(i){return a[i]}),s.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&i.push(l);return i},s.find=(a,i)=>{for(const l of a)if(i(l))return l},s.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,i=" | "){return a.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}s.joinValues=n,s.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(el||(el={}));var EOe;(function(s){s.mergeShapes=(t,r)=>({...t,...r})})(EOe||(EOe={}));const Ca=el.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qw=s=>{switch(typeof s){case"undefined":return Ca.undefined;case"string":return Ca.string;case"number":return Number.isNaN(s)?Ca.nan:Ca.number;case"boolean":return Ca.boolean;case"function":return Ca.function;case"bigint":return Ca.bigint;case"symbol":return Ca.symbol;case"object":return Array.isArray(s)?Ca.array:s===null?Ca.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?Ca.promise:typeof Map<"u"&&s instanceof Map?Ca.map:typeof Set<"u"&&s instanceof Set?Ca.set:typeof Date<"u"&&s instanceof Date?Ca.date:Ca.object;default:return Ca.unknown}},yn=el.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class n1 extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(i){return i.message},n={_errors:[]},a=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(a);else if(l.code==="invalid_return_type")a(l.returnTypeError);else if(l.code==="invalid_arguments")a(l.argumentsError);else if(l.path.length===0)n._errors.push(r(l));else{let o=n,c=0;for(;cr.message){const r={},n=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];r[i]=r[i]||[],r[i].push(t(a))}else n.push(t(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}n1.create=s=>new n1(s);const l2e=(s,t)=>{let r;switch(s.code){case yn.invalid_type:s.received===Ca.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case yn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,el.jsonStringifyReplacer)}`;break;case yn.unrecognized_keys:r=`Unrecognized key(s) in object: ${el.joinValues(s.keys,", ")}`;break;case yn.invalid_union:r="Invalid input";break;case yn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${el.joinValues(s.options)}`;break;case yn.invalid_enum_value:r=`Invalid enum value. Expected ${el.joinValues(s.options)}, received '${s.received}'`;break;case yn.invalid_arguments:r="Invalid function arguments";break;case yn.invalid_return_type:r="Invalid function return type";break;case yn.invalid_date:r="Invalid date";break;case yn.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:el.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case yn.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case yn.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case yn.custom:r="Invalid input";break;case yn.invalid_intersection_types:r="Intersection results could not be merged";break;case yn.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case yn.not_finite:r="Number must be finite";break;default:r=t.defaultError,el.assertNever(s)}return{message:r}};let e6t=l2e;function t6t(){return e6t}const s6t=s=>{const{data:t,path:r,errorMaps:n,issueData:a}=s,i=[...r,...a.path||[]],l={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let o="";const c=n.filter(d=>!!d).slice().reverse();for(const d of c)o=d(l,{data:t,defaultError:o}).message;return{...a,path:i,message:o}};function ia(s,t){const r=t6t(),n=s6t({issueData:t,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===l2e?void 0:l2e].filter(a=>!!a)});s.common.issues.push(n)}class Mx{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const a of r){if(a.status==="aborted")return Ri;a.status==="dirty"&&t.dirty(),n.push(a.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const a of r){const i=await a.key,l=await a.value;n.push({key:i,value:l})}return Mx.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const a of r){const{key:i,value:l}=a;if(i.status==="aborted"||l.status==="aborted")return Ri;i.status==="dirty"&&t.dirty(),l.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||a.alwaysSet)&&(n[i.value]=l.value)}return{status:t.value,value:n}}}const Ri=Object.freeze({status:"aborted"}),_R=s=>({status:"dirty",value:s}),Qg=s=>({status:"valid",value:s}),AOe=s=>s.status==="aborted",MOe=s=>s.status==="dirty",mI=s=>s.status==="valid",Pue=s=>typeof Promise<"u"&&s instanceof Promise;var La;(function(s){s.errToObj=t=>typeof t=="string"?{message:t}:t||{},s.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(La||(La={}));class N2{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const IOe=(s,t)=>{if(mI(t))return{success:!0,data:t.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new n1(s.common.issues);return this._error=r,this._error}}};function co(s){if(!s)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=s;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(l,o)=>{const{message:c}=s;return l.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:l.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class Xo{get description(){return this._def.description}_getType(t){return Qw(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Qw(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Mx,ctx:{common:t.parent.common,data:t.data,parsedType:Qw(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Pue(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Qw(t)},a=this._parseSync({data:t,path:n.path,parent:n});return IOe(n,a)}"~validate"(t){var n,a;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Qw(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return mI(i)?{value:i.value}:{issues:r.common.issues}}catch(i){(a=(n=i==null?void 0:i.message)==null?void 0:n.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>mI(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Qw(t)},a=this._parse({data:t,path:n.path,parent:n}),i=await(Pue(a)?a:Promise.resolve(a));return IOe(n,i)}refine(t,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,i)=>{const l=t(a),o=()=>i.addIssue({code:yn.custom,...n(a)});return typeof Promise<"u"&&l instanceof Promise?l.then(c=>c?!0:(o(),!1)):l?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,a)=>t(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(t){return new xI({schema:this,typeName:Oi.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return i2.create(this,this._def)}nullable(){return gI.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qv.create(this)}promise(){return Oue.create(this,this._def)}or(t){return Due.create([this,t],this._def)}and(t){return Rue.create(this,t,this._def)}transform(t){return new xI({...co(this._def),schema:this,typeName:Oi.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new h2e({...co(this._def),innerType:this,defaultValue:r,typeName:Oi.ZodDefault})}brand(){return new k6t({typeName:Oi.ZodBranded,type:this,...co(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new m2e({...co(this._def),innerType:this,catchValue:r,typeName:Oi.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return N3e.create(this,t)}readonly(){return f2e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const r6t=/^c[^\s-]{8,}$/i,n6t=/^[0-9a-z]+$/,a6t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,i6t=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,o6t=/^[a-z0-9_-]{21}$/i,l6t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,c6t=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,d6t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,u6t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let b1e;const h6t=/^(?:(?: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])$/,m6t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,f6t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,p6t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,x6t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g6t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ett="((\\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])))",y6t=new RegExp(`^${ett}$`);function ttt(s){let t="[0-5]\\d";s.precision?t=`${t}\\.\\d{${s.precision}}`:s.precision==null&&(t=`${t}(\\.\\d+)?`);const r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function v6t(s){return new RegExp(`^${ttt(s)}$`)}function b6t(s){let t=`${ett}T${ttt(s)}`;const r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function _6t(s,t){return!!((t==="v4"||!t)&&h6t.test(s)||(t==="v6"||!t)&&f6t.test(s))}function w6t(s,t){if(!l6t.test(s))return!1;try{const[r]=s.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function j6t(s,t){return!!((t==="v4"||!t)&&m6t.test(s)||(t==="v6"||!t)&&p6t.test(s))}class Ej extends Xo{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ca.string){const i=this._getOrReturnCtx(t);return ia(i,{code:yn.invalid_type,expected:Ca.string,received:i.parsedType}),Ri}const n=new Mx;let a;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(a=this._getOrReturnCtx(t,a),ia(a,{code:yn.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const l=t.data.length>i.value,o=t.data.lengtht.test(a),{validation:r,code:yn.invalid_string,...La.errToObj(n)})}_addCheck(t){return new Ej({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...La.errToObj(t)})}url(t){return this._addCheck({kind:"url",...La.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...La.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...La.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...La.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...La.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...La.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...La.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...La.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...La.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...La.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...La.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...La.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...La.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...La.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...La.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...La.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r==null?void 0:r.position,...La.errToObj(r==null?void 0:r.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...La.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...La.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...La.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...La.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...La.errToObj(r)})}nonempty(t){return this.min(1,La.errToObj(t))}trim(){return new Ej({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ej({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ej({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Ej({checks:[],typeName:Oi.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...co(s)});function N6t(s,t){const r=(s.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,i=Number.parseInt(s.toFixed(a).replace(".","")),l=Number.parseInt(t.toFixed(a).replace(".",""));return i%l/10**a}class fI extends Xo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ca.number){const i=this._getOrReturnCtx(t);return ia(i,{code:yn.invalid_type,expected:Ca.number,received:i.parsedType}),Ri}let n;const a=new Mx;for(const i of this._def.checks)i.kind==="int"?el.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?N6t(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.not_finite,message:i.message}),a.dirty()):el.assertNever(i);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,La.toString(r))}gt(t,r){return this.setLimit("min",t,!1,La.toString(r))}lte(t,r){return this.setLimit("max",t,!0,La.toString(r))}lt(t,r){return this.setLimit("max",t,!1,La.toString(r))}setLimit(t,r,n,a){return new fI({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:La.toString(a)}]})}_addCheck(t){return new fI({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:La.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:La.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:La.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:La.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:La.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:La.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:La.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:La.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:La.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&el.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.valuenew fI({checks:[],typeName:Oi.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...co(s)});class sF extends Xo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ca.bigint)return this._getInvalidInput(t);let n;const a=new Mx;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ia(n,{code:yn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):el.assertNever(i);return{status:a.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ia(r,{code:yn.invalid_type,expected:Ca.bigint,received:r.parsedType}),Ri}gte(t,r){return this.setLimit("min",t,!0,La.toString(r))}gt(t,r){return this.setLimit("min",t,!1,La.toString(r))}lte(t,r){return this.setLimit("max",t,!0,La.toString(r))}lt(t,r){return this.setLimit("max",t,!1,La.toString(r))}setLimit(t,r,n,a){return new sF({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:La.toString(a)}]})}_addCheck(t){return new sF({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:La.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:La.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:La.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:La.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:La.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew sF({checks:[],typeName:Oi.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...co(s)});class c2e extends Xo{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ca.boolean){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.boolean,received:n.parsedType}),Ri}return Qg(t.data)}}c2e.create=s=>new c2e({typeName:Oi.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...co(s)});class Lue extends Xo{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ca.date){const i=this._getOrReturnCtx(t);return ia(i,{code:yn.invalid_type,expected:Ca.date,received:i.parsedType}),Ri}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return ia(i,{code:yn.invalid_date}),Ri}const n=new Mx;let a;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(a=this._getOrReturnCtx(t,a),ia(a,{code:yn.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):el.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Lue({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:La.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:La.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Lue({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:Oi.ZodDate,...co(s)});class POe extends Xo{_parse(t){if(this._getType(t)!==Ca.symbol){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.symbol,received:n.parsedType}),Ri}return Qg(t.data)}}POe.create=s=>new POe({typeName:Oi.ZodSymbol,...co(s)});class LOe extends Xo{_parse(t){if(this._getType(t)!==Ca.undefined){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.undefined,received:n.parsedType}),Ri}return Qg(t.data)}}LOe.create=s=>new LOe({typeName:Oi.ZodUndefined,...co(s)});class DOe extends Xo{_parse(t){if(this._getType(t)!==Ca.null){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.null,received:n.parsedType}),Ri}return Qg(t.data)}}DOe.create=s=>new DOe({typeName:Oi.ZodNull,...co(s)});class ROe extends Xo{constructor(){super(...arguments),this._any=!0}_parse(t){return Qg(t.data)}}ROe.create=s=>new ROe({typeName:Oi.ZodAny,...co(s)});class OOe extends Xo{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Qg(t.data)}}OOe.create=s=>new OOe({typeName:Oi.ZodUnknown,...co(s)});class k2 extends Xo{_parse(t){const r=this._getOrReturnCtx(t);return ia(r,{code:yn.invalid_type,expected:Ca.never,received:r.parsedType}),Ri}}k2.create=s=>new k2({typeName:Oi.ZodNever,...co(s)});class FOe extends Xo{_parse(t){if(this._getType(t)!==Ca.undefined){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.void,received:n.parsedType}),Ri}return Qg(t.data)}}FOe.create=s=>new FOe({typeName:Oi.ZodVoid,...co(s)});class Qv extends Xo{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==Ca.array)return ia(r,{code:yn.invalid_type,expected:Ca.array,received:r.parsedType}),Ri;if(a.exactLength!==null){const l=r.data.length>a.exactLength.value,o=r.data.lengtha.maxLength.value&&(ia(r,{code:yn.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((l,o)=>a.type._parseAsync(new N2(r,l,r.path,o)))).then(l=>Mx.mergeArray(n,l));const i=[...r.data].map((l,o)=>a.type._parseSync(new N2(r,l,r.path,o)));return Mx.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new Qv({...this._def,minLength:{value:t,message:La.toString(r)}})}max(t,r){return new Qv({...this._def,maxLength:{value:t,message:La.toString(r)}})}length(t,r){return new Qv({...this._def,exactLength:{value:t,message:La.toString(r)}})}nonempty(t){return this.min(1,t)}}Qv.create=(s,t)=>new Qv({type:s,minLength:null,maxLength:null,exactLength:null,typeName:Oi.ZodArray,...co(t)});function oA(s){if(s instanceof yu){const t={};for(const r in s.shape){const n=s.shape[r];t[r]=i2.create(oA(n))}return new yu({...s._def,shape:()=>t})}else return s instanceof Qv?new Qv({...s._def,type:oA(s.element)}):s instanceof i2?i2.create(oA(s.unwrap())):s instanceof gI?gI.create(oA(s.unwrap())):s instanceof b5?b5.create(s.items.map(t=>oA(t))):s}class yu extends Xo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=el.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ca.object){const d=this._getOrReturnCtx(t);return ia(d,{code:yn.invalid_type,expected:Ca.object,received:d.parsedType}),Ri}const{status:n,ctx:a}=this._processInputParams(t),{shape:i,keys:l}=this._getCached(),o=[];if(!(this._def.catchall instanceof k2&&this._def.unknownKeys==="strip"))for(const d in a.data)l.includes(d)||o.push(d);const c=[];for(const d of l){const h=i[d],m=a.data[d];c.push({key:{status:"valid",value:d},value:h._parse(new N2(a,m,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof k2){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of o)c.push({key:{status:"valid",value:h},value:{status:"valid",value:a.data[h]}});else if(d==="strict")o.length>0&&(ia(a,{code:yn.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of o){const m=a.data[h];c.push({key:{status:"valid",value:h},value:d._parse(new N2(a,m,a.path,h)),alwaysSet:h in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of c){const m=await h.key,x=await h.value;d.push({key:m,value:x,alwaysSet:h.alwaysSet})}return d}).then(d=>Mx.mergeObjectSync(n,d)):Mx.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return La.errToObj,new yu({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var i,l;const a=((l=(i=this._def).errorMap)==null?void 0:l.call(i,r,n).message)??n.defaultError;return r.code==="unrecognized_keys"?{message:La.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new yu({...this._def,unknownKeys:"strip"})}passthrough(){return new yu({...this._def,unknownKeys:"passthrough"})}extend(t){return new yu({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new yu({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Oi.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new yu({...this._def,catchall:t})}pick(t){const r={};for(const n of el.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new yu({...this._def,shape:()=>r})}omit(t){const r={};for(const n of el.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new yu({...this._def,shape:()=>r})}deepPartial(){return oA(this)}partial(t){const r={};for(const n of el.objectKeys(this.shape)){const a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional()}return new yu({...this._def,shape:()=>r})}required(t){const r={};for(const n of el.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof i2;)i=i._def.innerType;r[n]=i}return new yu({...this._def,shape:()=>r})}keyof(){return stt(el.objectKeys(this.shape))}}yu.create=(s,t)=>new yu({shape:()=>s,unknownKeys:"strip",catchall:k2.create(),typeName:Oi.ZodObject,...co(t)});yu.strictCreate=(s,t)=>new yu({shape:()=>s,unknownKeys:"strict",catchall:k2.create(),typeName:Oi.ZodObject,...co(t)});yu.lazycreate=(s,t)=>new yu({shape:s,unknownKeys:"strip",catchall:k2.create(),typeName:Oi.ZodObject,...co(t)});class Due extends Xo{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function a(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const l=i.map(o=>new n1(o.ctx.common.issues));return ia(r,{code:yn.invalid_union,unionErrors:l}),Ri}if(r.common.async)return Promise.all(n.map(async i=>{const l={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:l}),ctx:l}})).then(a);{let i;const l=[];for(const c of n){const d={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=l.map(c=>new n1(c));return ia(r,{code:yn.invalid_union,unionErrors:o}),Ri}}get options(){return this._def.options}}Due.create=(s,t)=>new Due({options:s,typeName:Oi.ZodUnion,...co(t)});function d2e(s,t){const r=Qw(s),n=Qw(t);if(s===t)return{valid:!0,data:s};if(r===Ca.object&&n===Ca.object){const a=el.objectKeys(t),i=el.objectKeys(s).filter(o=>a.indexOf(o)!==-1),l={...s,...t};for(const o of i){const c=d2e(s[o],t[o]);if(!c.valid)return{valid:!1};l[o]=c.data}return{valid:!0,data:l}}else if(r===Ca.array&&n===Ca.array){if(s.length!==t.length)return{valid:!1};const a=[];for(let i=0;i{if(AOe(i)||AOe(l))return Ri;const o=d2e(i.value,l.value);return o.valid?((MOe(i)||MOe(l))&&r.dirty(),{status:r.value,value:o.data}):(ia(n,{code:yn.invalid_intersection_types}),Ri)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,l])=>a(i,l)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Rue.create=(s,t,r)=>new Rue({left:s,right:t,typeName:Oi.ZodIntersection,...co(r)});class b5 extends Xo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ca.array)return ia(n,{code:yn.invalid_type,expected:Ca.array,received:n.parsedType}),Ri;if(n.data.lengththis._def.items.length&&(ia(n,{code:yn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((l,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new N2(n,l,n.path,o)):null}).filter(l=>!!l);return n.common.async?Promise.all(i).then(l=>Mx.mergeArray(r,l)):Mx.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new b5({...this._def,rest:t})}}b5.create=(s,t)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new b5({items:s,typeName:Oi.ZodTuple,rest:null,...co(t)})};class BOe extends Xo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ca.map)return ia(n,{code:yn.invalid_type,expected:Ca.map,received:n.parsedType}),Ri;const a=this._def.keyType,i=this._def.valueType,l=[...n.data.entries()].map(([o,c],d)=>({key:a._parse(new N2(n,o,n.path,[d,"key"])),value:i._parse(new N2(n,c,n.path,[d,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of l){const d=await c.key,h=await c.value;if(d.status==="aborted"||h.status==="aborted")return Ri;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of l){const d=c.key,h=c.value;if(d.status==="aborted"||h.status==="aborted")return Ri;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}}}}BOe.create=(s,t,r)=>new BOe({valueType:t,keyType:s,typeName:Oi.ZodMap,...co(r)});class rF extends Xo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ca.set)return ia(n,{code:yn.invalid_type,expected:Ca.set,received:n.parsedType}),Ri;const a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&(ia(n,{code:yn.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const i=this._def.valueType;function l(c){const d=new Set;for(const h of c){if(h.status==="aborted")return Ri;h.status==="dirty"&&r.dirty(),d.add(h.value)}return{status:r.value,value:d}}const o=[...n.data.values()].map((c,d)=>i._parse(new N2(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>l(c)):l(o)}min(t,r){return new rF({...this._def,minSize:{value:t,message:La.toString(r)}})}max(t,r){return new rF({...this._def,maxSize:{value:t,message:La.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}rF.create=(s,t)=>new rF({valueType:s,minSize:null,maxSize:null,typeName:Oi.ZodSet,...co(t)});class zOe extends Xo{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}zOe.create=(s,t)=>new zOe({getter:s,typeName:Oi.ZodLazy,...co(t)});class u2e extends Xo{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ia(r,{received:r.data,code:yn.invalid_literal,expected:this._def.value}),Ri}return{status:"valid",value:t.data}}get value(){return this._def.value}}u2e.create=(s,t)=>new u2e({value:s,typeName:Oi.ZodLiteral,...co(t)});function stt(s,t){return new pI({values:s,typeName:Oi.ZodEnum,...co(t)})}class pI extends Xo{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ia(r,{expected:el.joinValues(n),received:r.parsedType,code:yn.invalid_type}),Ri}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return ia(r,{received:r.data,code:yn.invalid_enum_value,options:n}),Ri}return Qg(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return pI.create(t,{...this._def,...r})}exclude(t,r=this._def){return pI.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}pI.create=stt;class $Oe extends Xo{_parse(t){const r=el.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ca.string&&n.parsedType!==Ca.number){const a=el.objectValues(r);return ia(n,{expected:el.joinValues(a),received:n.parsedType,code:yn.invalid_type}),Ri}if(this._cache||(this._cache=new Set(el.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const a=el.objectValues(r);return ia(n,{received:n.data,code:yn.invalid_enum_value,options:a}),Ri}return Qg(t.data)}get enum(){return this._def.values}}$Oe.create=(s,t)=>new $Oe({values:s,typeName:Oi.ZodNativeEnum,...co(t)});class Oue extends Xo{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ca.promise&&r.common.async===!1)return ia(r,{code:yn.invalid_type,expected:Ca.promise,received:r.parsedType}),Ri;const n=r.parsedType===Ca.promise?r.data:Promise.resolve(r.data);return Qg(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Oue.create=(s,t)=>new Oue({type:s,typeName:Oi.ZodPromise,...co(t)});class xI extends Xo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Oi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,i={addIssue:l=>{ia(n,l),l.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const l=a.transform(n.data,i);if(n.common.async)return Promise.resolve(l).then(async o=>{if(r.value==="aborted")return Ri;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?Ri:c.status==="dirty"||r.value==="dirty"?_R(c.value):c});{if(r.value==="aborted")return Ri;const o=this._def.schema._parseSync({data:l,path:n.path,parent:n});return o.status==="aborted"?Ri:o.status==="dirty"||r.value==="dirty"?_R(o.value):o}}if(a.type==="refinement"){const l=o=>{const c=a.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ri:(o.status==="dirty"&&r.dirty(),l(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Ri:(o.status==="dirty"&&r.dirty(),l(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!mI(l))return Ri;const o=a.transform(l.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>mI(l)?Promise.resolve(a.transform(l.value,i)).then(o=>({status:r.value,value:o})):Ri);el.assertNever(a)}}xI.create=(s,t,r)=>new xI({schema:s,typeName:Oi.ZodEffects,effect:t,...co(r)});xI.createWithPreprocess=(s,t,r)=>new xI({schema:t,effect:{type:"preprocess",transform:s},typeName:Oi.ZodEffects,...co(r)});class i2 extends Xo{_parse(t){return this._getType(t)===Ca.undefined?Qg(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}i2.create=(s,t)=>new i2({innerType:s,typeName:Oi.ZodOptional,...co(t)});class gI extends Xo{_parse(t){return this._getType(t)===Ca.null?Qg(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gI.create=(s,t)=>new gI({innerType:s,typeName:Oi.ZodNullable,...co(t)});class h2e extends Xo{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===Ca.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}h2e.create=(s,t)=>new h2e({innerType:s,typeName:Oi.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...co(t)});class m2e extends Xo{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pue(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new n1(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new n1(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}m2e.create=(s,t)=>new m2e({innerType:s,typeName:Oi.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...co(t)});class UOe extends Xo{_parse(t){if(this._getType(t)!==Ca.nan){const n=this._getOrReturnCtx(t);return ia(n,{code:yn.invalid_type,expected:Ca.nan,received:n.parsedType}),Ri}return{status:"valid",value:t.data}}}UOe.create=s=>new UOe({typeName:Oi.ZodNaN,...co(s)});class k6t extends Xo{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class N3e extends Xo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ri:i.status==="dirty"?(r.dirty(),_R(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ri:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new N3e({in:t,out:r,typeName:Oi.ZodPipeline})}}class f2e extends Xo{_parse(t){const r=this._def.innerType._parse(t),n=a=>(mI(a)&&(a.value=Object.freeze(a.value)),a);return Pue(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}f2e.create=(s,t)=>new f2e({innerType:s,typeName:Oi.ZodReadonly,...co(t)});var Oi;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(Oi||(Oi={}));const oo=Ej.create,KO=fI.create,S6t=c2e.create;k2.create;Qv.create;const M_=yu.create;Due.create;Rue.create;b5.create;const Ng=u2e.create,rtt=pI.create;Oue.create;i2.create;gI.create;const ur=k.forwardRef(({className:s,...t},r)=>e.jsx("textarea",{className:Bt("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}));ur.displayName="Textarea";const C6t=["Excellent","Good","Neutral","Bad","Very Bad"],T6t=[5,4,3,2,1];function E6t({questions:s,visitorId:t,onComplete:r,onSkip:n}){const a=oIt(),[i,l]=k.useState({}),o=s.filter(x=>x.question_type==="rating"),c=s.filter(x=>x.question_type!=="rating"),d=(x,g)=>{l(v=>({...v,[x]:{rating_value:g}}))},h=(x,g)=>{l(v=>({...v,[x]:{text_value:g}}))},m=async()=>{const x=Object.entries(i).filter(([,g])=>g.rating_value!=null||g.text_value&&g.text_value.trim()).map(([g,v])=>{var j;return{visitor_id:t,question_id:g,rating_value:v.rating_value??null,text_value:((j=v.text_value)==null?void 0:j.trim())||null}});if(x.length>0)try{await a.mutateAsync(x)}catch{}r()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),C6t.map(x=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:x})},x))]}),o.map(x=>e.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:x.question_text}),T6t.map(g=>{var v;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(x.id,g),className:`w-6 h-6 rounded-full border-2 transition-all ${((v=i[x.id])==null?void 0:v.rating_value)===g?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},g)})]},x.id))]}),c.map(x=>{var g;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:x.question_text}),e.jsx(ur,{value:((g=i[x.id])==null?void 0:g.text_value)||"",onChange:v=>h(x.id,v.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},x.id)}),e.jsx(G,{onClick:m,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var Ape="Checkbox",[A6t]=yd(Ape),[M6t,k3e]=A6t(Ape);function I6t(s){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:h="on",internal_do_not_use_render:m}=s,[x,g]=Lh({prop:r,defaultProp:a??!1,onChange:c,caller:Ape}),[v,j]=k.useState(null),[b,N]=k.useState(null),S=k.useRef(!1),T=v?!!l||!!v.closest("form"):!0,A={checked:x,disabled:i,setChecked:g,control:v,setControl:j,name:o,form:l,value:h,hasConsumerStoppedPropagationRef:S,required:d,defaultChecked:o2(a)?!1:a,isFormControl:T,bubbleInput:b,setBubbleInput:N};return e.jsx(M6t,{scope:t,...A,children:P6t(m)?m(A):n})}var ntt="CheckboxTrigger",att=k.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:r,...n},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:x,isFormControl:g,bubbleInput:v}=k3e(ntt,s),j=Qa(a,h),b=k.useRef(c);return k.useEffect(()=>{const N=i==null?void 0:i.form;if(N){const S=()=>m(b.current);return N.addEventListener("reset",S),()=>N.removeEventListener("reset",S)}},[i,m]),e.jsx(pn.button,{type:"button",role:"checkbox","aria-checked":o2(c)?"mixed":c,"aria-required":d,"data-state":dtt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...n,ref:j,onKeyDown:Or(t,N=>{N.key==="Enter"&&N.preventDefault()}),onClick:Or(r,N=>{m(S=>o2(S)?!0:!S),v&&g&&(x.current=N.isPropagationStopped(),x.current||N.stopPropagation())})})});att.displayName=ntt;var S3e=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:h,...m}=s;return e.jsx(I6t,{__scopeCheckbox:r,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:n,form:h,value:c,internal_do_not_use_render:({isFormControl:x})=>e.jsxs(e.Fragment,{children:[e.jsx(att,{...m,ref:t,__scopeCheckbox:r}),x&&e.jsx(ctt,{__scopeCheckbox:r})]})})});S3e.displayName=Ape;var itt="CheckboxIndicator",ott=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,forceMount:n,...a}=s,i=k3e(itt,r);return e.jsx(qd,{present:n||o2(i.checked)||i.checked===!0,children:e.jsx(pn.span,{"data-state":dtt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});ott.displayName=itt;var ltt="CheckboxBubbleInput",ctt=k.forwardRef(({__scopeCheckbox:s,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:h,form:m,bubbleInput:x,setBubbleInput:g}=k3e(ltt,s),v=Qa(r,g),j=HB(i),b=MB(n);k.useEffect(()=>{const S=x;if(!S)return;const T=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(T,"checked").set,D=!a.current;if(j!==i&&P){const B=new Event("click",{bubbles:D});S.indeterminate=o2(i),P.call(S,o2(i)?!1:i),S.dispatchEvent(B)}},[x,j,i,a]);const N=k.useRef(o2(i)?!1:i);return e.jsx(pn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??N.current,required:o,disabled:c,name:d,value:h,form:m,...t,tabIndex:-1,ref:v,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});ctt.displayName=ltt;function P6t(s){return typeof s=="function"}function o2(s){return s==="indeterminate"}function dtt(s){return o2(s)?"indeterminate":s?"checked":"unchecked"}const Ei=k.forwardRef(({className:s,...t},r)=>e.jsx(S3e,{ref:r,className:Bt("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(ott,{className:Bt("flex items-center justify-center text-current"),children:e.jsx(Hn,{className:"h-4 w-4"})})}));Ei.displayName=S3e.displayName;const G2=xpe,C3e=e3e,L6t=gpe,utt=k.forwardRef(({className:s,...t},r)=>e.jsx(SP,{className:Bt("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}));utt.displayName=SP.displayName;const D6t=V5("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"}}),I_=k.forwardRef(({side:s="right",className:t,children:r,...n},a)=>e.jsxs(L6t,{children:[e.jsx(utt,{}),e.jsxs(CP,{ref:a,className:Bt(D6t({side:s}),t),...n,children:[r,e.jsxs(VB,{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"})]})]})]}));I_.displayName=CP.displayName;const W2=({className:s,...t})=>e.jsx("div",{className:Bt("flex flex-col space-y-2 text-center sm:text-left",s),...t});W2.displayName="SheetHeader";const K2=k.forwardRef(({className:s,...t},r)=>e.jsx(UB,{ref:r,className:Bt("text-lg font-semibold text-foreground",s),...t}));K2.displayName=UB.displayName;const T3e=k.forwardRef(({className:s,...t},r)=>e.jsx(qB,{ref:r,className:Bt("text-sm text-muted-foreground",s),...t}));T3e.displayName=qB.displayName;function p2e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function R6t({rooms:s}){var m;const[t,r]=k.useState(((m=s[0])==null?void 0:m.id)||""),[n,a]=k.useState(null),i=s.find(x=>x.id===t)||s[0],l=n!==null?i==null?void 0:i.media[n]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(x=>x===null||o===0?x:(x-1+o)%o),h=()=>a(x=>x===null||o===0?x:(x+1)%o);return k.useEffect(()=>{if(n===null)return;const x=g=>{g.key==="Escape"?c():g.key==="ArrowLeft"?d():g.key==="ArrowRight"&&h()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(x=>e.jsxs("button",{onClick:()=>r(x.id),className:Bt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===x.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[x.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:x.media.length})]},x.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((x,g)=>e.jsx("button",{onClick:()=>a(g),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:x.kind==="video"?e.jsxs(e.Fragment,{children:[p2e(x.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:x.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(sn,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:x.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},x.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(n??0)+1," / ",o]}),e.jsx("button",{onClick:x=>{x.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:x=>{x.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(Vo,{className:"h-6 w-6"})}),l.kind==="video"?p2e(l.url)?e.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:x=>x.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:x=>x.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:x=>x.stopPropagation()}),o>1&&e.jsx("button",{onClick:x=>{x.stopPropagation(),h()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx(ya,{className:"h-6 w-6"})})]})]}):null}function O6t({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,h)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:h,total:c.media.length})})});const r=k.useRef(null),[n,a]=k.useState(0);k.useEffect(()=>{const c=r.current;if(!c)return;let d=0;const h=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const m=Math.round(c.scrollLeft/c.clientWidth);a(m)})};return c.addEventListener("scroll",h,{passive:!0}),()=>{c.removeEventListener("scroll",h),cancelAnimationFrame(d)}},[]);const i=c=>{const d=r.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[n])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(m=>m.roomId===c.id),h=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Bt("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",h?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:t.map((c,d)=>e.jsx("div",{className:"shrink-0 w-screen snap-center",children:e.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[c.type==="cover"?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),e.jsx("h3",{className:"text-3xl font-bold",children:c.roomName}),c.description&&e.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:c.description}),e.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[c.mediaCount," ",c.mediaCount===1?"item":"items"," — swipe to view →"]})]}):c.kind==="video"?p2e(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(Vo,{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(ya,{className:"h-4 w-4"})]})]})]})}const _1e={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:bi},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:rn},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:ln},offer:{label:"I'm Interested — Let's Talk",title:"Express interest / make an offer",placeholder:"Tell the agent about your interest or any offer thoughts.",icon:_l}},F6t=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function B6t(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 z6t({openHouse:s,visitorId:t,visitorName:r,visitorEmail:n,visitorPhone:a,previewMode:i=!1}){var Te;const l=s.profiles,o=((Te=l==null?void 0:l.name)==null?void 0:Te.split(" ").map(ye=>ye[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,h]=k.useState(null),[m,x]=k.useState(""),[g,v]=k.useState(n||""),[j,b]=k.useState(a||""),[N,S]=k.useState(!1),[T,A]=k.useState(null),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState(""),[X,K]=k.useState([]),[Q,Y]=k.useState(""),[ne,de]=k.useState(""),[ce,ae]=k.useState(""),[ie,me]=k.useState(""),oe=B6t(s.price),ge=s.tour_mode==="rooms",{data:be=[]}=gIt(ge?s.id:void 0),Oe=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Me=ye=>{h(ye),x(""),D(""),z(""),$(""),K([]),Y(""),de(""),ae(""),me("")},Pe=()=>{h(null)},Ee=ye=>{K(ct=>ct.includes(ye)?ct.filter(ve=>ve!==ye):[...ct,ye])},$e=ye=>ye==="showing"?{preferred_date:P||null,preferred_time:B||null,alternate_date:F||null}:ye==="disclosure"?{requested_documents:X}:ye==="offer"?{offer_amount:Q||null,financing:ne||null,timeline:ce||null,pre_approved:ie||null}:{},Se=d?d==="showing"?!!P:d==="question"?m.trim().length>0:!0:!1,ze=async()=>{if(d){if(i){nn({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{h(null),A(null)},1500);return}S(!0);try{const ye=$e(d),{error:ct}=await H.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:m.trim()||null,email:g.trim()||null,phone:j.trim()||null,visitor_name:r,...ye}});if(ct)throw ct;H.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:g.trim()||null,visitor_phone:j.trim()||null,extras:ye}}).catch(()=>{}),A(d),nn({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Pe(),A(null)},1400)}catch(ye){nn({title:"Something went wrong",description:ye.message,variant:"destructive"})}finally{S(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(ja,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),oe&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:oe}),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(e0,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fp,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx($g,{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(vn,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(ga,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(bn,{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(Nn,{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(Qs,{className:"h-4 w-4"})})]})]}),ge&&be.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(R6t,{rooms:be}),e.jsx(O6t,{rooms:be})]}),Oe.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Oe.map(ye=>{const ct=_1e[ye],ve=ct.icon;return e.jsxs("button",{onClick:()=>Me(ye),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(ve,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:ct.label})]},ye)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(G2,{open:!!d,onOpenChange:ye=>!ye&&Pe(),children:e.jsx(I_,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(W2,{className:"text-left",children:[e.jsx(K2,{children:_1e[d].title}),e.jsxs(T3e,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),T===d?e.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(Mn,{className:"h-7 w-7 text-green-600"})}),e.jsx("p",{className:"font-medium",children:"Message sent!"})]}):e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Email"}),e.jsx(ke,{type:"email",value:g,onChange:ye=>v(ye.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Phone"}),e.jsx(ke,{type:"tel",value:j,onChange:ye=>b(ye.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Preferred date *"}),e.jsx(ke,{type:"date",value:P,onChange:ye=>D(ye.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Preferred time"}),e.jsx(ke,{type:"time",value:B,onChange:ye=>z(ye.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(ke,{type:"date",value:F,onChange:ye=>$(ye.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:F6t.map(ye=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ei,{checked:X.includes(ye),onCheckedChange:()=>Ee(ye)}),e.jsx("span",{children:ye})]},ye))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Estimated offer"}),e.jsx(ke,{value:Q,onChange:ye=>Y(ye.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Financing"}),e.jsxs(zs,{value:ne,onValueChange:de,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"Cash",children:"Cash"}),e.jsx(mt,{value:"Conventional",children:"Conventional"}),e.jsx(mt,{value:"FHA",children:"FHA"}),e.jsx(mt,{value:"VA",children:"VA"}),e.jsx(mt,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Timeline"}),e.jsxs(zs,{value:ce,onValueChange:ae,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"ASAP",children:"ASAP"}),e.jsx(mt,{value:"30 days",children:"30 days"}),e.jsx(mt,{value:"60 days",children:"60 days"}),e.jsx(mt,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(zs,{value:ie,onValueChange:me,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"Yes",children:"Yes"}),e.jsx(mt,{value:"No",children:"No"}),e.jsx(mt,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(ur,{value:m,onChange:ye=>x(ye.target.value),placeholder:_1e[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(G,{onClick:ze,disabled:N||!Se,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:N?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const $6t=M_({first_name:oo().trim().min(1,"First name is required").max(50),last_name:oo().trim().max(50).optional(),email:oo().trim().email("Please enter a valid email").max(255).optional().or(Ng("")),phone:oo().trim().max(20).optional().or(Ng(""))}),U6t=[{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 htt({slug:s}={}){var Se;const t=Xi(),r=s||t.slug,{data:n,isLoading:a,error:i}=nIt(r),l=mIt(),o=fIt(),c=pIt(),d=k.useRef(!1),[h,m]=k.useState("welcome"),[x,g]=k.useState(null),[v,j]=k.useState({first_name:"",last_name:"",email:"",phone:""}),[b,N]=k.useState(""),[S,T]=k.useState(!1),[A,P]=k.useState(!1),[D,B]=k.useState(""),[z,F]=k.useState(""),{data:$,isLoading:X}=iIt(n==null?void 0:n.id),K=!!(n!=null&&n.enable_survey),Q=(n==null?void 0:n.ask_visitor_intent)!==!1;k.useEffect(()=>{if(!r||!(n!=null&&n.id)||d.current)return;const ze=`oh_scan_${n.id}`;if(sessionStorage.getItem(ze)){d.current=!0;return}d.current=!0,sessionStorage.setItem(ze,"1"),c.mutate(r)},[r,n==null?void 0:n.id]),k.useEffect(()=>{h==="pending_survey"&&(X||m(K&&(($==null?void 0:$.length)??0)>0?"survey":"done"))},[h,X,K,$]);const Y=ze=>{if(!ze)return"";const[Te,ye]=ze.split(":"),ct=parseInt(Te),ve=ct>=12?"PM":"AM";return`${ct>12?ct-12:ct||12}:${ye} ${ve}`},ne=async()=>{F("");const ze=$6t.safeParse(v);if(!ze.success){F(ze.error.issues[0].message);return}if(!v.email&&!v.phone){F("Please provide either an email or phone number");return}const Te=(n==null?void 0:n.kind)==="virtual";if(!x&&(n!=null&&n.id))try{const ye=await l.mutateAsync({open_house_id:n.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():void 0,partial_signin:Te?!1:Q});g(ye.id)}catch{if(Te){F("We could not start the virtual tour. Please try again.");return}}if(Te){m(Q?"intent":"done");return}if(!Q){K?!X&&$&&$.length>0?m("survey"):m("pending_survey"):m("done");return}m("intent")},de=async ze=>{N(ze);try{let Te=x;if(Te?await o.mutateAsync({visitor_id:Te,visitor_intent:ze,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():null,partial_signin:!1}):(Te=(await l.mutateAsync({open_house_id:n.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_intent:ze,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():void 0,partial_signin:!1})).id,g(Te)),(n==null?void 0:n.kind)==="virtual"){m("done");return}K?!X&&$&&$.length>0?m("survey"):m("pending_survey"):m("done")}catch{F("Something went wrong. Please try again.")}};if(a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(i||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Cn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const ce=n.profiles,ae=((Se=ce==null?void 0:ce.name)==null?void 0:Se.split(" ").map(ze=>ze[0]).join("").slice(0,2))||"?",ie=n.event_type==="community",me=n.kind==="virtual",oe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(me&&(oe||h==="done"))return!oe&&!x?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsxs("title",{children:["Virtual Tour | ",n.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${n.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),oe&&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(z6t,{openHouse:n,visitorId:oe?"preview":x,visitorName:oe?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:oe?"":v.email,visitorPhone:oe?"":v.phone,previewMode:oe})]});const be=`${me?"Virtual Open House":ie?"Community Event":"Open House"} — ${n.property_address}`,Me=[[n.city,n.state].filter(Boolean).join(", "),n.event_date?Ss(new Date(n.event_date+"T00:00:00"),"EEE, MMM d"):null,ce!=null&&ce.name?`Hosted by ${ce.name}`:null].filter(Boolean).join(" · "),Pe=n.photo_url||"",Ee=Pe&&Pe.includes("/storage/v1/object/public/")?Pe.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Pe||"https://dashboard.relevelup.com/og-image.png",$e=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsx("title",{children:be}),e.jsx("meta",{name:"description",content:Me||`Sign in to ${n.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:be}),e.jsx("meta",{property:"og:description",content:Me||`Sign in to ${n.property_address}`}),e.jsx("meta",{property:"og:image",content:Ee}),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:$e}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:be}),e.jsx("meta",{name:"twitter:description",content:Me||`Sign in to ${n.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ee}),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(vn,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(ga,{src:(ce==null?void 0:ce.avatar_url)||"",alt:(ce==null?void 0:ce.name)||""}),e.jsx(bn,{className:"bg-white/10 text-white text-lg",children:ae})]}),e.jsx("p",{className:"text-white/60 text-sm",children:ce==null?void 0:ce.name}),(ce==null?void 0:ce.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:ce.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[n.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:n.photo_url,alt:n.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Y(n.start_time),n.end_time?` – ${Y(n.end_time)}`:""]})]})]})]})]}),!n.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:ie?e.jsx(Sa,{className:"h-5 w-5 text-white"}):e.jsx(Cn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Y(n.start_time),n.end_time?` – ${Y(n.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[h==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:n.agent_greeting||"Please sign in below."})]}),e.jsxs(G,{onClick:()=>m("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Ga,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),h==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>m("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(wa,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(ke,{value:v.first_name,onChange:ze=>j(Te=>({...Te,first_name:ze.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(ke,{value:v.last_name,onChange:ze=>j(Te=>({...Te,last_name:ze.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(ke,{type:"email",value:v.email,onChange:ze=>j(Te=>({...Te,email:ze.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(ke,{type:"tel",value:v.phone,onChange:ze=>j(Te=>({...Te,phone:ze.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:S,onChange:ze=>T(ze.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:A?"Yes":"No"}),e.jsx(br,{checked:A,onCheckedChange:P})]})]}),A&&e.jsx(ke,{value:D,onChange:ze=>B(ze.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),z&&e.jsx("p",{className:"text-destructive text-sm",children:z}),e.jsxs(G,{onClick:ne,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Ga,{className:"h-5 w-5 ml-2"})]})]}),h==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>m("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(wa,{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:U6t.map(ze=>e.jsxs("button",{onClick:()=>de(ze.value),disabled:l.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:ze.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:ze.label})]},ze.value))}),z&&e.jsx("p",{className:"text-destructive text-sm text-center",children:z})]}),h==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),h==="survey"&&x&&$&&e.jsx(E6t,{questions:$,visitorId:x,onComplete:()=>m("done"),onSkip:()=>m("done")}),h==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(Mn,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",v.first_name,". ",ie?"Enjoy the event!":"Enjoy the open house!"]})]}),(n==null?void 0:n.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(n.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(ln,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(ce==null?void 0:ce.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:ce.name})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"})]})})]})}function WUs(s){const{user:t}=As();return gt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:r,error:n}=await H.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 KUs(){const s=es(),{user:t}=As();return Lt({mutationFn:async({openHouseId:r,label:n})=>{const{data:a,error:i}=await H.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 YUs(){const s=es();return Lt({mutationFn:async({id:t,openHouseId:r})=>{const{error:n}=await H.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 q6t(s){return gt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:r}=await H.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 E3e="ScrollArea",[mtt]=yd(E3e),[H6t,Jg]=mtt(E3e),ftt=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(null),[N,S]=k.useState(0),[T,A]=k.useState(0),[P,D]=k.useState(!1),[B,z]=k.useState(!1),F=Qa(t,X=>c(X)),$=$2(a);return e.jsx(H6t,{scope:r,type:n,dir:$,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:h,content:m,onContentChange:x,scrollbarX:g,onScrollbarXChange:v,scrollbarXEnabled:P,onScrollbarXEnabledChange:D,scrollbarY:j,onScrollbarYChange:b,scrollbarYEnabled:B,onScrollbarYEnabledChange:z,onCornerWidthChange:S,onCornerHeightChange:A,children:e.jsx(pn.div,{dir:$,...l,ref:F,style:{position:"relative","--radix-scroll-area-corner-width":N+"px","--radix-scroll-area-corner-height":T+"px",...s.style}})})});ftt.displayName=E3e;var ptt="ScrollAreaViewport",xtt=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,children:n,nonce:a,...i}=s,l=Jg(ptt,r),o=k.useRef(null),c=Qa(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(pn.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})})]})});xtt.displayName=ptt;var y1="ScrollAreaScrollbar",A3e=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=Jg(y1,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(G6t,{...n,ref:t,forceMount:r}):a.type==="scroll"?e.jsx(W6t,{...n,ref:t,forceMount:r}):a.type==="auto"?e.jsx(gtt,{...n,ref:t,forceMount:r}):a.type==="always"?e.jsx(M3e,{...n,ref:t,"data-state":"visible"}):null});A3e.displayName=y1;var G6t=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=Jg(y1,s.__scopeScrollArea),[i,l]=k.useState(!1);return k.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},h=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",h)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(qd,{present:r||i,children:e.jsx(gtt,{"data-state":i?"visible":"hidden",...n,ref:t})})}),W6t=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=Jg(y1,s.__scopeScrollArea),i=s.orientation==="horizontal",l=Ipe(()=>c("SCROLL_END"),100),[o,c]=V6t("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return k.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),k.useEffect(()=>{const d=a.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const x=()=>{const g=d[h];m!==g&&(c("SCROLL"),l()),m=g};return d.addEventListener("scroll",x),()=>d.removeEventListener("scroll",x)}},[a.viewport,i,c,l]),e.jsx(qd,{present:r||o!=="hidden",children:e.jsx(M3e,{"data-state":o==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:Or(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Or(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),gtt=k.forwardRef((s,t)=>{const r=Jg(y1,s.__scopeScrollArea),{forceMount:n,...a}=s,[i,l]=k.useState(!1),o=s.orientation==="horizontal",c=Ipe(()=>{if(r.viewport){const d=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=s,a=Jg(y1,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=wtt(o.viewport,o.content),h={...n,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:x=>i.current=x,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:x=>l.current=x};function m(x,g){return J6t(x,l.current,o,g)}return r==="horizontal"?e.jsx(K6t,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const x=a.viewport.scrollLeft,g=qOe(x,o,a.dir);i.current.style.transform=`translate3d(${g}px, 0, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollLeft=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollLeft=m(x,a.dir))}}):r==="vertical"?e.jsx(Y6t,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const x=a.viewport.scrollTop,g=qOe(x,o);i.current.style.transform=`translate3d(0, ${g}px, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollTop=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollTop=m(x))}}):null}),K6t=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=Jg(y1,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=Qa(t,c,i.onScrollbarXChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(vtt,{"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":Mpe(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.x),onDragScroll:h=>s.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const x=i.viewport.scrollLeft+h.deltaX;s.onWheelScroll(x),Ntt(x,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Bue(l.paddingLeft),paddingEnd:Bue(l.paddingRight)}})}})}),Y6t=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=Jg(y1,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=Qa(t,c,i.onScrollbarYChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(vtt,{"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":Mpe(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.y),onDragScroll:h=>s.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const x=i.viewport.scrollTop+h.deltaY;s.onWheelScroll(x),Ntt(x,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Bue(l.paddingTop),paddingEnd:Bue(l.paddingBottom)}})}})}),[Z6t,ytt]=mtt(y1),vtt=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:m,...x}=s,g=Jg(y1,r),[v,j]=k.useState(null),b=Qa(t,F=>j(F)),N=k.useRef(null),S=k.useRef(""),T=g.viewport,A=n.content-n.viewport,P=Ld(h),D=Ld(c),B=Ipe(m,10);function z(F){if(N.current){const $=F.clientX-N.current.left,X=F.clientY-N.current.top;d({x:$,y:X})}}return k.useEffect(()=>{const F=$=>{const X=$.target;(v==null?void 0:v.contains(X))&&P($,A)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[T,v,A,P]),k.useEffect(D,[n,D]),yI(v,B),yI(g.content,B),e.jsx(Z6t,{scope:r,scrollbar:v,hasThumb:a,onThumbChange:Ld(i),onThumbPointerUp:Ld(l),onThumbPositionChange:D,onThumbPointerDown:Ld(o),children:e.jsx(pn.div,{...x,ref:b,style:{position:"absolute",...x.style},onPointerDown:Or(s.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),N.current=v.getBoundingClientRect(),S.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",g.viewport&&(g.viewport.style.scrollBehavior="auto"),z(F))}),onPointerMove:Or(s.onPointerMove,z),onPointerUp:Or(s.onPointerUp,F=>{const $=F.target;$.hasPointerCapture(F.pointerId)&&$.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=S.current,g.viewport&&(g.viewport.style.scrollBehavior=""),N.current=null})})})}),Fue="ScrollAreaThumb",btt=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=ytt(Fue,s.__scopeScrollArea);return e.jsx(qd,{present:r||a.hasThumb,children:e.jsx(X6t,{ref:t,...n})})}),X6t=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,style:n,...a}=s,i=Jg(Fue,r),l=ytt(Fue,r),{onThumbPositionChange:o}=l,c=Qa(t,m=>l.onThumbChange(m)),d=k.useRef(void 0),h=Ipe(()=>{d.current&&(d.current(),d.current=void 0)},100);return k.useEffect(()=>{const m=i.viewport;if(m){const x=()=>{if(h(),!d.current){const g=eDt(m,o);d.current=g,o()}};return o(),m.addEventListener("scroll",x),()=>m.removeEventListener("scroll",x)}},[i.viewport,h,o]),e.jsx(pn.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:Or(s.onPointerDownCapture,m=>{const g=m.target.getBoundingClientRect(),v=m.clientX-g.left,j=m.clientY-g.top;l.onThumbPointerDown({x:v,y:j})}),onPointerUp:Or(s.onPointerUp,l.onThumbPointerUp)})});btt.displayName=Fue;var I3e="ScrollAreaCorner",_tt=k.forwardRef((s,t)=>{const r=Jg(I3e,s.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?e.jsx(Q6t,{...s,ref:t}):null});_tt.displayName=I3e;var Q6t=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,...n}=s,a=Jg(I3e,r),[i,l]=k.useState(0),[o,c]=k.useState(0),d=!!(i&&o);return yI(a.scrollbarX,()=>{var m;const h=((m=a.scrollbarX)==null?void 0:m.offsetHeight)||0;a.onCornerHeightChange(h),c(h)}),yI(a.scrollbarY,()=>{var m;const h=((m=a.scrollbarY)==null?void 0:m.offsetWidth)||0;a.onCornerWidthChange(h),l(h)}),d?e.jsx(pn.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 Bue(s){return s?parseInt(s,10):0}function wtt(s,t){const r=s/t;return isNaN(r)?0:r}function Mpe(s){const t=wtt(s.viewport,s.content),r=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,n=(s.scrollbar.size-r)*t;return Math.max(n,18)}function J6t(s,t,r,n="ltr"){const a=Mpe(r),i=a/2,l=t||i,o=a-l,c=r.scrollbar.paddingStart+l,d=r.scrollbar.size-r.scrollbar.paddingEnd-o,h=r.content-r.viewport,m=n==="ltr"?[0,h]:[h*-1,0];return jtt([c,d],m)(s)}function qOe(s,t,r="ltr"){const n=Mpe(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=tF(s,c);return jtt([0,l],[0,o])(d)}function jtt(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 Ntt(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 Ipe(s,t){const r=Ld(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 yI(s,t){const r=Ld(t);fd(()=>{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 ktt=ftt,tDt=xtt,sDt=_tt;const ti=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(ktt,{ref:n,className:Bt("relative overflow-hidden",s),...r,children:[e.jsx(tDt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Ppe,{}),e.jsx(sDt,{})]}));ti.displayName=ktt.displayName;const Ppe=k.forwardRef(({className:s,orientation:t="vertical",...r},n)=>e.jsx(A3e,{ref:n,orientation:t,className:Bt("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(btt,{className:"relative flex-1 rounded-full bg-border"})}));Ppe.displayName=A3e.displayName;const P3e=k.createContext({});function L3e(s){const t=k.useRef(null);return t.current===null&&(t.current=s()),t.current}const rDt=typeof window<"u",Stt=rDt?k.useLayoutEffect:k.useEffect,Lpe=k.createContext(null);function D3e(s,t){s.indexOf(t)===-1&&s.push(t)}function zue(s,t){const r=s.indexOf(t);r>-1&&s.splice(r,1)}const a1=(s,t,r)=>r>t?t:r{};const S2={},Ctt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s),Ttt=s=>typeof s=="object"&&s!==null,Ett=s=>/^0[^.\s]+$/u.test(s);function Att(s){let t;return()=>(t===void 0&&(t=s()),t)}const qg=s=>s,WB=(...s)=>s.reduce((t,r)=>n=>r(t(n))),nF=(s,t,r)=>{const n=t-s;return n?(r-s)/n:1};class O3e{constructor(){this.subscriptions=[]}add(t){return D3e(this.subscriptions,t),()=>zue(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,Dg=s=>s/1e3,Mtt=(s,t)=>t?s*(1e3/t):0,Itt=(s,t,r)=>(((1-3*r+3*t)*s+(3*r-6*t))*s+3*t)*s,nDt=1e-7,aDt=12;function iDt(s,t,r,n,a){let i,l,o=0;do l=t+(r-t)/2,i=Itt(l,n,a)-s,i>0?r=l:t=l;while(Math.abs(i)>nDt&&++oiDt(i,0,1,s,r);return i=>i===0||i===1?i:Itt(a(i),t,n)}const Ptt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,Ltt=s=>t=>1-s(1-t),Dtt=KB(.33,1.53,.69,.99),F3e=Ltt(Dtt),Rtt=Ptt(F3e),Ott=s=>s>=1?1:(s*=2)<1?.5*F3e(s):.5*(2-Math.pow(2,-10*(s-1))),B3e=s=>1-Math.sin(Math.acos(s)),Ftt=Ltt(B3e),Btt=Ptt(B3e),oDt=KB(.42,0,1,1),lDt=KB(0,0,.58,1),ztt=KB(.42,0,.58,1),cDt=s=>Array.isArray(s)&&typeof s[0]!="number",$tt=s=>Array.isArray(s)&&typeof s[0]=="number",dDt={linear:qg,easeIn:oDt,easeInOut:ztt,easeOut:lDt,circIn:B3e,circInOut:Btt,circOut:Ftt,backIn:F3e,backInOut:Rtt,backOut:Dtt,anticipate:Ott},uDt=s=>typeof s=="string",VOe=s=>{if($tt(s)){R3e(s.length===4);const[t,r,n,a]=s;return KB(t,r,n,a)}else if(uDt(s))return dDt[s];return s},tU=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function hDt(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};function c(h){l.has(h)&&(d.schedule(h),s()),h(o)}const d={schedule:(h,m=!1,x=!1)=>{const v=x&&a?r:n;return m&&l.add(h),v.add(h),h},cancel:h=>{n.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const m=r;r=n,n=m,r.forEach(c),r.clear(),a=!1,i&&(i=!1,d.process(h))}};return d}const mDt=40;function Utt(s,t){let r=!1,n=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>r=!0,l=tU.reduce((T,A)=>(T[A]=hDt(i),T),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:h,update:m,preRender:x,render:g,postRender:v}=l,j=()=>{const T=S2.useManualTiming,A=T?a.timestamp:performance.now();r=!1,T||(a.delta=n?1e3/60:Math.max(Math.min(A-a.timestamp,mDt),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),h.process(a),m.process(a),x.process(a),g.process(a),v.process(a),a.isProcessing=!1,r&&t&&(n=!1,s(j))},b=()=>{r=!0,n=!0,a.isProcessing||s(j)};return{schedule:tU.reduce((T,A)=>{const P=l[A];return T[A]=(D,B=!1,z=!1)=>(r||b(),P.schedule(D,B,z)),T},{}),cancel:T=>{for(let A=0;A(pde===void 0&&xf.set(Kh.isProcessing||S2.useManualTiming?Kh.timestamp:performance.now()),pde),set:s=>{pde=s,queueMicrotask(fDt)}},qtt=s=>t=>typeof t=="string"&&t.startsWith(s),Vtt=qtt("--"),pDt=qtt("var(--"),z3e=s=>pDt(s)?xDt.test(s.split("/*")[0].trim()):!1,xDt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function HOe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const TP={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},aF={...TP,transform:s=>a1(0,1,s)},sU={...TP,default:1},YO=s=>Math.round(s*1e5)/1e5,$3e=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function gDt(s){return s==null}const yDt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,U3e=(s,t)=>r=>!!(typeof r=="string"&&yDt.test(r)&&r.startsWith(s)||t&&!gDt(r)&&Object.prototype.hasOwnProperty.call(r,t)),Htt=(s,t,r)=>n=>{if(typeof n!="string")return n;const[a,i,l,o]=n.match($3e);return{[s]:parseFloat(a),[t]:parseFloat(i),[r]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},vDt=s=>a1(0,255,s),j1e={...TP,transform:s=>Math.round(vDt(s))},V4={test:U3e("rgb","red"),parse:Htt("red","green","blue"),transform:({red:s,green:t,blue:r,alpha:n=1})=>"rgba("+j1e.transform(s)+", "+j1e.transform(t)+", "+j1e.transform(r)+", "+YO(aF.transform(n))+")"};function bDt(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 x2e={test:U3e("#"),parse:bDt,transform:V4.transform},YB=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),bb=YB("deg"),Jv=YB("%"),va=YB("px"),_Dt=YB("vh"),wDt=YB("vw"),GOe={...Jv,parse:s=>Jv.parse(s)/100,transform:s=>Jv.transform(s*100)},AA={test:U3e("hsl","hue"),parse:Htt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:r,alpha:n=1})=>"hsla("+Math.round(s)+", "+Jv.transform(YO(t))+", "+Jv.transform(YO(r))+", "+YO(aF.transform(n))+")"},vu={test:s=>V4.test(s)||x2e.test(s)||AA.test(s),parse:s=>V4.test(s)?V4.parse(s):AA.test(s)?AA.parse(s):x2e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?V4.transform(s):AA.transform(s),getAnimatableNone:s=>{const t=vu.parse(s);return t.alpha=0,vu.transform(t)}},jDt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function NDt(s){var t,r;return isNaN(s)&&typeof s=="string"&&(((t=s.match($3e))==null?void 0:t.length)||0)+(((r=s.match(jDt))==null?void 0:r.length)||0)>0}const Gtt="number",Wtt="color",kDt="var",SDt="var(",WOe="${}",CDt=/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 vI(s){const t=s.toString(),r=[],n={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(CDt,c=>(vu.test(c)?(n.color.push(i),a.push(Wtt),r.push(vu.parse(c))):c.startsWith(SDt)?(n.var.push(i),a.push(kDt),r.push(c)):(n.number.push(i),a.push(Gtt),r.push(parseFloat(c))),++i,WOe)).split(WOe);return{values:r,split:o,indexes:n,types:a}}function TDt(s){return vI(s).values}function Ktt({split:s,types:t}){const r=s.length;return n=>{let a="";for(let i=0;itypeof s=="number"?0:vu.test(s)?vu.getAnimatableNone(s):s,MDt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:ADt(s);function IDt(s){const t=vI(s);return Ktt(t)(t.values.map((n,a)=>MDt(n,t.split[a])))}const o0={test:NDt,parse:TDt,createTransformer:EDt,getAnimatableNone:IDt};function N1e(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 PDt({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=N1e(c,o,s+1/3),i=N1e(c,o,s),l=N1e(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:n}}function $ue(s,t){return r=>r>0?t:s}const Yl=(s,t,r)=>s+(t-s)*r,k1e=(s,t,r)=>{const n=s*s,a=r*(t*t-n)+n;return a<0?0:Math.sqrt(a)},LDt=[x2e,V4,AA],DDt=s=>LDt.find(t=>t.test(s));function KOe(s){const t=DDt(s);if(!t)return!1;let r=t.parse(s);return t===AA&&(r=PDt(r)),r}const YOe=(s,t)=>{const r=KOe(s),n=KOe(t);if(!r||!n)return $ue(s,t);const a={...r};return i=>(a.red=k1e(r.red,n.red,i),a.green=k1e(r.green,n.green,i),a.blue=k1e(r.blue,n.blue,i),a.alpha=Yl(r.alpha,n.alpha,i),V4.transform(a))},g2e=new Set(["none","hidden"]);function RDt(s,t){return g2e.has(s)?r=>r<=0?s:t:r=>r>=1?t:s}function ODt(s,t){return r=>Yl(s,t,r)}function q3e(s){return typeof s=="number"?ODt:typeof s=="string"?z3e(s)?$ue:vu.test(s)?YOe:zDt:Array.isArray(s)?Ytt:typeof s=="object"?vu.test(s)?YOe:FDt:$ue}function Ytt(s,t){const r=[...s],n=r.length,a=s.map((i,l)=>q3e(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in n)r[i]=n[i](a);return r}}function BDt(s,t){const r=[],n={color:0,var:0,number:0};for(let a=0;a{const r=o0.createTransformer(t),n=vI(s),a=vI(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?g2e.has(s)&&!a.values.length||g2e.has(t)&&!n.values.length?RDt(s,t):WB(Ytt(BDt(n,a),a.values),r):$ue(s,t)};function Ztt(s,t,r){return typeof s=="number"&&typeof t=="number"&&typeof r=="number"?Yl(s,t,r):q3e(s)(s,t)}const $Dt=s=>{const t=({timestamp:r})=>s(r);return{start:(r=!0)=>Ql.update(t,r),stop:()=>C2(t),now:()=>Kh.isProcessing?Kh.timestamp:xf.now()}},Xtt=(s,t,r=10)=>{let n="";const a=Math.max(Math.round(t/r),2);for(let i=0;i=Uue?1/0:t}function UDt(s,t=100,r){const n=r({...s,keyframes:[0,t]}),a=Math.min(V3e(n),Uue);return{type:"keyframes",ease:i=>n.next(a*i).value/t,duration:Dg(a)}}const Td={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 y2e(s,t){return s*Math.sqrt(1-t*t)}const qDt=12;function VDt(s,t,r){let n=r;for(let a=1;a{const h=d*l,m=h*s,x=h-r,g=y2e(d,l),v=Math.exp(-m);return S1e-x/g*v},i=d=>{const m=d*l*s,x=m*r+r,g=Math.pow(l,2)*Math.pow(d,2)*s,v=Math.exp(-m),j=y2e(Math.pow(d,2),l);return(-a(d)+S1e>0?-1:1)*((x-g)*v)/j}):(a=d=>{const h=Math.exp(-d*s),m=(d-r)*s+1;return-S1e+h*m},i=d=>{const h=Math.exp(-d*s),m=(r-d)*(s*s);return h*m});const o=5/s,c=VDt(a,i,o);if(s=vx(s),isNaN(c))return{stiffness:Td.stiffness,damping:Td.damping,duration:s};{const d=Math.pow(c,2)*n;return{stiffness:d,damping:l*2*Math.sqrt(n*d),duration:s}}}const GDt=["duration","bounce"],WDt=["stiffness","damping","mass"];function ZOe(s,t){return t.some(r=>s[r]!==void 0)}function KDt(s){let t={velocity:Td.velocity,stiffness:Td.stiffness,damping:Td.damping,mass:Td.mass,isResolvedFromDuration:!1,...s};if(!ZOe(s,WDt)&&ZOe(s,GDt))if(t.velocity=0,s.visualDuration){const r=s.visualDuration,n=2*Math.PI/(r*1.2),a=n*n,i=2*a1(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Td.mass,stiffness:a,damping:i}}else{const r=HDt({...s,velocity:0});t={...t,...r,mass:Td.mass},t.isResolvedFromDuration=!0}return t}function que(s=Td.visualDuration,t=Td.bounce){const r=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:n,restDelta:a}=r;const i=r.keyframes[0],l=r.keyframes[r.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:h,duration:m,velocity:x,isResolvedFromDuration:g}=KDt({...r,velocity:-Dg(r.velocity||0)}),v=x||0,j=d/(2*Math.sqrt(c*h)),b=l-i,N=Dg(Math.sqrt(c/h)),S=Math.abs(b)<5;n||(n=S?Td.restSpeed.granular:Td.restSpeed.default),a||(a=S?Td.restDelta.granular:Td.restDelta.default);let T,A,P,D,B,z;if(j<1)P=y2e(N,j),D=(v+j*N*b)/P,T=$=>{const X=Math.exp(-j*N*$);return l-X*(D*Math.sin(P*$)+b*Math.cos(P*$))},B=j*N*D+b*P,z=j*N*b-D*P,A=$=>Math.exp(-j*N*$)*(B*Math.sin(P*$)+z*Math.cos(P*$));else if(j===1){T=X=>l-Math.exp(-N*X)*(b+(v+N*b)*X);const $=v+N*b;A=X=>Math.exp(-N*X)*(N*$*X-v)}else{const $=N*Math.sqrt(j*j-1);T=Y=>{const ne=Math.exp(-j*N*Y),de=Math.min($*Y,300);return l-ne*((v+j*N*b)*Math.sinh(de)+$*b*Math.cosh(de))/$};const X=(v+j*N*b)/$,K=j*N*X-b*$,Q=j*N*b-X*$;A=Y=>{const ne=Math.exp(-j*N*Y),de=Math.min($*Y,300);return ne*(K*Math.sinh(de)+Q*Math.cosh(de))}}const F={calculatedDuration:g&&m||null,velocity:$=>vx(A($)),next:$=>{if(!g&&j<1){const K=Math.exp(-j*N*$),Q=Math.sin(P*$),Y=Math.cos(P*$),ne=l-K*(D*Q+b*Y),de=vx(K*(B*Q+z*Y));return o.done=Math.abs(de)<=n&&Math.abs(l-ne)<=a,o.value=o.done?l:ne,o}const X=T($);if(g)o.done=$>=m;else{const K=vx(A($));o.done=Math.abs(K)<=n&&Math.abs(l-X)<=a}return o.value=o.done?l:X,o},toString:()=>{const $=Math.min(V3e(F),Uue),X=Xtt(K=>F.next($*K).value,$,30);return $+"ms "+X},toTransition:()=>{}};return F}que.applyToOptions=s=>{const t=UDt(s,100,que);return s.ease=t.ease,s.duration=vx(t.duration),s.type="keyframes",s};const YDt=5;function Qtt(s,t,r){const n=Math.max(t-YDt,0);return Mtt(r-s(n),t-n)}function v2e({keyframes:s,velocity:t=0,power:r=.8,timeConstant:n=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:h}){const m=s[0],x={done:!1,value:m},g=z=>o!==void 0&&zc,v=z=>o===void 0?c:c===void 0||Math.abs(o-z)-j*Math.exp(-z/n),T=z=>N+S(z),A=z=>{const F=S(z),$=T(z);x.done=Math.abs(F)<=d,x.value=x.done?N:$};let P,D;const B=z=>{g(x.value)&&(P=z,D=que({keyframes:[x.value,v(x.value)],velocity:Qtt(T,z,x.value),damping:a,stiffness:i,restDelta:d,restSpeed:h}))};return B(0),{calculatedDuration:null,next:z=>{let F=!1;return!D&&P===void 0&&(F=!0,A(z),B(z)),P!==void 0&&z>=P?D.next(z-P):(!F&&A(z),x)}}}function ZDt(s,t,r){const n=[],a=r||S2.mix||Ztt,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=ZDt(t,n,a),c=o.length,d=h=>{if(l&&h1)for(;md(a1(s[0],s[i-1],h)):d}function QDt(s,t){const r=s[s.length-1];for(let n=1;n<=t;n++){const a=nF(0,t,n);s.push(Yl(r,1,a))}}function JDt(s){const t=[0];return QDt(t,s.length-1),t}function eRt(s,t){return s.map(r=>r*t)}function tRt(s,t){return s.map(()=>t||ztt).splice(0,s.length-1)}function ZO({duration:s=300,keyframes:t,times:r,ease:n="easeInOut"}){const a=cDt(n)?n.map(VOe):VOe(n),i={done:!1,value:t[0]},l=eRt(r&&r.length===t.length?r:JDt(t),s),o=XDt(l,t,{ease:Array.isArray(a)?a:tRt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const sRt=s=>s!==null;function Dpe(s,{repeat:t,repeatType:r="loop"},n,a=1){const i=s.filter(sRt),o=a<0||t&&r!=="loop"&&t%2===1?0:i.length-1;return!o||n===void 0?i[o]:n}const rRt={decay:v2e,inertia:v2e,tween:ZO,keyframes:ZO,spring:que};function Jtt(s){typeof s.type=="string"&&(s.type=rRt[s.type])}class H3e{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 nRt=s=>s/100;class Vue extends H3e{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!==xf.now()&&this.tick(xf.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;Jtt(t);const{type:r=ZO,repeat:n=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=r||ZO;c!==ZO&&typeof o[0]!="number"&&(this.mixKeyframes=WB(nRt,Ztt(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=V3e(d));const{calculatedDuration:h}=d;this.calculatedDuration=h,this.resolvedDuration=h+a,this.totalDuration=this.resolvedDuration*(n+1)-a,this.generator=d}updateTime(t){const r=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(t,r=!1){const{generator:n,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return n.next(0);const{delay:d=0,keyframes:h,repeat:m,repeatType:x,repeatDelay:g,type:v,onUpdate:j,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),r?this.currentTime=t:this.updateTime(t);const N=this.currentTime-d*(this.playbackSpeed>=0?1:-1),S=this.playbackSpeed>=0?N<0:N>a;this.currentTime=Math.max(N,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let T=this.currentTime,A=n;if(m){const z=Math.min(this.currentTime,a)/o;let F=Math.floor(z),$=z%1;!$&&z>=1&&($=1),$===1&&F--,F=Math.min(F,m+1),!!(F%2)&&(x==="reverse"?($=1-$,g&&($-=g/o)):x==="mirror"&&(A=l)),T=a1(0,1,$)*o}let P;S?(this.delayState.value=h[0],P=this.delayState):P=A.next(T),i&&!S&&(P.value=i(P.value));let{done:D}=P;!S&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const B=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return B&&v!==v2e&&(P.value=Dpe(h,this.options,b,this.speed)),j&&j(P.value),B&&this.finish(),P}then(t,r){return this.finished.then(t,r)}get duration(){return Dg(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Dg(t)}get time(){return Dg(this.currentTime)}set time(t){t=vx(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 Qtt(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(xf.now()),this.playbackSpeed=t,r&&this.driver&&(this.time=Dg(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=$Dt,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(xf.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 aRt(s){for(let t=1;ts*180/Math.PI,b2e=s=>{const t=H4(Math.atan2(s[1],s[0]));return _2e(t)},iRt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:b2e,rotateZ:b2e,skewX:s=>H4(Math.atan(s[1])),skewY:s=>H4(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},_2e=s=>(s=s%360,s<0&&(s+=360),s),XOe=b2e,QOe=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),JOe=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),oRt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:QOe,scaleY:JOe,scale:s=>(QOe(s)+JOe(s))/2,rotateX:s=>_2e(H4(Math.atan2(s[6],s[5]))),rotateY:s=>_2e(H4(Math.atan2(-s[2],s[0]))),rotateZ:XOe,rotate:XOe,skewX:s=>H4(Math.atan(s[4])),skewY:s=>H4(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function w2e(s){return s.includes("scale")?1:0}function j2e(s,t){if(!s||s==="none")return w2e(t);const r=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,a;if(r)n=oRt,a=r;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=iRt,a=o}if(!a)return w2e(t);const i=n[t],l=a[1].split(",").map(cRt);return typeof i=="function"?i(l):l[i]}const lRt=(s,t)=>{const{transform:r="none"}=getComputedStyle(s);return j2e(r,t)};function cRt(s){return parseFloat(s.trim())}const EP=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],AP=new Set([...EP,"pathRotation"]),e8e=s=>s===TP||s===va,dRt=new Set(["x","y","z"]),uRt=EP.filter(s=>!dRt.has(s));function hRt(s){const t=[];return uRt.forEach(r=>{const n=s.getValue(r);n!==void 0&&(t.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),t}const Aj={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})=>j2e(t,"x"),y:(s,{transform:t})=>j2e(t,"y")};Aj.translateX=Aj.x;Aj.translateY=Aj.y;const K3=new Set;let N2e=!1,k2e=!1,S2e=!1;function est(){if(k2e){const s=Array.from(K3).filter(n=>n.needsMeasurement),t=new Set(s.map(n=>n.element)),r=new Map;t.forEach(n=>{const a=hRt(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)})}k2e=!1,N2e=!1,K3.forEach(s=>s.complete(S2e)),K3.clear()}function tst(){K3.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(k2e=!0)})}function mRt(){S2e=!0,tst(),est(),S2e=!1}class G3e{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?(K3.add(this),N2e||(N2e=!0,Ql.read(tst),Ql.resolveKeyframes(est))):(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])}aRt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),K3.delete(this)}cancel(){this.state==="scheduled"&&(K3.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const fRt=s=>s.startsWith("--");function sst(s,t,r){fRt(t)?s.style.setProperty(t,r):s.style[t]=r}const pRt={};function rst(s,t){const r=Att(s);return()=>pRt[t]??r()}const xRt=rst(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),nst=rst(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),wR=([s,t,r,n])=>`cubic-bezier(${s}, ${t}, ${r}, ${n})`,t8e={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:wR([0,.65,.55,1]),circOut:wR([.55,0,1,.45]),backIn:wR([.31,.01,.66,-.59]),backOut:wR([.33,1.53,.69,.99])};function ast(s,t){if(s)return typeof s=="function"?nst()?Xtt(s,t):"ease-out":$tt(s)?wR(s):Array.isArray(s)?s.map(r=>ast(r,t)||t8e.easeOut):t8e[s]}function gRt(s,t,r,{delay:n=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const h={[t]:r};c&&(h.offset=c);const m=ast(o,a);Array.isArray(m)&&(h.easing=m);const x={delay:n,duration:a,easing:Array.isArray(m)?"linear":m,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),s.animate(h,x)}function ist(s){return typeof s=="function"&&"applyToOptions"in s}function yRt({type:s,...t}){return ist(s)&&nst()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class ost extends H3e{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,R3e(typeof t.type!="string");const d=yRt(t);this.animation=gRt(r,n,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const h=Dpe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(h),sst(r,n,h),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,r;(r=(t=this.animation).finish)==null||r.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var r,n,a;const t=(r=this.options)==null?void 0:r.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(n=this.animation).commitStyles)==null||a.call(n))}get duration(){var r,n;const t=((n=(r=this.animation.effect)==null?void 0:r.getComputedTiming)==null?void 0:n.call(r).duration)||0;return Dg(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Dg(t)}get time(){return Dg(Number(this.animation.currentTime)||0)}set time(t){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=vx(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&&xRt()?(this.animation.timeline=t,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),qg):a(this)}}const lst={anticipate:Ott,backInOut:Rtt,circInOut:Btt};function vRt(s){return s in lst}function bRt(s){typeof s.ease=="string"&&vRt(s.ease)&&(s.ease=lst[s.ease])}const C1e=10;class _Rt extends ost{constructor(t){bRt(t),Jtt(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 Vue({...l,autoplay:!1}),c=Math.max(C1e,xf.now()-this.startTime),d=a1(0,C1e,c-C1e),h=o.sample(c).value,{name:m}=this.options;i&&m&&sst(i,m,h),r.setWithVelocity(o.sample(Math.max(0,c-d)).value,h,d),o.stop()}}const s8e=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(o0.test(s)||s==="0")&&!s.startsWith("url("));function wRt(s){const t=s[0];if(s.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function TRt(s){var m;const{motionValue:t,name:r,repeatDelay:n,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((m=t==null?void 0:t.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:h}=t.owner.getProps();return CRt()&&r&&(cst.has(r)||SRt.has(r)&&kRt(o))&&(r!=="transform"||!h)&&!d&&!n&&a!=="mirror"&&i!==0&&l!=="inertia"}const ERt=40;class ARt extends H3e{constructor({autoplay:t=!0,delay:r=0,type:n="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:h,...m}){var v;super(),this.stop=()=>{var j,b;this._animation&&(this._animation.stop(),(j=this.stopTimeline)==null||j.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=xf.now();const x={autoplay:t,delay:r,type:n,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:h,...m},g=(h==null?void 0:h.KeyframeResolver)||G3e;this.keyframeResolver=new g(o,(j,b,N)=>this.onKeyframesResolved(j,b,x,!N),c,d,h),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(t,r,n,a){var N,S;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:h}=n;this.resolvedAt=xf.now();let m=!0;jRt(t,i,l,o)||(m=!1,(S2.instantAnimations||!c)&&(h==null||h(Dpe(t,n,r))),t[0]=t[t.length-1],C2e(n),n.repeat=0);const g={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>ERt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:t},v=m&&!d&&TRt(g),j=(S=(N=g.motionValue)==null?void 0:N.owner)==null?void 0:S.current;let b;if(v)try{b=new _Rt({...g,element:j})}catch{b=new Vue(g)}else b=new Vue(g);b.finished.then(()=>{this.notifyFinished()}).catch(qg),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(),mRt()),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 dst(s,t,r,n=0,a=1){const i=Array.from(s).sort((d,h)=>d.sortNodePosition(h)).indexOf(t),l=s.size,o=(l-1)*n;return typeof r=="function"?r(i,l):a===1?i*n:o-i*n}const r8e=30,MRt=s=>!isNaN(parseFloat(s));class IRt{constructor(t,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var i;const a=xf.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=xf.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=MRt(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 O3e);const n=this.events[t].add(r);return t==="change"?()=>{n(),Ql.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=xf.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>r8e)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,r8e);return Mtt(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 bI(s,t){return new IRt(s,t)}function ust(s,t){if(s!=null&&s.inherit&&t){const{inherit:r,...n}=s;return{...t,...n}}return s}function W3e(s,t){const r=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return r!==s?ust(r,s):r}const PRt={type:"spring",stiffness:500,damping:25,restSpeed:10},LRt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),DRt={type:"keyframes",duration:.8},RRt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ORt=(s,{keyframes:t})=>t.length>2?DRt:AP.has(s)?s.startsWith("scale")?LRt(t[1]):PRt:RRt,FRt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function BRt(s){for(const t in s)if(!FRt.has(t))return!0;return!1}const K3e=(s,t,r,n={},a,i)=>l=>{const o=W3e(n,s)||{},c=o.delay||n.delay||0;let{elapsed:d=0}=n;d=d-vx(c);const h={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:x=>{t.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};BRt(o)||Object.assign(h,ORt(s,h)),h.duration&&(h.duration=vx(h.duration)),h.repeatDelay&&(h.repeatDelay=vx(h.repeatDelay)),h.from!==void 0&&(h.keyframes[0]=h.from);let m=!1;if((h.type===!1||h.duration===0&&!h.repeatDelay)&&(C2e(h),h.delay===0&&(m=!0)),(S2.instantAnimations||S2.skipAnimations||a!=null&&a.shouldSkipAnimations||o.skipAnimations)&&(m=!0,C2e(h),h.delay=0),h.allowFlatten=!o.type&&!o.ease,m&&!i&&t.get()!==void 0){const x=Dpe(h.keyframes,o);if(x!==void 0){Ql.update(()=>{h.onUpdate(x),h.onComplete()});return}}return o.isSync?new Vue(h):new ARt(h)},zRt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function $Rt(s){const t=zRt.exec(s);if(!t)return[,];const[,r,n,a]=t;return[`--${r??n}`,a]}function hst(s,t,r=1){const[n,a]=$Rt(s);if(!n)return;const i=window.getComputedStyle(t).getPropertyValue(n);if(i){const l=i.trim();return Ctt(l)?parseFloat(l):l}return z3e(a)?hst(a,t,r+1):a}function n8e(s){const t=[{},{}];return s==null||s.values.forEach((r,n)=>{t[0][n]=r.get(),t[1][n]=r.getVelocity()}),t}function Y3e(s,t,r,n){if(typeof t=="function"){const[a,i]=n8e(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]=n8e(n);t=t(r!==void 0?r:s.custom,a,i)}return t}function Y3(s,t,r){const n=s.getProps();return Y3e(n,t,r!==void 0?r:n.custom,s)}const mst=new Set(["width","height","top","left","right","bottom",...EP]),T2e=s=>Array.isArray(s);function URt(s,t,r){s.hasValue(t)?s.getValue(t).set(r):s.addValue(t,bI(r))}function qRt(s){return T2e(s)?s[s.length-1]||0:s}function VRt(s,t){const r=Y3(s,t);let{transitionEnd:n={},transition:a={},...i}=r||{};i={...i,...n};for(const l in i){const o=qRt(i[l]);URt(s,l,o)}}const sm=s=>!!(s&&s.getVelocity);function HRt(s){return!!(sm(s)&&s.add)}function E2e(s,t){const r=s.getValue("willChange");if(HRt(r))return r.add(t);if(!r&&S2.WillChange){const n=new S2.WillChange("auto");s.addValue("willChange",n),n.add(t)}}function Z3e(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const GRt="framerAppearId",fst="data-"+Z3e(GRt);function pst(s){return s.props[fst]}function WRt({protectedKeys:s,needsAnimating:t},r){const n=s.hasOwnProperty(r)&&t[r]!==!0;return t[r]=!1,n}function xst(s,t,{delay:r=0,transitionOverride:n,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?ust(i,c):c;const d=i==null?void 0:i.reduceMotion,h=i==null?void 0:i.skipAnimations;n&&(i=n);const m=[],x=a&&s.animationState&&s.animationState.getState()[a],g=i==null?void 0:i.path;g&&g.animateVisualElement(s,o,i,r,m);for(const v in o){const j=s.getValue(v,s.latestValues[v]??null),b=o[v];if(b===void 0||x&&WRt(x,v))continue;const N={delay:r,...W3e(i||{},v)};h&&(N.skipAnimations=!0);const S=j.get();if(S!==void 0&&!j.isAnimating()&&!Array.isArray(b)&&b===S&&!N.velocity){Ql.update(()=>j.set(b));continue}let T=!1;if(window.MotionHandoffAnimation){const D=pst(s);if(D){const B=window.MotionHandoffAnimation(D,v,Ql);B!==null&&(N.startTime=B,T=!0)}}E2e(s,v);const A=d??s.shouldReduceMotion;j.start(K3e(v,j,b,A&&mst.has(v)?{type:!1}:N,s,T));const P=j.animation;P&&m.push(P)}if(l){const v=()=>Ql.update(()=>{l&&VRt(s,l)});m.length?Promise.all(m).then(v):v()}return m}function A2e(s,t,r={}){var c;const n=Y3(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(xst(s,n,r)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:h=0,staggerChildren:m,staggerDirection:x}=a;return KRt(s,t,d,h,m,x,r)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,h]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>h())}else return Promise.all([i(),l(r.delay)])}function KRt(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(A2e(c,t,{...l,delay:r+(typeof n=="function"?0:n)+dst(s.variantChildren,c,n,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function YRt(s,t,r={}){s.notify("AnimationStart",t);let n;if(Array.isArray(t)){const a=t.map(i=>A2e(s,i,r));n=Promise.all(a)}else if(typeof t=="string")n=A2e(s,t,r);else{const a=typeof t=="function"?Y3(s,t,r.custom):t;n=Promise.all(xst(s,a,r))}return n.then(()=>{s.notify("AnimationComplete",t)})}const ZRt={test:s=>s==="auto",parse:s=>s},gst=s=>t=>t.test(s),yst=[TP,va,Jv,bb,wDt,_Dt,ZRt],a8e=s=>yst.find(gst(s));function XRt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Ett(s):!0}const QRt=new Set(["brightness","contrast","saturate","opacity"]);function JRt(s){const[t,r]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[n]=r.match($3e)||[];if(!n)return s;const a=r.replace(n,"");let i=QRt.has(t)?1:0;return n!==r&&(i*=100),t+"("+i+a+")"}const eOt=/\b([a-z-]*)\(.*?\)/gu,M2e={...o0,getAnimatableNone:s=>{const t=s.match(eOt);return t?t.map(JRt).join(" "):s}},I2e={...o0,getAnimatableNone:s=>{const t=o0.parse(s);return o0.createTransformer(s)(t.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},i8e={...TP,transform:Math.round},tOt={rotate:bb,pathRotation:bb,rotateX:bb,rotateY:bb,rotateZ:bb,scale:sU,scaleX:sU,scaleY:sU,scaleZ:sU,skew:bb,skewX:bb,skewY:bb,distance:va,translateX:va,translateY:va,translateZ:va,x:va,y:va,z:va,perspective:va,transformPerspective:va,opacity:aF,originX:GOe,originY:GOe,originZ:va},Hue={borderWidth:va,borderTopWidth:va,borderRightWidth:va,borderBottomWidth:va,borderLeftWidth:va,borderRadius:va,borderTopLeftRadius:va,borderTopRightRadius:va,borderBottomRightRadius:va,borderBottomLeftRadius:va,width:va,maxWidth:va,height:va,maxHeight:va,top:va,right:va,bottom:va,left:va,inset:va,insetBlock:va,insetBlockStart:va,insetBlockEnd:va,insetInline:va,insetInlineStart:va,insetInlineEnd:va,padding:va,paddingTop:va,paddingRight:va,paddingBottom:va,paddingLeft:va,paddingBlock:va,paddingBlockStart:va,paddingBlockEnd:va,paddingInline:va,paddingInlineStart:va,paddingInlineEnd:va,margin:va,marginTop:va,marginRight:va,marginBottom:va,marginLeft:va,marginBlock:va,marginBlockStart:va,marginBlockEnd:va,marginInline:va,marginInlineStart:va,marginInlineEnd:va,fontSize:va,backgroundPositionX:va,backgroundPositionY:va,...tOt,zIndex:i8e,fillOpacity:aF,strokeOpacity:aF,numOctaves:i8e},sOt={...Hue,color:vu,backgroundColor:vu,outlineColor:vu,fill:vu,stroke:vu,borderColor:vu,borderTopColor:vu,borderRightColor:vu,borderBottomColor:vu,borderLeftColor:vu,filter:M2e,WebkitFilter:M2e,mask:I2e,WebkitMask:I2e},vst=s=>sOt[s],rOt=new Set([M2e,I2e]);function bst(s,t){let r=vst(s);return rOt.has(r)||(r=o0),r.getAnimatableNone?r.getAnimatableNone(t):void 0}const nOt=new Set(["auto","none","0"]);function aOt(s,t,r){let n=0,a;for(;n{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function X3e(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 P2e=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function xde(s){return Ttt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:Q3e}=Utt(queueMicrotask,!1),Ly={x:!1,y:!1};function _st(){return Ly.x||Ly.y}function oOt(s){return s==="x"||s==="y"?Ly[s]?null:(Ly[s]=!0,()=>{Ly[s]=!1}):Ly.x||Ly.y?null:(Ly.x=Ly.y=!0,()=>{Ly.x=Ly.y=!1})}function wst(s,t){const r=X3e(s),n=new AbortController,a={passive:!0,...t,signal:n.signal};return[r,a,()=>n.abort()]}function lOt(s){return!(s.pointerType==="touch"||_st())}function cOt(s,t,r={}){const[n,a,i]=wst(s,r);return n.forEach(l=>{let o=!1,c=!1,d;const h=()=>{l.removeEventListener("pointerleave",v)},m=b=>{d&&(d(b),d=void 0),h()},x=b=>{o=!1,window.removeEventListener("pointerup",x),window.removeEventListener("pointercancel",x),c&&(c=!1,m(b))},g=()=>{o=!0,window.addEventListener("pointerup",x,a),window.addEventListener("pointercancel",x,a)},v=b=>{if(b.pointerType!=="touch"){if(o){c=!0;return}m(b)}},j=b=>{if(!lOt(b))return;c=!1;const N=t(l,b);typeof N=="function"&&(d=N,l.addEventListener("pointerleave",v,a))};l.addEventListener("pointerenter",j,a),l.addEventListener("pointerdown",g,a)}),i}const jst=(s,t)=>t?s===t?!0:jst(s,t.parentElement):!1,J3e=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,dOt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function uOt(s){return dOt.has(s.tagName)||s.isContentEditable===!0}const hOt=new Set(["INPUT","SELECT","TEXTAREA"]);function mOt(s){return hOt.has(s.tagName)||s.isContentEditable===!0}const gde=new WeakSet;function o8e(s){return t=>{t.key==="Enter"&&s(t)}}function T1e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const fOt=(s,t)=>{const r=s.currentTarget;if(!r)return;const n=o8e(()=>{if(gde.has(r))return;T1e(r,"down");const a=o8e(()=>{T1e(r,"up")}),i=()=>T1e(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 l8e(s){return J3e(s)&&!_st()}const c8e=new WeakSet;function pOt(s,t,r={}){const[n,a,i]=wst(s,r),l=o=>{const c=o.currentTarget;if(!l8e(o)||c8e.has(o))return;gde.add(c),r.stopPropagation&&c8e.add(o);const d=t(c,o),h=(g,v)=>{window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",x),gde.has(c)&&gde.delete(c),l8e(g)&&typeof d=="function"&&d(g,{success:v})},m=g=>{h(g,c===window||c===document||r.useGlobalTarget||jst(c,g.target))},x=g=>{h(g,!1)};window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",x,a)};return n.forEach(o=>{(r.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),xde(o)&&(o.addEventListener("focus",d=>fOt(d,a)),!uOt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function e5e(s){return Ttt(s)&&"ownerSVGElement"in s}const yde=new WeakMap;let Gw;const Nst=(s,t,r)=>(n,a)=>a&&a[0]?a[0][s+"Size"]:e5e(n)&&"getBBox"in n?n.getBBox()[t]:n[r],xOt=Nst("inline","width","offsetWidth"),gOt=Nst("block","height","offsetHeight");function yOt({target:s,borderBoxSize:t}){var r;(r=yde.get(s))==null||r.forEach(n=>{n(s,{get width(){return xOt(s,t)},get height(){return gOt(s,t)}})})}function vOt(s){s.forEach(yOt)}function bOt(){typeof ResizeObserver>"u"||(Gw=new ResizeObserver(vOt))}function _Ot(s,t){Gw||bOt();const r=X3e(s);return r.forEach(n=>{let a=yde.get(n);a||(a=new Set,yde.set(n,a)),a.add(t),Gw==null||Gw.observe(n)}),()=>{r.forEach(n=>{const a=yde.get(n);a==null||a.delete(t),a!=null&&a.size||Gw==null||Gw.unobserve(n)})}}const vde=new Set;let MA;function wOt(){MA=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};vde.forEach(t=>t(s))},window.addEventListener("resize",MA)}function jOt(s){return vde.add(s),MA||wOt(),()=>{vde.delete(s),!vde.size&&typeof MA=="function"&&(window.removeEventListener("resize",MA),MA=void 0)}}function d8e(s,t){return typeof s=="function"?jOt(s):_Ot(s,t)}function NOt(s){return e5e(s)&&s.tagName==="svg"}const kOt=[...yst,vu,o0],SOt=s=>kOt.find(gst(s)),u8e=()=>({translate:0,scale:1,origin:0,originPoint:0}),IA=()=>({x:u8e(),y:u8e()}),h8e=()=>({min:0,max:0}),Ou=()=>({x:h8e(),y:h8e()}),COt=new WeakMap;function Rpe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function iF(s){return typeof s=="string"||Array.isArray(s)}const t5e=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],s5e=["initial",...t5e];function Ope(s){return Rpe(s.animate)||s5e.some(t=>iF(s[t]))}function kst(s){return!!(Ope(s)||s.variants)}function TOt(s,t,r){for(const n in t){const a=t[n],i=r[n];if(sm(a))s.addValue(n,a);else if(sm(i))s.addValue(n,bI(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,bI(l!==void 0?l:a,{owner:s}))}}for(const n in r)t[n]===void 0&&s.removeValue(n);return t}const L2e={current:null},Sst={current:!1},EOt=typeof window<"u";function AOt(){if(Sst.current=!0,!!EOt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>L2e.current=s.matches;s.addEventListener("change",t),t()}else L2e.current=!1}const m8e=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Gue={};function Cst(s){Gue=s}function MOt(){return Gue}class IOt{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=G3e,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 g=xf.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Sst.current||AOt(),this.shouldReduceMotion=L2e.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(),C2(this.notifyUpdate),C2(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&&cst.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:h}=r.accelerate,m=new ost({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:vx(h)}),x=l(m);this.valueSubscriptions.set(t,()=>{x(),m.cancel()});return}const n=AP.has(t);n&&this.onBindTransform&&this.onBindTransform();const a=r.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Ql.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()})}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 Gue){const r=Gue[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):Ou()}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=bI(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"&&(Ctt(n)||Ett(n))?n=parseFloat(n):!SOt(n)&&o0.test(r)&&(n=bst(t,r)),this.setBaseTarget(t,sm(n)?n.get():n)),sm(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=Y3e(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&&!sm(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 O3e),this.events[t].add(r)}notify(t,...r){this.events[t]&&this.events[t].notify(...r)}scheduleRenderMicrotask(){Q3e.render(this.render)}}class Tst extends IOt{constructor(){super(...arguments),this.KeyframeResolver=iOt}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;sm(t)&&(this.childSubscription=t.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class Y2{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Est({top:s,left:t,right:r,bottom:n}){return{x:{min:t,max:r},y:{min:s,max:n}}}function POt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function LOt(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 E1e(s){return s===void 0||s===1}function D2e({scale:s,scaleX:t,scaleY:r}){return!E1e(s)||!E1e(t)||!E1e(r)}function C4(s){return D2e(s)||Ast(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function Ast(s){return f8e(s.x)||f8e(s.y)}function f8e(s){return s&&s!=="0%"}function Wue(s,t,r){const n=s-r,a=t*n;return r+a}function p8e(s,t,r,n,a){return a!==void 0&&(s=Wue(s,a,n)),Wue(s,r,n)+t}function R2e(s,t=0,r=1,n,a){s.min=p8e(s.min,t,r,n,a),s.max=p8e(s.max,t,r,n,a)}function Mst(s,{x:t,y:r}){R2e(s.x,t.translate,t.scale,t.originPoint),R2e(s.y,r.translate,r.scale,r.originPoint)}const x8e=.999999999999,g8e=1.0000000000001;function DOt(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;cx8e&&(t.x=1),t.yx8e&&(t.y=1)}function _v(s,t){s.min+=t,s.max+=t}function y8e(s,t,r,n,a=.5){const i=Yl(s.min,s.max,a);R2e(s,t,r,i,n)}function v8e(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function bde(s,t,r){const n=r??s;y8e(s.x,v8e(t.x,n.x),t.scaleX,t.scale,t.originX),y8e(s.y,v8e(t.y,n.y),t.scaleY,t.scale,t.originY)}function Ist(s,t){return Est(LOt(s.getBoundingClientRect(),t))}function ROt(s,t,r){const n=Ist(s,r),{scroll:a}=t;return a&&(_v(n.x,a.offset.x),_v(n.y,a.offset.y)),n}const OOt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},FOt=EP.length;function BOt(s,t,r){let n="",a=!0;for(let l=0;l{if(!t.target)return s;if(typeof s=="string")if(va.test(s))s=parseFloat(s);else return s;const r=b8e(s,t.target.x),n=b8e(s,t.target.y);return`${r}% ${n}%`}},zOt={correct:(s,{treeScale:t,projectionDelta:r})=>{const n=s,a=o0.parse(s);if(a.length>5)return n;const i=o0.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=Yl(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},O2e={borderRadius:{...$D,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:$D,borderTopRightRadius:$D,borderBottomLeftRadius:$D,borderBottomRightRadius:$D,boxShadow:zOt};function Lst(s,{layout:t,layoutId:r}){return AP.has(s)||s.startsWith("origin")||(t||r!==void 0)&&(!!O2e[s]||s==="opacity")}function n5e(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)(sm(n[o])||a&&sm(a[o])||Lst(o,s)||((l=r==null?void 0:r.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=n[o]);return i}function $Ot(s){return window.getComputedStyle(s)}class UOt extends Tst{constructor(){super(...arguments),this.type="html",this.renderInstance=Pst}readValueFromInstance(t,r){var n;if(AP.has(r))return(n=this.projection)!=null&&n.isProjecting?w2e(r):lRt(t,r);{const a=$Ot(t),i=(Vtt(r)?a.getPropertyValue(r):a[r])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:r}){return Ist(t,r)}build(t,r,n){r5e(t,r,n.transformTemplate)}scrapeMotionValuesFromProps(t,r,n){return n5e(t,r,n)}}const qOt={offset:"stroke-dashoffset",array:"stroke-dasharray"},VOt={offset:"strokeDashoffset",array:"strokeDasharray"};function HOt(s,t,r=1,n=0,a=!0){s.pathLength=1;const i=a?qOt:VOt;s[i.offset]=`${-n}`,s[i.array]=`${t} ${r}`}const GOt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Dst(s,{attrX:t,attrY:r,attrScale:n,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,h){if(r5e(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:m,style:x}=s;m.transform&&(x.transform=m.transform,delete m.transform),(x.transform||m.transformOrigin)&&(x.transformOrigin=m.transformOrigin??"50% 50%",delete m.transformOrigin),x.transform&&(x.transformBox=(h==null?void 0:h.transformBox)??"fill-box",delete m.transformBox);for(const g of GOt)m[g]!==void 0&&(x[g]=m[g],delete m[g]);t!==void 0&&(m.x=t),r!==void 0&&(m.y=r),n!==void 0&&(m.scale=n),a!==void 0&&HOt(m,a,i,l,!1)}const Rst=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"]),Ost=s=>typeof s=="string"&&s.toLowerCase()==="svg";function WOt(s,t,r,n){Pst(s,t,void 0,n);for(const a in t.attrs)s.setAttribute(Rst.has(a)?a:Z3e(a),t.attrs[a])}function Fst(s,t,r){const n=n5e(s,t,r);for(const a in s)if(sm(s[a])||sm(t[a])){const i=EP.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;n[i]=s[a]}return n}class KOt extends Tst{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ou}getBaseTargetFromProps(t,r){return t[r]}readValueFromInstance(t,r){if(AP.has(r)){const n=vst(r);return n&&n.default||0}return r=Rst.has(r)?r:Z3e(r),t.getAttribute(r)}scrapeMotionValuesFromProps(t,r,n){return Fst(t,r,n)}build(t,r,n){Dst(t,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,r,n,a){WOt(t,r,n,a)}mount(t){this.isSVGTag=Ost(t.tagName),super.mount(t)}}const YOt=s5e.length;function Bst(s){if(!s)return;if(!s.isControllingVariants){const r=s.parent?Bst(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})=>YRt(s,r,n)))}function JOt(s){let t=QOt(s),r=_8e(),n=!0,a=!1;const i=d=>(h,m)=>{var g;const x=Y3(s,m,d==="exit"?(g=s.presenceContext)==null?void 0:g.custom:void 0);if(x){const{transition:v,transitionEnd:j,...b}=x;h={...h,...b,...j}}return h};function l(d){t=d(s)}function o(d){const{props:h}=s,m=Bst(s.parent)||{},x=[],g=new Set;let v={},j=1/0;for(let N=0;Nj&&P,$=!1;const X=Array.isArray(A)?A:[A];let K=X.reduce(i(S),{});D===!1&&(K={});const{prevResolvedValues:Q={}}=T,Y={...Q,...K},ne=ae=>{F=!0,g.has(ae)&&($=!0,g.delete(ae)),T.needsAnimating[ae]=!0;const ie=s.getValue(ae);ie&&(ie.liveStyle=!1)};for(const ae in Y){const ie=K[ae],me=Q[ae];if(v.hasOwnProperty(ae))continue;let oe=!1;T2e(ie)&&T2e(me)?oe=!zst(ie,me)||z:oe=ie!==me,oe?ie!=null?ne(ae):g.add(ae):ie!==void 0&&g.has(ae)?ne(ae):T.protectedKeys[ae]=!0}T.prevProp=A,T.prevResolvedValues=K,T.isActive&&(v={...v,...K}),(n||a)&&s.blockInitialAnimation&&(F=!1);const de=B&&z;F&&(!de||$)&&x.push(...X.map(ae=>{const ie={type:S};if(typeof ae=="string"&&(n||a)&&!de&&s.manuallyAnimateOnMount&&s.parent){const{parent:me}=s,oe=Y3(me,ae);if(me.enteringChildren&&oe){const{delayChildren:ge}=oe.transition||{};ie.delay=dst(me.enteringChildren,s,ge)}}return{animation:ae,options:ie}}))}if(g.size){const N={};if(typeof h.initial!="boolean"){const S=Y3(s,Array.isArray(h.initial)?h.initial[0]:h.initial);S&&S.transition&&(N.transition=S.transition)}g.forEach(S=>{const T=s.getBaseTarget(S),A=s.getValue(S);A&&(A.liveStyle=!0),N[S]=T??null}),x.push({animation:N})}let b=!!x.length;return n&&(h.initial===!1||h.initial===h.animate)&&!s.manuallyAnimateOnMount&&(b=!1),n=!1,a=!1,b?t(x):Promise.resolve()}function c(d,h){var x;if(r[d].isActive===h)return Promise.resolve();(x=s.variantChildren)==null||x.forEach(g=>{var v;return(v=g.animationState)==null?void 0:v.setActive(d,h)}),r[d].isActive=h;const m=o(d);for(const g in r)r[g].protectedKeys={};return m}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>r,reset:()=>{r=_8e(),a=!0}}}function e8t(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!zst(t,s):!1}function ok(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function _8e(){return{animate:ok(!0),whileInView:ok(),whileHover:ok(),whileTap:ok(),whileDrag:ok(),whileFocus:ok(),exit:ok()}}function F2e(s,t){s.min=t.min,s.max=t.max}function Ey(s,t){F2e(s.x,t.x),F2e(s.y,t.y)}function w8e(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const $st=1e-4,t8t=1-$st,s8t=1+$st,Ust=.01,r8t=0-Ust,n8t=0+Ust;function gf(s){return s.max-s.min}function a8t(s,t,r){return Math.abs(s-t)<=r}function j8e(s,t,r,n=.5){s.origin=n,s.originPoint=Yl(t.min,t.max,s.origin),s.scale=gf(r)/gf(t),s.translate=Yl(r.min,r.max,s.origin)-s.originPoint,(s.scale>=t8t&&s.scale<=s8t||isNaN(s.scale))&&(s.scale=1),(s.translate>=r8t&&s.translate<=n8t||isNaN(s.translate))&&(s.translate=0)}function XO(s,t,r,n){j8e(s.x,t.x,r.x,n?n.originX:void 0),j8e(s.y,t.y,r.y,n?n.originY:void 0)}function N8e(s,t,r,n=0){const a=n?Yl(r.min,r.max,n):r.min;s.min=a+t.min,s.max=s.min+gf(t)}function i8t(s,t,r,n){N8e(s.x,t.x,r.x,n==null?void 0:n.x),N8e(s.y,t.y,r.y,n==null?void 0:n.y)}function k8e(s,t,r,n=0){const a=n?Yl(r.min,r.max,n):r.min;s.min=t.min-a,s.max=s.min+gf(t)}function Kue(s,t,r,n){k8e(s.x,t.x,r.x,n==null?void 0:n.x),k8e(s.y,t.y,r.y,n==null?void 0:n.y)}function S8e(s,t,r,n,a){return s-=t,s=Wue(s,1/r,n),a!==void 0&&(s=Wue(s,1/a,n)),s}function o8t(s,t=0,r=1,n=.5,a,i=s,l=s){if(Jv.test(t)&&(t=parseFloat(t),t=Yl(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Yl(i.min,i.max,n);s===i&&(o-=t),s.min=S8e(s.min,t,r,o,a),s.max=S8e(s.max,t,r,o,a)}function C8e(s,t,[r,n,a],i,l){o8t(s,t[r],t[n],t[a],t.scale,i,l)}const l8t=["x","scaleX","originX"],c8t=["y","scaleY","originY"];function T8e(s,t,r,n){C8e(s.x,t,l8t,r?r.x:void 0,n?n.x:void 0),C8e(s.y,t,c8t,r?r.y:void 0,n?n.y:void 0)}function E8e(s){return s.translate===0&&s.scale===1}function qst(s){return E8e(s.x)&&E8e(s.y)}function A8e(s,t){return s.min===t.min&&s.max===t.max}function d8t(s,t){return A8e(s.x,t.x)&&A8e(s.y,t.y)}function M8e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function Vst(s,t){return M8e(s.x,t.x)&&M8e(s.y,t.y)}function I8e(s){return gf(s.x)/gf(s.y)}function P8e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function dv(s){return[s("x"),s("y")]}function u8t(s,t,r){let n="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(r==null?void 0:r.z)||0;if((a||i||l)&&(n=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),r){const{transformPerspective:d,rotate:h,pathRotation:m,rotateX:x,rotateY:g,skewX:v,skewY:j}=r;d&&(n=`perspective(${d}px) ${n}`),h&&(n+=`rotate(${h}deg) `),m&&(n+=`rotate(${m}deg) `),x&&(n+=`rotateX(${x}deg) `),g&&(n+=`rotateY(${g}deg) `),v&&(n+=`skewX(${v}deg) `),j&&(n+=`skewY(${j}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 Hst=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],h8t=Hst.length,L8e=s=>typeof s=="string"?parseFloat(s):s,D8e=s=>typeof s=="number"||va.test(s);function m8t(s,t,r,n,a,i){a?(s.opacity=Yl(0,r.opacity??1,f8t(n)),s.opacityExit=Yl(t.opacity??1,0,p8t(n))):i&&(s.opacity=Yl(t.opacity??1,r.opacity??1,n));for(let l=0;lnt?1:r(nF(s,t,n))}function x8t(s,t,r){const n=sm(s)?s:bI(s);return n.start(K3e("",n,t,r)),n.animation}function oF(s,t,r,n={passive:!0}){return s.addEventListener(t,r,n),()=>s.removeEventListener(t,r)}const g8t=(s,t)=>s.depth-t.depth;class y8t{constructor(){this.children=[],this.isDirty=!1}add(t){D3e(this.children,t),this.isDirty=!0}remove(t){zue(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(g8t),this.isDirty=!1,this.children.forEach(t)}}function v8t(s,t){const r=xf.now(),n=({timestamp:a})=>{const i=a-r;i>=t&&(C2(n),s(i-t))};return Ql.setup(n,!0),()=>C2(n)}function _de(s){return sm(s)?s.get():s}class b8t{constructor(){this.members=[]}add(t){D3e(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&&(zue(this.members,n),n.unmount())}t.scheduleRender()}remove(t){if(zue(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 wde={hasAnimatedSinceResize:!0,hasEverUpdated:!1},A1e=["","X","Y","Z"],_8t=1e3;let w8t=0;function M1e(s,t,r,n){const{latestValues:a}=t;a[s]&&(r[s]=a[s],t.setStaticValue(s,0),n&&(n[s]=0))}function Wst(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const r=pst(t);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(r,"transform",Ql,!(a||i))}const{parent:n}=s;n&&!n.hasCheckedOptimisedAppear&&Wst(n)}function Kst({attachResizeListener:s,defaultParent:t,measureScroll:r,checkIsScrollRoot:n,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=w8t++,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(k8t),this.nodes.forEach(M8t),this.nodes.forEach(I8t),this.nodes.forEach(S8t)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Ql.read(()=>{m=window.innerWidth}),s(l,()=>{const g=window.innerWidth;g!==m&&(m=g,this.root.updateBlockedByResize=!0,h&&h(),h=v8t(x,250),wde.hasAnimatedSinceResize&&(wde.hasAnimatedSinceResize=!1,this.nodes.forEach(B8e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:h,hasLayoutChanged:m,hasRelativeLayoutChanged:x,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||d.getDefaultTransition()||O8t,{onLayoutAnimationStart:j,onLayoutAnimationComplete:b}=d.getProps(),N=!this.targetLayout||!Vst(this.targetLayout,g),S=!m&&x;if(this.options.layoutRoot||this.resumeFrom||S||m&&(N||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...W3e(v,"layout"),onPlay:j,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(h,S,T.path)}else m||B8e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}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(),C2(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(P8t),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&&Wst(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let h=0;h{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!gf(this.snapshot.measuredBox.x)&&!gf(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 B=D/1e3,z=P==null?void 0:P(B);z?(x.x.translate=z.x,x.x.scale=Yl(l.x.scale,1,B),x.x.origin=l.x.origin,x.x.originPoint=l.x.originPoint,x.y.translate=z.y,x.y.scale=Yl(l.y.scale,1,B),x.y.origin=l.y.origin,x.y.originPoint=l.y.originPoint):(z8e(x.x,l.x,B),z8e(x.y,l.y,B)),this.setTargetDelta(x),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Kue(g,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),D8t(this.relativeTarget,this.relativeTargetOrigin,g,B),A&&d8t(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=Ou()),Ey(A,this.relativeTarget)),b&&(this.animationValues=m,m8t(m,h,this.latestValues,B,T,S)),z&&z.rotate!==void 0&&(this.animationValues||(this.animationValues=m),this.animationValues.pathRotation=z.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=B},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&&(C2(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ql.update(()=>{wde.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=bI(0)),this.motionValue.jump(0,!1),this.currentAnimation=x8t(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:h=>{this.mixTargetDelta(h),l.onUpdate&&l.onUpdate(h)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(_8t),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:h}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Yst(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Ou();const m=gf(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+m;const x=gf(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Ey(o,c),bde(o,h),XO(this.projectionDeltaWithTransform,this.layoutCorrected,o,h)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new b8t),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&&M1e("z",l,d,this.animationValues);for(let h=0;h{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(O8e),this.root.sharedNodes.clear()}}}function j8t(s){s.updateLayout()}function N8t(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")dv(m=>{const x=l?t.measuredBox[m]:t.layoutBox[m],g=gf(x);x.min=n[m].min,x.max=x.min+g});else if(i==="x"||i==="y"){const m=i==="x"?"y":"x";F2e(l?t.measuredBox[m]:t.layoutBox[m],n[m])}else Yst(i,t.layoutBox,n)&&dv(m=>{const x=l?t.measuredBox[m]:t.layoutBox[m],g=gf(n[m]);x.max=x.min+g,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[m].max=s.relativeTarget[m].min+g)});const o=IA();XO(o,n,t.layoutBox);const c=IA();l?XO(c,s.applyTransform(a,!0),t.measuredBox):XO(c,n,t.layoutBox);const d=!qst(o);let h=!1;if(!s.resumeFrom){const m=s.getClosestProjectingParent();if(m&&!m.resumeFrom){const{snapshot:x,layout:g}=m;if(x&&g){const v=s.options.layoutAnchor||void 0,j=Ou();Kue(j,t.layoutBox,x.layoutBox,v);const b=Ou();Kue(b,n,g.layoutBox,v),Vst(j,b)||(h=!0),m.options.layoutRoot&&(s.relativeTarget=b,s.relativeTargetOrigin=j,s.relativeParent=m)}}}s.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:h})}else if(s.isLead()){const{onExitComplete:n}=s.options;n&&n()}s.options.transition=void 0}function k8t(s){s.parent&&(s.isProjecting()||(s.isProjectionDirty=s.parent.isProjectionDirty),s.isSharedProjectionDirty||(s.isSharedProjectionDirty=!!(s.isProjectionDirty||s.parent.isProjectionDirty||s.parent.isSharedProjectionDirty)),s.isTransformDirty||(s.isTransformDirty=s.parent.isTransformDirty))}function S8t(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function C8t(s){s.clearSnapshot()}function O8e(s){s.clearMeasurements()}function T8t(s){s.isLayoutDirty=!0,s.updateLayout()}function F8e(s){s.isLayoutDirty=!1}function E8t(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function A8t(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function B8e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function M8t(s){s.resolveTargetDelta()}function I8t(s){s.calcProjection()}function P8t(s){s.resetSkewAndRotation()}function L8t(s){s.removeLeadSnapshot()}function z8e(s,t,r){s.translate=Yl(t.translate,0,r),s.scale=Yl(t.scale,1,r),s.origin=t.origin,s.originPoint=t.originPoint}function $8e(s,t,r,n){s.min=Yl(t.min,r.min,n),s.max=Yl(t.max,r.max,n)}function D8t(s,t,r,n){$8e(s.x,t.x,r.x,n),$8e(s.y,t.y,r.y,n)}function R8t(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const O8t={duration:.45,ease:[.4,0,.1,1]},U8e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),q8e=U8e("applewebkit/")&&!U8e("chrome/")?Math.round:qg;function V8e(s){s.min=q8e(s.min),s.max=q8e(s.max)}function F8t(s){V8e(s.x),V8e(s.y)}function Yst(s,t,r){return s==="position"||s==="preserve-aspect"&&!a8t(I8e(t),I8e(r),.2)}function B8t(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const z8t=Kst({attachResizeListener:(s,t)=>oF(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}),I1e={current:void 0},Zst=Kst({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!I1e.current){const s=new z8t({});s.mount(window),s.setOptions({layoutScroll:!0}),I1e.current=s}return I1e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),a5e=k.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function H8e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function $8t(...s){return t=>{let r=!1;const n=s.map(a=>{const i=H8e(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{width:g,height:v,top:j,left:b,right:N,bottom:S,direction:T}=c.current;if(t||i===!1||!o.current||!g||!v)return;const A=T==="rtl",P=r==="left"?A?`right: ${N}`:`left: ${b}`:A?`left: ${b}`:`right: ${N}`,D=n==="bottom"?`bottom: ${S}`:`top: ${j}`;o.current.dataset.motionPopId=l;const B=document.createElement("style");d&&(B.nonce=d);const z=a??document.head;return z.appendChild(B),B.sheet&&B.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${g}px !important; height: ${v}px !important; ${P}px !important; ${D}px !important; } `),()=>{var F;(F=o.current)==null||F.removeAttribute("data-motion-pop-id"),z.contains(B)&&z.removeChild(B)}},[t]),e.jsx(q8t,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:k.cloneElement(s,{ref:m})})}const H8t=({children:s,initial:t,isPresent:r,onExitComplete:n,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const h=L3e(G8t),m=k.useId();let x=!0,g=k.useMemo(()=>(x=!1,{id:m,initial:t,isPresent:r,custom:a,onExitComplete:v=>{h.set(v,!0);for(const j of h.values())if(!j)return;n&&n()},register:v=>(h.set(v,!1),()=>h.delete(v))}),[r,h,n]);return i&&x&&(g={...g}),k.useMemo(()=>{h.forEach((v,j)=>h.set(j,!1))},[r]),k.useEffect(()=>{!r&&!h.size&&n&&n()},[r]),s=e.jsx(V8t,{pop:l==="popLayout",isPresent:r,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(Lpe.Provider,{value:g,children:s})};function G8t(){return new Map}function Xst(s=!0){const t=k.useContext(Lpe);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 rU=s=>s.key||"";function G8e(s){const t=[];return k.Children.forEach(s,r=>{k.isValidElement(r)&&t.push(r)}),t}const i5e=({children:s,custom:t,initial:r=!0,onExitComplete:n,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[h,m]=Xst(l),x=k.useMemo(()=>G8e(s),[s]),g=l&&!h?[]:x.map(rU),v=k.useRef(!0),j=k.useRef(x),b=L3e(()=>new Map),N=k.useRef(new Set),[S,T]=k.useState(x),[A,P]=k.useState(x);Stt(()=>{v.current=!1,j.current=x;for(let z=0;z{const F=rU(z),$=l&&!h?!1:x===A||g.includes(F),X=()=>{if(N.current.has(F))return;if(b.has(F))N.current.add(F),b.set(F,!0);else return;let K=!0;b.forEach(Q=>{Q||(K=!1)}),K&&(B==null||B(),P(j.current),l&&(m==null||m()),n&&n())};return e.jsx(H8t,{isPresent:$,initial:!v.current||r?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:$?void 0:X,anchorX:o,anchorY:c,children:z},F)})})},Qst=k.createContext({strict:!1}),W8e={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 K8e=!1;function W8t(){if(K8e)return;const s={};for(const t in W8e)s[t]={isEnabled:r=>W8e[t].some(n=>!!r[n])};Cst(s),K8e=!0}function Jst(){return W8t(),MOt()}function K8t(s){const t=Jst();for(const r in s)t[r]={...t[r],...s[r]};Cst(t)}const Y8t=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 Yue(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||Y8t.has(s)}let ert=s=>!Yue(s);function Z8t(s){typeof s=="function"&&(ert=t=>t.startsWith("on")?!Yue(t):s(t))}try{Z8t(require("@emotion/is-prop-valid").default)}catch{}function X8t(s,t,r){const n={};for(const a in s)a==="values"&&typeof s.values=="object"||sm(s[a])||(ert(a)||r===!0&&Yue(a)||!t&&!Yue(a)||s.draggable&&a.startsWith("onDrag"))&&(n[a]=s[a]);return n}const Fpe=k.createContext({});function Q8t(s,t){if(Ope(s)){const{initial:r,animate:n}=s;return{initial:r===!1||iF(r)?r:void 0,animate:iF(n)?n:void 0}}return s.inherit!==!1?t:{}}function J8t(s){const{initial:t,animate:r}=Q8t(s,k.useContext(Fpe));return k.useMemo(()=>({initial:t,animate:r}),[Y8e(t),Y8e(r)])}function Y8e(s){return Array.isArray(s)?s.join(" "):s}const o5e=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function trt(s,t,r){for(const n in t)!sm(t[n])&&!Lst(n,r)&&(s[n]=t[n])}function eFt({transformTemplate:s},t){return k.useMemo(()=>{const r=o5e();return r5e(r,t,s),Object.assign({},r.vars,r.style)},[t])}function tFt(s,t){const r=s.style||{},n={};return trt(n,r,s),Object.assign(n,eFt(s,t)),n}function sFt(s,t){const r={},n=tFt(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 srt=()=>({...o5e(),attrs:{}});function rFt(s,t,r,n){const a=k.useMemo(()=>{const i=srt();return Dst(i,t,Ost(n),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};trt(i,s.style,s),a.style={...i,...a.style}}return a}const nFt=["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 l5e(s){return typeof s!="string"||s.includes("-")?!1:!!(nFt.indexOf(s)>-1||/[A-Z]/u.test(s))}function aFt(s,t,r,{latestValues:n},a,i=!1,l){const c=(l??l5e(s)?rFt:sFt)(t,n,a,s),d=X8t(t,typeof s=="string",i),h=s!==k.Fragment?{...d,...c,ref:r}:{},{children:m}=t,x=k.useMemo(()=>sm(m)?m.get():m,[m]);return k.createElement(s,{...h,children:x})}function iFt({scrapeMotionValuesFromProps:s,createRenderState:t},r,n,a){return{latestValues:oFt(r,n,a,s),renderState:t()}}function oFt(s,t,r,n){const a={},i=n(s,{});for(const x in i)a[x]=_de(i[x]);let{initial:l,animate:o}=s;const c=Ope(s),d=kst(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let h=r?r.initial===!1:!1;h=h||l===!1;const m=h?o:l;if(m&&typeof m!="boolean"&&!Rpe(m)){const x=Array.isArray(m)?m:[m];for(let g=0;g(t,r)=>{const n=k.useContext(Fpe),a=k.useContext(Lpe),i=()=>iFt(s,t,n,a);return r?i():L3e(i)},lFt=rrt({scrapeMotionValuesFromProps:n5e,createRenderState:o5e}),cFt=rrt({scrapeMotionValuesFromProps:Fst,createRenderState:srt}),dFt=Symbol.for("motionComponentSymbol");function uFt(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)),t&&(i?t.mount(i):t.unmount());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])}const nrt=k.createContext({});function lA(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function hFt(s,t,r,n,a,i){var T,A;const{visualElement:l}=k.useContext(Fpe),o=k.useContext(Qst),c=k.useContext(Lpe),d=k.useContext(a5e),h=d.reducedMotion,m=d.skipAnimations,x=k.useRef(null),g=k.useRef(!1);n=n||o.renderer,!x.current&&n&&(x.current=n(s,{visualState:t,parent:l,props:r,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:h,skipAnimations:m,isSVG:i}),g.current&&x.current&&(x.current.manuallyAnimateOnMount=!0));const v=x.current,j=k.useContext(nrt);v&&!v.projection&&a&&(v.type==="html"||v.type==="svg")&&mFt(x.current,r,a,j);const b=k.useRef(!1);k.useInsertionEffect(()=>{v&&b.current&&v.update(r,c)});const N=r[fst],S=k.useRef(!!N&&typeof window<"u"&&!((T=window.MotionHandoffIsComplete)!=null&&T.call(window,N))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,N)));return Stt(()=>{g.current=!0,v&&(b.current=!0,window.MotionIsMounted=!0,v.updateFeatures(),v.scheduleRenderMicrotask(),S.current&&v.animationState&&v.animationState.animateChanges())}),k.useEffect(()=>{v&&(!S.current&&v.animationState&&v.animationState.animateChanges(),S.current&&(queueMicrotask(()=>{var P;(P=window.MotionHandoffMarkAsComplete)==null||P.call(window,N)}),S.current=!1),v.enteringChildren=void 0)}),v}function mFt(s,t,r,n){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:h,layoutCrossfade:m}=t;s.projection=new r(s.latestValues,t["data-framer-portal-id"]?void 0:art(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&lA(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:n,crossfade:m,layoutScroll:c,layoutRoot:d,layoutAnchor:h})}function art(s){if(s)return s.options.allowProjection!==!1?s.projection:art(s.parent)}function P1e(s,{forwardMotionProps:t=!1,type:r}={},n,a){n&&K8t(n);const i=r?r==="svg":l5e(s),l=i?cFt:lFt;function o(d,h){let m;const x={...k.useContext(a5e),...d,layoutId:fFt(d)},{isStatic:g}=x,v=J8t(d),j=l(d,g);if(!g&&typeof window<"u"){pFt();const b=xFt(x);m=b.MeasureLayout,v.visualElement=hFt(s,j,x,a,b.ProjectionNode,i)}return e.jsxs(Fpe.Provider,{value:v,children:[m&&v.visualElement?e.jsx(m,{visualElement:v.visualElement,...x}):null,aFt(s,d,uFt(j,v.visualElement,h),j,g,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=k.forwardRef(o);return c[dFt]=s,c}function fFt({layoutId:s}){const t=k.useContext(P3e).id;return t&&s!==void 0?t+"-"+s:s}function pFt(s,t){k.useContext(Qst).strict}function xFt(s){const t=Jst(),{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 gFt(s,t){if(typeof Proxy>"u")return P1e;const r=new Map,n=(i,l)=>P1e(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,P1e(l,void 0,s,t)),r.get(l))})}const yFt=(s,t)=>t.isSVG??l5e(s)?new KOt(t):new UOt(t,{allowProjection:s!==k.Fragment});class vFt extends Y2{constructor(t){super(t),t.animationState||(t.animationState=JOt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Rpe(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 bFt=0;class _Ft extends Y2{constructor(){super(...arguments),this.id=bFt++,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"||typeof l=="object"&&l!==null&&!Array.isArray(l)){const c=Y3(this.node,l,o);if(c){const{transition:d,transitionEnd:h,...m}=c;for(const x in m)(i=this.node.getValue(x))==null||i.jump(m[x])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);r&&!t&&a.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:t,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const wFt={animation:{Feature:vFt},exit:{Feature:_Ft}};function ZB(s){return{point:{x:s.pageX,y:s.pageY}}}const jFt=s=>t=>J3e(t)&&s(t,ZB(t));function QO(s,t,r,n){return oF(s,t,jFt(r),n)}const irt=({current:s})=>s?s.ownerDocument.defaultView:null,Z8e=(s,t)=>Math.abs(s-t);function NFt(s,t){const r=Z8e(s.x,t.x),n=Z8e(s.y,t.y);return Math.sqrt(r**2+n**2)}const X8e=new Set(["auto","scroll"]);class ort{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=g=>{this.handleScroll(g.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=nU(this.lastRawMoveEventInfo,this.transformPagePoint));const g=L1e(this.lastMoveEventInfo,this.history),v=this.startEvent!==null,j=NFt(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!v&&!j)return;const{point:b}=g,{timestamp:N}=Kh;this.history.push({...b,timestamp:N});const{onStart:S,onMove:T}=this.handlers;v||(S&&S(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,g)},this.handlePointerMove=(g,v)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=v,this.lastMoveEventInfo=nU(v,this.transformPagePoint),Ql.update(this.updatePoint,!0)},this.handlePointerUp=(g,v)=>{this.end();const{onEnd:j,onSessionEnd:b,resumeAnimation:N}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&N&&N(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=L1e(g.type==="pointercancel"?this.lastMoveEventInfo:nU(v,this.transformPagePoint),this.history);this.startEvent&&j&&j(g,S),b&&b(g,S)},!J3e(t))return;this.dragSnapToOrigin=i,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=l,this.contextWindow=a||window;const c=ZB(t),d=nU(c,this.transformPagePoint),{point:h}=d,{timestamp:m}=Kh;this.history=[{...h,timestamp:m}];const{onSessionStart:x}=r;x&&x(t,L1e(d,this.history)),this.removeListeners=WB(QO(this.contextWindow,"pointermove",this.handlePointerMove),QO(this.contextWindow,"pointerup",this.handlePointerUp),QO(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let r=t.parentElement;for(;r;){const n=getComputedStyle(r);(X8e.has(n.overflowX)||X8e.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),Ql.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),C2(this.updatePoint)}}function nU(s,t){return t?{point:t(s.point)}:s}function Q8e(s,t){return{x:s.x-t.x,y:s.y-t.y}}function L1e({point:s},t){return{point:s,delta:Q8e(s,lrt(t)),offset:Q8e(s,kFt(t)),velocity:SFt(t,.1)}}function kFt(s){return s[0]}function lrt(s){return s[s.length-1]}function SFt(s,t){if(s.length<2)return{x:0,y:0};let r=s.length-1,n=null;const a=lrt(s);for(;r>=0&&(n=s[r],!(a.timestamp-n.timestamp>vx(t)));)r--;if(!n)return{x:0,y:0};n===s[0]&&s.length>2&&a.timestamp-n.timestamp>vx(t)*2&&(n=s[1]);const i=Dg(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 CFt(s,{min:t,max:r},n){return t!==void 0&&sr&&(s=n?Yl(r,s,n.max):Math.min(s,r)),s}function J8e(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 TFt(s,{top:t,left:r,bottom:n,right:a}){return{x:J8e(s.x,r,a),y:J8e(s.y,t,n)}}function eFe(s,t){let r=t.min-s.min,n=t.max-s.max;return t.max-t.minn?r=nF(t.min,t.max-n,s.min):n>a&&(r=nF(s.min,s.max-a,t.min)),a1(0,1,r)}function MFt(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 B2e=.35;function IFt(s=B2e){return s===!1?s=0:s===!0&&(s=B2e),{x:tFe(s,"left","right"),y:tFe(s,"top","bottom")}}function tFe(s,t,r){return{min:sFe(s,t),max:sFe(s,r)}}function sFe(s,t){return typeof s=="number"?s:s[t]||0}const PFt=new WeakMap;class LFt{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=Ou(),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(ZB(m).point),this.stopAnimation()},l=(m,x)=>{const{drag:g,dragPropagation:v,onDragStart:j}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=oOt(g),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),dv(N=>{let S=this.getAxisMotionValue(N).get()||0;if(Jv.test(S)){const{projection:T}=this.visualElement;if(T&&T.layout){const A=T.layout.layoutBox[N];A&&(S=gf(A)*(parseFloat(S)/100))}}this.originPoint[N]=S}),j&&Ql.update(()=>j(m,x),!1,!0),E2e(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(m,x)=>{this.latestPointerEvent=m,this.latestPanInfo=x;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:j,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:N}=x;if(v&&this.currentDirection===null){this.currentDirection=RFt(N),this.currentDirection!==null&&j&&j(this.currentDirection);return}this.updateAxis("x",x.point,N),this.updateAxis("y",x.point,N),this.visualElement.render(),b&&Ql.update(()=>b(m,x),!1,!0)},c=(m,x)=>{this.latestPointerEvent=m,this.latestPanInfo=x,this.stop(m,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:h}=this.getProps();this.panSession=new ort(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:h,distanceThreshold:n,contextWindow:irt(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&&Ql.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||!aU(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(l=CFt(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&&lA(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=TFt(n.layoutBox,t):this.constraints=!1,this.elastic=IFt(r),a!==this.constraints&&!lA(t)&&n&&this.constraints&&!this.hasMutatedConstraints&&dv(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=MFt(n.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:r}=this.getProps();if(!t||!lA(t))return!1;const n=t.current,{projection:a}=this.visualElement;if(!a||!a.layout)return!1;a.root&&(a.root.scroll=void 0,a.root.updateScroll());const i=ROt(n,a.root,this.visualElement.getTransformPagePoint());let l=EFt(a.layout.layoutBox,i);if(r){const o=r(POt(l));this.hasMutatedConstraints=!!o,o&&(l=Est(o))}return l}startAnimation(t){const{drag:r,dragMomentum:n,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=dv(h=>{if(!aU(h,r,this.currentDirection))return;let m=c&&c[h]||{};(l===!0||l===h)&&(m={min:0,max:0});const x=a?200:1e6,g=a?40:1e7,v={type:"inertia",velocity:n?t[h]:0,bounceStiffness:x,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...i,...m};return this.startAxisValueAnimation(h,v)});return Promise.all(d).then(o)}startAxisValueAnimation(t,r){const n=this.getAxisMotionValue(t);return E2e(this.visualElement,t),n.start(K3e(t,n,0,r,this.visualElement,!1))}stopAnimation(){dv(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const r=`_drag${t.toUpperCase()}`,a=this.visualElement.getProps()[r];return a||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){dv(r=>{const{drag:n}=this.getProps();if(!aU(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]-Yl(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!lA(r)||!n||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};dv(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=AFt({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(),dv(l=>{if(!aU(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Yl(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;PFt.set(this.visualElement,this);const t=this.visualElement.current,r=QO(t,"pointerdown",d=>{const{drag:h,dragListener:m=!0}=this.getProps(),x=d.target,g=x!==t&&mOt(x);h&&m&&!g&&this.start(d)});let n;const a=()=>{const{dragConstraints:d}=this.getProps();lA(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),n||(n=DFt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Ql.read(a);const o=oF(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h})=>{this.isDragging&&h&&(dv(m=>{const x=this.getAxisMotionValue(m);x&&(this.originPoint[m]+=d[m].translate,x.set(x.get()+d[m].translate))}),this.visualElement.render())});return()=>{o(),r(),l(),c&&c(),n&&n()}}getProps(){const t=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=B2e,dragMomentum:o=!0}=t;return{...t,drag:r,dragDirectionLock:n,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function rFe(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function DFt(s,t,r){const n=d8e(s,rFe(r)),a=d8e(t,rFe(r));return()=>{n(),a()}}function aU(s,t,r){return(t===!0||t===s)&&(r===null||r===s)}function RFt(s,t=10){let r=null;return Math.abs(s.y)>t?r="y":Math.abs(s.x)>t&&(r="x"),r}class OFt extends Y2{constructor(t){super(t),this.removeGroupControls=qg,this.removeListeners=qg,this.controls=new LFt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qg}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 D1e=s=>(t,r)=>{s&&Ql.update(()=>s(t,r),!1,!0)};class FFt extends Y2{constructor(){super(...arguments),this.removePointerDownListener=qg}onPointerDown(t){this.session=new ort(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:irt(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:r,onPan:n,onPanEnd:a}=this.node.getProps();return{onSessionStart:D1e(t),onStart:D1e(r),onMove:D1e(n),onEnd:(i,l)=>{delete this.session,a&&Ql.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=QO(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 R1e=!1;class BFt 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),R1e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),wde.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}),R1e=!0,a||t.layoutDependency!==r||r===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Ql.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(),Q3e.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:a}=t;R1e=!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 crt(s){const[t,r]=Xst(),n=k.useContext(P3e);return e.jsx(BFt,{...s,layoutGroup:n,switchLayoutGroup:k.useContext(nrt),isPresent:t,safeToRemove:r})}const zFt={pan:{Feature:FFt},drag:{Feature:OFt,ProjectionNode:Zst,MeasureLayout:crt}};function nFe(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&&Ql.postRender(()=>i(t,ZB(t)))}class $Ft extends Y2{mount(){const{current:t}=this.node;t&&(this.unmount=cOt(t,(r,n)=>(nFe(this.node,n,"Start"),a=>nFe(this.node,a,"End"))))}unmount(){}}class UFt extends Y2{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=WB(oF(this.node.current,"focus",()=>this.onFocus()),oF(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function aFe(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&&Ql.postRender(()=>i(t,ZB(t)))}class qFt extends Y2{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=pOt(t,(a,i)=>(aFe(this.node,i,"Start"),(l,{success:o})=>aFe(this.node,l,o?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const z2e=new WeakMap,O1e=new WeakMap,VFt=s=>{const t=z2e.get(s.target);t&&t(s)},HFt=s=>{s.forEach(VFt)};function GFt({root:s,...t}){const r=s||document;O1e.has(r)||O1e.set(r,{});const n=O1e.get(r),a=JSON.stringify(t);return n[a]||(n[a]=new IntersectionObserver(HFt,{root:s,...t})),n[a]}function WFt(s,t,r){const n=GFt(t);return z2e.set(s,r),n.observe(s),()=>{z2e.delete(s),n.unobserve(s)}}const KFt={some:0,all:1};class YFt extends Y2{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:KFt[a]},o=d=>{const{isIntersecting:h}=d;if(this.isInView===h||(this.isInView=h,i&&!h&&this.hasEnteredView))return;h&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",h);const{onViewportEnter:m,onViewportLeave:x}=this.node.getProps(),g=h?m:x;g&&g(d)};this.stopObserver=WFt(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(ZFt(t,r))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function ZFt({viewport:s={}},{viewport:t={}}={}){return r=>s[r]!==t[r]}const XFt={inView:{Feature:YFt},tap:{Feature:qFt},focus:{Feature:UFt},hover:{Feature:$Ft}},QFt={layout:{ProjectionNode:Zst,MeasureLayout:crt}},JFt={...wFt,...XFt,...zFt,...QFt},Cr=gFt(JFt,yFt),eBt={some:0,all:1};function tBt(s,t,{root:r,margin:n,amount:a="some"}={}){const i=X3e(s),l=new WeakMap,o=d=>{d.forEach(h=>{const m=l.get(h.target);if(h.isIntersecting!==!!m)if(h.isIntersecting){const x=t(h.target,h);typeof x=="function"?l.set(h.target,x):c.unobserve(h.target)}else typeof m=="function"&&(m(h),l.delete(h.target))})},c=new IntersectionObserver(o,{root:r,rootMargin:n,threshold:typeof a=="number"?a:eBt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function sBt(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 tBt(s.current,c,d)},[t,s,r,a,n]),l}function rBt(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 iFe(s){return s.visitor_intent==="buying"&&!s.has_agent}function nBt({token:s}={}){var v;const t=Xi(),r=s||t.token,{data:n,isLoading:a,isError:i}=q6t(r),l=es(),o=(v=n==null?void 0:n.open_houses)==null?void 0:v.id,{data:c}=gt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:j,error:b}=await H.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(b)throw b;return j},enabled:!!o});if(k.useEffect(()=>{if(!o)return;const j=H.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()=>{H.removeChannel(j)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=n.open_houses,h=(c==null?void 0:c.length)||0,m=(c==null?void 0:c.filter(j=>j.visitor_intent==="buying").length)||0,x=(c==null?void 0:c.filter(iFe).length)||0,g=j=>{if(!j)return"";const[b,N]=j.split(":"),S=parseInt(b);return`${S>12?S-12:S||12}:${N} ${S>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(xc,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:x})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cn,{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:Ss(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[g(d.start_time),d.end_time?` – ${g(d.end_time)}`:""]})]}),e.jsx(ti,{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(i5e,{children:c.map((j,b)=>{var T;const N=rBt(j.visitor_intent),S=iFe(j);return e.jsxs(Cr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:b*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${S?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${S?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(T=j.first_name[0])==null?void 0:T.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[j.first_name," ",j.last_name||""]}),S&&e.jsx(Ge,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),j.has_agent&&e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs(Ge,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${N.color}`,children:[N.emoji," ",N.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Ss(new Date(j.created_at),"h:mm a")})]})]})]},j.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(r_,{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 aBt(){const t=sc().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(nBt,{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(htt,{slug:t})}const iBt="#2a4c64",oBt="#406E71";function lBt({dealData:s,agentProfile:t,welcomeMessage:r,isWon:n,branding:a}){var v;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.brand_color)||iBt,o=(a==null?void 0:a.accent_color)||oBt,c=(a==null?void 0:a.logo_url)||null,d=(a==null?void 0:a.cover_photo_url)||null,h=(a==null?void 0:a.tagline)||"Your Real Estate Agent",m=d?{backgroundImage:`linear-gradient(135deg, ${l}d9 0%, ${l}b3 50%, ${o}d9 100%), url(${d})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${l} 0%, ${l} 30%, ${o} 100%)`},x="flex items-center gap-2 px-4 py-2.5 rounded-xl transition-colors",g={backgroundColor:`${l}1a`,color:l};return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative text-white px-4 pt-10 pb-16",style:m,children:[!d&&e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsx("div",{className:"bg-white/95 backdrop-blur-sm rounded-2xl px-4 py-2.5 shadow-lg",children:e.jsx("img",{src:c,alt:"Brand logo",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs("div",{className:"mb-6",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx("span",{className:"text-2xl font-bold text-white/70",children:((v=t.name)==null?void 0:v.charAt(0))||"?"})}),e.jsx("p",{className:"text-sm font-medium text-white/95",children:t.name}),e.jsx("p",{className:"text-xs text-white/60 mt-0.5",children:h})]}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/80 mb-3",children:[e.jsx(Cn,{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(ja,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:i})]}),r&&e.jsx("p",{className:"mt-4 text-sm text-white/80 leading-relaxed max-w-sm mx-auto",children:r})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-8 relative z-10",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:x,style:g,children:[e.jsx(Nn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:x,style:g,children:[e.jsx(Qs,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:x,style:g,children:[e.jsx(tc,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function drt({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=Kg(a,i);if(OIt(a,i),Xv(a)&&!qu(a))return null;let o="from-blue-500 to-cyan-400",c="from-blue-50 to-cyan-50",d="text-blue-900",h="text-blue-600",m="🏡";l<=3?(o="from-emerald-500 to-teal-400",c="from-emerald-50 to-teal-50",d="text-emerald-900",h="text-emerald-600",m="🎉"):l<=7?(o="from-amber-500 to-orange-400",c="from-amber-50 to-orange-50",d="text-amber-900",h="text-amber-600",m="⏳"):l<=14&&(o="from-violet-500 to-purple-400",c="from-violet-50 to-purple-50",d="text-violet-900",h="text-violet-600",m="📅");const x=qu(a)?"Today!":l===1?"1":String(l),g=qu(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}),qu(a)?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:`text-2xl font-bold ${d}`,children:"It's Closing Day!"}),e.jsxs("p",{className:`text-sm ${h} mt-1`,children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","! 🎊"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-baseline justify-center gap-1.5",children:e.jsx("span",{className:`text-5xl font-bold ${d} tabular-nums leading-none`,children:x})}),e.jsx("p",{className:`text-sm font-medium ${h} mt-1.5`,children:g}),l<=7&&e.jsxs("p",{className:`text-xs ${h} opacity-70 mt-1`,children:["You're almost there",r?`, ${r.split(" ")[0]}`:"","!"]})]}),!qu(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 urt({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(Ga,{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 Ul(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 cBt(s,t){const r=Ss(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 dBt(s,t){const r=Ss(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 mrt({targetCloseDate:s,contractDate:t,inspectionDate:r,appraisalDate:n,actualCloseDate:a}){const i=[{label:"Contract Date",date:t,icon:JA,color:"text-blue-600 bg-blue-50"},{label:"Inspection",date:r,icon:fn,color:"text-amber-600 bg-amber-50"},{label:"Appraisal",date:n,icon:Cn,color:"text-purple-600 bg-purple-50"},{label:a?"Closed":"Target Close",date:a||s,icon:rn,color:"text-emerald-600 bg-emerald-50"}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const h=Ul(c);if(d==="google")window.open(cBt(o,h),"_blank");else{const m=dBt(o,h),x=document.createElement("a");x.href=m,x.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,x.click()}};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Key Dates"}),e.jsx("div",{className:"space-y-3",children:i.map(({label:o,date:c,icon:d,color:h})=>{const m=Ul(c),x=Xv(m)&&!qu(m),g=qu(m),v=!x&&!g;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center ${h}`,children:e.jsx(d,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-slate-500",children:o}),e.jsxs("p",{className:`text-sm font-medium ${g?"text-emerald-600":x?"text-slate-400":"text-slate-800"}`,children:[Ss(m,"MMM d, yyyy"),g&&e.jsx("span",{className:"ml-1.5 text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full",children:"Today"})]})]}),x&&e.jsx("span",{className:"text-xs text-slate-400",children:"✓"}),v&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"text-xs text-slate-400 hover:text-blue-500 transition-colors px-1.5 py-1 rounded hover:bg-blue-50",title:"Add to Google Calendar",children:e.jsx(Ub,{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 frt({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 H.storage.from("deal-files").createSignedUrl(n.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(n=>e.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-left group",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0 group-hover:bg-blue-50 transition-colors",children:e.jsx(ln,{className:"w-4 h-4 text-slate-500 group-hover:text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700 truncate",children:n.file_name}),e.jsx("p",{className:"text-xs text-slate-400",children:t(n.file_size)})]}),e.jsx(Xa,{className:"w-4 h-4 text-slate-300 group-hover:text-blue-500 transition-colors"})]},n.id))})]})}function prt({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(Rd,{className:"w-3.5 h-3.5 text-emerald-600"}):e.jsx(Rm,{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:Ss(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 XB=[{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"}],uBt=[{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 hBt(s){return gt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 mBt(){const s=na(),{brokerageId:t}=As();return gt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let r=H.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}),H.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 fBt(){const s=es();return Lt({mutationFn:async t=>{if(t.id){const{id:r,created_at:n,...a}=t,{data:i,error:l}=await H.from("vendors").update(a).eq("id",r).select().single();if(l)throw l;return i}else{const{data:r,error:n}=await H.from("vendors").insert(t).select().single();if(n)throw n;return r}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function xrt(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("vendors").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function pBt(){const s=na(),t=es();return Lt({mutationFn:async({vendorId:r,isVisible:n})=>{if(!s)throw new Error("No user");const{data:a}=await H.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",r).maybeSingle();if(a){const{error:i}=await H.from("agent_vendor_selections").update({is_visible:n}).eq("id",a.id);if(i)throw i}else{const{error:i}=await H.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 xBt(s){return gt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const[{data:t},{data:r}]=await Promise.all([H.from("agent_vendor_selections").select("vendor_id, display_order, stage_filter, is_visible, vendors:vendors!inner(*)").eq("agent_user_id",s.owner_user_id).eq("is_visible",!0),H.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]),n=new Map;return(r||[]).forEach(i=>n.set(i.vendor_id,i.is_visible)),(t||[]).map(i=>({...i.vendors,display_order:i.display_order})).filter(i=>i.is_active&&n.get(i.id)!==!1).sort((i,l)=>(i.display_order||0)-(l.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function gBt(s){try{await H.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 grt(s,t){return gt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:r}=await H.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 H.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 yrt({portalId:s,ownerUserId:t,currentStage:r,brandingColor:n}){const{data:a=[],isLoading:i}=xBt({id:s,owner_user_id:t});if(i||a.length===0)return null;const l=a.filter(x=>!x.stage_filter||x.stage_filter.length===0||!r?!0:x.stage_filter.includes(r));if(l.length===0)return null;const o=l.reduce((x,g)=>((x[g.category]=x[g.category]||[]).push(g),x),{}),c=n||"#406E71",d=x=>{let g=x.action_type,v=null;switch(x.action_type){case"book":v=x.booking_url;break;case"website":v=x.website;break;case"call":v=x.phone?`tel:${x.phone.replace(/[^\d+]/g,"")}`:null;break;case"email":case"quote":v=x.email?`mailto:${x.email}`:null;break}gBt({vendorId:x.id,portalId:s,agentUserId:t,actionTaken:g}),v&&window.open(v,x.action_type==="call"||x.action_type==="email"||x.action_type==="quote"?"_self":"_blank")},h=x=>{switch(x.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},m=x=>{switch(x.action_type){case"book":return e.jsx(rn,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Nn,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(Qs,{className:"w-3.5 h-3.5"});case"website":return e.jsx(gc,{className:"w-3.5 h-3.5"})}};return e.jsxs(Ne,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(jr,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),e.jsx("div",{className:"space-y-4",children:Object.entries(o).map(([x,g])=>{var j;const v=((j=XB.find(b=>b.value===x))==null?void 0:j.label)||x;return e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:v}),e.jsx("div",{className:"space-y-2",children:g.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:b.logo_url?e.jsx("img",{src:b.logo_url,alt:b.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:b.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.name}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:b.description})]}),e.jsxs(G,{size:"sm",onClick:()=>d(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[m(b),e.jsx("span",{className:"ml-1.5 text-xs",children:h(b)})]})]},b.id))})]},x)})}),l.some(x=>x.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:l.filter(x=>x.disclosure_text).map(x=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[x.company||x.name,":"]})," ",x.disclosure_text]},x.id))})]})}function yBt(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 vBt(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 vrt({portalId:s,portalSlug:t,ownerUserId:r,rewardText:n,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,h]=k.useState(!1),m=k.useRef(!1),x=yBt(t);k.useEffect(()=>{m.current||(m.current=!0,H.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 g=async D=>{await H.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:D,user_agent:navigator.userAgent.slice(0,500)})},v=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${x}`,j=async()=>{await navigator.clipboard.writeText(x),h(!0),g("copy_link"),setTimeout(()=>h(!1),2e3)},b=()=>{g("share_sms");const D=encodeURIComponent(v());window.location.href=`sms:?&body=${D}`},N=()=>{g("share_email");const D=encodeURIComponent("A referral you'll thank me for"),B=encodeURIComponent(v());window.location.href=`mailto:?subject=${D}&body=${B}`},S=()=>{g("open_form"),window.open(x,"_blank")},T=a||"Know someone buying or selling?",A=c?vBt(c):null,P=A==null?void 0:A.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),A&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:P?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(li,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:T}),n&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:S,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(Ga,{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(tc,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:N,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Qs,{className:"w-3.5 h-3.5"}),"Email"]}),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:[d?e.jsx(Hn,{className:"w-3.5 h-3.5"}):e.jsx(Ra,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>g("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(Ga,{className:"w-4 h-4 text-slate-400"})]})})]})}function bBt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function _Bt(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 wBt={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. 🎉"}},brt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Bpe(s){return brt.map(t=>{if(t==="Active")return{key:"Active",label:bBt(s),description:_Bt(s)};const r=wBt[t];return{key:t,label:r.label,description:r.description}})}function Zue(s){if(!s)return 0;const t=brt.indexOf(s);return t>=0?t:0}const jBt="#2a4c64",NBt="#406E71";function kBt({portal:s,linkedPortal:t,activePortal:r,activeTab:n,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var Y,ne,de;const d=(l==null?void 0:l.brand_color)||jBt,h=(l==null?void 0:l.accent_color)||NBt,m=(l==null?void 0:l.cover_photo_url)||null,x=(l==null?void 0:l.logo_url)||null,g=(l==null?void 0:l.tagline)||"Your Real Estate Agent",v=r==null?void 0:r.deal_pipeline,j=v==null?void 0:v.deal_pipeline_stages,b=j==null?void 0:j.is_won_stage,N=v==null?void 0:v.deal_type,S=r==null?void 0:r.stage_mapping;let T=Bpe(N);S&&S.length>0&&(T=S.map((ce,ae)=>{var ie,me;return{key:`custom-${ae}`,label:ce.label||((ie=T[ae])==null?void 0:ie.label)||`Stage ${ae+1}`,description:ce.description||((me=T[ae])==null?void 0:me.description)||"",video_url:ce.video_url||void 0}}));const A=S&&S.length>0?Math.min(Zue(j==null?void 0:j.name),T.length-1):Zue(j==null?void 0:j.name),P=T[A],D=P==null?void 0:P.video_url,B=b&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,z=v!=null&&v.property_address?`${v.property_address}, ${v.city||""}, ${v.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,F=!!t,$=(Y=s==null?void 0:s.deal_pipeline)==null?void 0:Y.deal_type,X=(ne=t==null?void 0:t.deal_pipeline)==null?void 0:ne.deal_type,K=ce=>ce==="listing"?"Your Sale":ce==="buy-side"?"Your Purchase":"Transaction",Q=T.length>1?Math.round((A+1)/T.length*100):0;return e.jsxs("div",{className:"min-h-screen relative",style:{background:`radial-gradient(ellipse 80% 60% at 50% -10%, ${d}22, transparent 60%), linear-gradient(180deg, #f8fafc 0%, #ffffff 100%)`},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[480px] opacity-50",style:{background:`radial-gradient(circle at 80% 0%, ${h}33, transparent 50%), radial-gradient(circle at 10% 10%, ${d}33, transparent 55%)`}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[x?e.jsx("div",{className:"bg-white/80 backdrop-blur-sm rounded-xl px-3 py-1.5 shadow-sm border border-white",children:e.jsx("img",{src:x,alt:"Brand",className:"h-7 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold shadow-md",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:e.jsx(jr,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.18em] text-slate-400 font-semibold",children:"Client Portal"}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(Zu,{className:"w-3.5 h-3.5"}),"Secure portal"]})]}),e.jsxs(Cr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl shadow-2xl border border-white/60 mb-8",style:{minHeight:320},children:[e.jsx("div",{className:"absolute inset-0",style:m?{backgroundImage:`linear-gradient(135deg, ${d}e6 0%, ${d}b3 45%, ${h}cc 100%), url(${m})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${d} 0%, ${h} 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"28px 28px"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-10 text-white",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-4 self-start",children:[e.jsx(Cn,{className:"w-3 h-3"}),N==="listing"?"Listing":N==="buy-side"?"Purchase":"Transaction",b&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"•"}),"Complete"]})]}),e.jsx("h1",{className:"text-5xl font-bold tracking-tight leading-[1.05] mb-3 font-serif",children:(v==null?void 0:v.deal_name)||"Your Transaction"}),z&&e.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-base",children:[e.jsx(ja,{className:"w-4 h-4"}),e.jsx("span",{children:z})]}),(r==null?void 0:r.welcome_message)&&e.jsx("p",{className:"mt-5 text-white/85 text-sm leading-relaxed max-w-2xl",children:r.welcome_message})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(SBt,{pct:Q,brand:d,accent:h}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/70 mt-3",children:"Journey progress"}),e.jsxs("p",{className:"text-sm font-medium text-white/95 mt-1",children:["Stage ",A+1," of ",T.length]})]})]})]}),F&&e.jsx("div",{className:"inline-flex gap-1 bg-white/70 backdrop-blur border border-slate-200 rounded-xl p-1 mb-6 shadow-sm",children:["primary","linked"].map(ce=>{const ae=ce==="primary"?$:X;return e.jsx("button",{onClick:()=>a(ce),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${n===ce?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:K(ae)},ce)})}),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(Pw,{children:[e.jsxs("div",{className:"text-center pt-2",children:[i!=null&&i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 rounded-full mx-auto object-cover ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center text-3xl font-bold text-white ring-4 ring-white shadow-lg",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:((de=i==null?void 0:i.name)==null?void 0:de.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:g})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(F1e,{href:`tel:${i.phone}`,icon:Nn,label:"Call",sub:i.phone,brand:d}),(i==null?void 0:i.phone)&&e.jsx(F1e,{href:`sms:${i.phone}`,icon:tc,label:"Text message",brand:d}),(i==null?void 0:i.email)&&e.jsx(F1e,{href:`mailto:${i.email}`,icon:Qs,label:"Email",sub:i.email,brand:d})]})]}),e.jsxs(Pw,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"At a glance"}),e.jsxs("div",{className:"space-y-3",children:[(v==null?void 0:v.target_close_date)&&e.jsx(B1e,{icon:rn,label:"Target close",value:oFe(v.target_close_date),brand:d}),(v==null?void 0:v.contract_date)&&e.jsx(B1e,{icon:cn,label:"Under contract",value:oFe(v.contract_date),brand:d}),e.jsx(B1e,{icon:jr,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:[B&&e.jsx(vrt,{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(drt,{targetCloseDate:v==null?void 0:v.target_close_date,actualCloseDate:v==null?void 0:v.actual_close_date,clientName:r.client_name}),P&&e.jsxs(Pw,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"Where you are now"}),e.jsx(hrt,{currentStage:P,nextStepText:r.next_step_text,nextStepVideoUrl:D||r.next_step_video_url})]}),e.jsxs(Pw,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-4",children:"Your journey"}),e.jsx(urt,{journeyStages:T,currentIndex:A})]}),o&&o.length>0&&e.jsx(Pw,{children:e.jsx(prt,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-6",children:[e.jsx(Pw,{children:e.jsx(mrt,{targetCloseDate:v==null?void 0:v.target_close_date,contractDate:v==null?void 0:v.contract_date,inspectionDate:r.inspection_date,appraisalDate:r.appraisal_date,actualCloseDate:v==null?void 0:v.actual_close_date})}),c&&c.length>0&&e.jsx(Pw,{children:e.jsx(frt,{documents:c})}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&e.jsx(Pw,{children:e.jsx(yrt,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:j==null?void 0:j.name})})]})]})]})]})}function Pw({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 F1e({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 B1e({icon:s,label:t,value:r,brand:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${n}14`,color:n},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-slate-400 uppercase tracking-wide",children:t}),e.jsx("p",{className:"text-sm font-semibold text-slate-800 truncate",children:r})]})]})}function SBt({pct:s,brand:t,accent:r}){const l=2*Math.PI*74,o=l-s/100*l,c="pg-"+t.replace("#","");return e.jsxs("div",{className:"relative",style:{width:160,height:160},children:[e.jsxs("svg",{width:160,height:160,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#ffffff",stopOpacity:"0.95"}),e.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:"0.9"})]})}),e.jsx("circle",{cx:160/2,cy:160/2,r:74,stroke:"rgba(255,255,255,0.18)",strokeWidth:12,fill:"none"}),e.jsx(Cr.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 oFe(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 CBt({portal:s,dealData:t,agentProfile:r,customQuestions:n,deviceFingerprint:a,onComplete:i}){var v,j;const[l,o]=k.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((j=s.client_name)==null?void 0:j.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=k.useState({}),[h,m]=k.useState(!1),x=Lt({mutationFn:async()=>{const{error:b}=await H.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:h&&l.spouse_first_name||null,spouse_last_name:h&&l.spouse_last_name||null,spouse_email:h&&l.spouse_email||null,spouse_phone:h&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),ue.error("Something went wrong. Please try again.")}}),g=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"}),g&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ja,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:g.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),x.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"First Name *"}),e.jsx(ke,{required:!0,value:l.first_name,onChange:b=>o(N=>({...N,first_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(ke,{value:l.last_name,onChange:b=>o(N=>({...N,last_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(ke,{type:"email",value:l.email,onChange:b=>o(N=>({...N,email:b.target.value})),className:"mt-1 rounded-xl",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(ke,{type:"tel",value:l.phone,onChange:b=>o(N=>({...N,phone:b.target.value})),className:"mt-1 rounded-xl",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(b=>e.jsx("button",{type:"button",onClick:()=>o(N=>({...N,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(b=>e.jsx("button",{type:"button",onClick:()=>o(N=>({...N,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),n.map(b=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs text-slate-600",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(ke,{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 rounded-xl"}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm h-10",children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(N=>e.jsx("option",{value:N,children:N},N))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(N=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:N})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===N?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:N},N))})]},b.id)),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(N=>({...N,notes:b.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>m(!h),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:h?"− Remove spouse/partner":"+ Add spouse/partner"}),h&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"First Name"}),e.jsx(ke,{value:l.spouse_first_name,onChange:b=>o(N=>({...N,spouse_first_name:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(ke,{value:l.spouse_last_name,onChange:b=>o(N=>({...N,spouse_last_name:b.target.value})),className:"mt-1 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(ke,{type:"email",value:l.spouse_email,onChange:b=>o(N=>({...N,spouse_email:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(ke,{type:"tel",value:l.spouse_phone,onChange:b=>o(N=>({...N,spouse_phone:b.target.value})),className:"mt-1 rounded-xl"})]})]})]}),e.jsx(G,{type:"submit",disabled:x.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:x.isPending?"Submitting...":"Access My Portal"})]})]})}function TBt(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 _rt(){const s=na();return gt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function EBt(s){return gt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 ABt(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 wrt(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 H.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=H.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function MBt(s,t){return gt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:r,error:n}=await H.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 IBt(s){return gt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 jrt({slug:s}){var ae,ie,me,oe,ge,be;const[t,r]=k.useState(!1),[n,a]=k.useState("primary"),[i]=k.useState(()=>{const Oe=`portal_fp_${s}`;let Me=localStorage.getItem(Oe);return Me||(Me=localStorage.getItem("portal_fp"),Me?localStorage.setItem(Oe,Me):(Me=crypto.randomUUID(),localStorage.setItem(Oe,Me),localStorage.setItem("portal_fp",Me))),Me});k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=MBt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:h}=IBt(d),m=(ae=l==null?void 0:l.deal_pipeline)==null?void 0:ae.owner_user_id,{data:x}=gt({queryKey:["portal-stages",m],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",m).order("sort_order",{ascending:!0});if(Me)throw Me;return Oe},enabled:!!m}),{data:g}=gt({queryKey:["portal-agent",m],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("profiles").select("id, name, avatar_url, phone, email").eq("id",m).single();if(Me)throw Me;return Oe},enabled:!!m}),{data:v}=EBt(m),j=n==="linked"&&h?h:l,b=j==null?void 0:j.id,N=TBt(v,j==null?void 0:j.branding_override),{data:S}=gt({queryKey:["portal-updates-public",b],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("portal_updates").select("*").eq("portal_id",b).order("created_at",{ascending:!1});if(Me)throw Me;return Oe},enabled:!!b}),T=(ie=j==null?void 0:j.deal_pipeline)==null?void 0:ie.id,{data:A}=gt({queryKey:["portal-documents",T],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("deal_files").select("*").eq("deal_id",T).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Me)throw Me;return Oe},enabled:!!T}),P=l==null?void 0:l.id,D=P?`portal_onboarded_${P}_${i}`:null,B=D?localStorage.getItem(D)==="1":!1,{data:z,isLoading:F}=gt({queryKey:["portal-onboarding-check",P,i],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("portal_onboarding_submissions").select("id").eq("portal_id",P).eq("device_fingerprint",i).maybeSingle();if(Me)throw Me;return Oe&&D&&localStorage.setItem(D,"1"),Oe},enabled:!!P&&!!(l!=null&&l.require_onboarding)&&!B,staleTime:5*60*1e3}),$=!!(l!=null&&l.require_onboarding)&&!B&&!z&&!t,{data:X}=gt({queryKey:["portal-custom-questions-public",m],queryFn:async()=>{const{data:Oe,error:Me}=await H.from("portal_custom_questions").select("*").eq("owner_user_id",m).eq("is_active",!0).order("sort_order",{ascending:!0});if(Me)throw Me;return Oe},enabled:!!m&&$}),K=B||!!z||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!B&&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 Oe=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(CBt,{portal:l,dealData:Oe,agentProfile:g,customQuestions:X||[],deviceFingerprint:i,onComplete:()=>{D&&localStorage.setItem(D,"1"),r(!0)}})})}const Q=(me=l==null?void 0:l.deal_pipeline)==null?void 0:me.deal_type,Y=(oe=h==null?void 0:h.deal_pipeline)==null?void 0:oe.deal_type,ne=!!h,de=Oe=>Oe==="listing"?"Your Sale":Oe==="buy-side"?"Your Purchase":"Transaction",ce=Oe=>Oe==="listing"?e.jsx(Cn,{className:"w-3.5 h-3.5"}):e.jsx(gp,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(kBt,{portal:l,linkedPortal:h,activePortal:j,activeTab:n,onTabChange:a,agentProfile:g,branding:N,updates:S,documents:A})}),e.jsxs("div",{className:"lg:hidden min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsx(lBt,{dealData:j==null?void 0:j.deal_pipeline,agentProfile:g,welcomeMessage:(j==null?void 0:j.welcome_message)||N.welcome_message,isWon:(be=(ge=j==null?void 0:j.deal_pipeline)==null?void 0:ge.deal_pipeline_stages)==null?void 0:be.is_won_stage,branding:N}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-6",children:[ne&&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:[ce(Q),de(Q)]}),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:[ce(Y),de(Y)]})]}),e.jsx(PBt,{portal:j,updates:S,documents:A,agentProfile:g}),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(Zu,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs",children:"Secure Client Portal"})]}),g&&e.jsxs("p",{className:"text-xs text-slate-400",children:["Managed by ",e.jsx("span",{className:"font-medium text-slate-500",children:g.name})]}),e.jsx("p",{className:"text-[10px] text-slate-300",children:"Powered by ReLevelUp"})]})]})]})]})}function PBt({portal:s,updates:t,documents:r,agentProfile:n}){const a=s,i=a==null?void 0:a.deal_pipeline,l=i==null?void 0:i.deal_pipeline_stages,o=l==null?void 0:l.is_won_stage,c=i==null?void 0:i.deal_type,d=s.stage_mapping;let h=Bpe(c);d&&d.length>0&&(h=d.map((j,b)=>{var N,S;return{key:`custom-${b}`,label:j.label||((N=h[b])==null?void 0:N.label)||`Stage ${b+1}`,description:j.description||((S=h[b])==null?void 0:S.description)||"",video_url:j.video_url||void 0}}));const m=d&&d.length>0?Math.min(Zue(l==null?void 0:l.name),h.length-1):Zue(l==null?void 0:l.name),x=h[m],g=x==null?void 0:x.video_url,v=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[v&&e.jsx(vrt,{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(drt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(urt,{journeyStages:h,currentIndex:m}),x&&e.jsx(hrt,{currentStage:x,nextStepText:s.next_step_text,nextStepVideoUrl:g||s.next_step_video_url}),e.jsx(mrt,{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(frt,{documents:r}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(yrt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(prt,{updates:t})]})}function Nrt({slug:s}){const t=Xi(),r=s||t.slug,[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState("buying"),[T,A]=k.useState("");k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:P,isLoading:D,error:B}=gt({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:$,error:X}=await H.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(X)throw X;return $},enabled:!!r}),{data:z}=gt({queryKey:["portal-referral-agent",P==null?void 0:P.owner_user_id],queryFn:async()=>{const{data:$}=await H.from("profiles").select("id, name, avatar_url").eq("id",P.owner_user_id).single();return $},enabled:!!(P!=null&&P.owner_user_id)}),F=async $=>{if($.preventDefault(),!P||!m.trim()){ue.error("Please enter your friend's name");return}if(!g.trim()&&!j.trim()){ue.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:X}=await H.from("portal_referrals").insert({portal_id:P.id,owner_user_id:P.owner_user_id,referrer_name:o.trim()||P.client_name||null,referrer_email:d.trim()||null,friend_name:m.trim(),friend_email:g.trim()||null,friend_phone:j.trim()||null,friend_interest:N,friend_message:T.trim()||null});if(X)throw X;l(!0)}catch(X){ue.error(X.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(Vs,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):B||!P||!P.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(Hn,{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 ",(z==null?void 0:z.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(wa,{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:[z!=null&&z.avatar_url?e.jsx("img",{src:z.avatar_url,alt:z.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(li,{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(li,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:P.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(z==null?void 0:z.name)||"your agent"," someone you trust."]}),P.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:P.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit:F,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"friend_name",value:m,onChange:$=>x($.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(ke,{id:"friend_email",type:"email",value:g,onChange:$=>v($.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(ke,{id:"friend_phone",type:"tel",value:j,onChange:$=>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(he,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map($=>e.jsx("button",{type:"button",onClick:()=>S($.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${N===$.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:$.l},$.v))})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:T,onChange:$=>A($.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(ke,{id:"referrer_name",value:o,onChange:$=>c($.target.value),placeholder:P.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(ke,{id:"referrer_email",type:"email",value:d,onChange:$=>h($.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(li,{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 LBt(){const t=sc().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(Nrt,{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(jrt,{slug:t})}const $2e="levelup_affiliate_ref",DBt=30,RBt=()=>{const[s]=Lc();k.useEffect(()=>{const t=s.get("ref");if(t){const r={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem($2e,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",t)}},[s])},OBt=()=>{try{const s=localStorage.getItem($2e);if(!s)return null;const t=JSON.parse(s),r=DBt*24*60*60*1e3;return Date.now()-t.timestamp>r?(localStorage.removeItem($2e),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},Xue="/assets/levelup-logo-header-_ZX7DvlA.png",FBt="/assets/scale-your-team-ku4MPatU.png";function BBt({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(js,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(Sa,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Fr,{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 mh={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"},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"]},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"]}},zBt=[{icon:mf,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:rn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:tc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ln,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:li,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],$Bt=[{icon:fr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:jr,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Nn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Eh,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ja,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ao,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:hi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Xu,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],UBt=[{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."}],qBt=()=>{const{user:s,loading:t}=As(),r=vr(),[n]=Lc();k.useEffect(()=>{const B=window.location.host==="listings.relevelup.com",z=window.location.pathname==="/";if(B&&z){r("/public/listings",{replace:!0});return}},[r]);const[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=(B,z=!1)=>{o({tier:B,skipTrial:z}),d(!0)};RBt(),k.useEffect(()=>{const B=window.location.host==="listings.relevelup.com",z=location.pathname.startsWith("/public/");!t&&s&&!B&&!z&&r("/dashboard")},[s,t,r,location.pathname]),k.useEffect(()=>{n.get("canceled")==="true"&&ue.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const P=async(B,z=!1)=>{if(!h){ue.error("Please enter your email address");return}if(!x.trim()){ue.error("Please enter your full name");return}N(!0),i(B+(z?"_direct":""));const F=OBt();try{const{data:$,error:X}=await H.functions.invoke("create-checkout",{body:{tier:B,email:h,name:x.trim(),couponCode:v.trim()||void 0,skipTrial:z,referralCode:F}});if(X)throw X;if($!=null&&$.url)window.open($.url,"_blank","noopener,noreferrer"),ue.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch($){console.error("Checkout error:",$),ue.error($.message||"Failed to start checkout. Please try again.")}finally{N(!1),i(null),d(!1),o(null)}},D=()=>{l&&P(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:Xue,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(G,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var B;return(B=document.getElementById("features"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(G,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var B;return(B=document.getElementById("pricing"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(G,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(G,{size:"lg",onClick:()=>{var B;return(B=document.getElementById("free-trial"))==null?void 0:B.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(Ga,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(G,{size:"lg",variant:"outline",onClick:()=>{var B;return(B=document.getElementById("features"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(G,{size:"lg",variant:"outline",onClick:()=>{var B;return(B=document.getElementById("brokerage"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Sa,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(G,{size:"lg",onClick:()=>{var B;return(B=document.getElementById("pricing"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Bi,{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:zBt.map((B,z)=>e.jsxs(Ne,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ot,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(B.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(zt,{className:"text-xl font-sans",children:B.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:B.description})})]},z))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(jr,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:$Bt.map((B,z)=>e.jsxs(Ne,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ot,{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(B.icon,{className:"w-6 h-6 text-white"})}),e.jsx(zt,{className:"text-lg font-semibold text-white",children:B.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:B.description})})]},z))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(G,{size:"lg",onClick:()=>{var B;return(B=document.getElementById("pricing"))==null?void 0:B.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(Ga,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[e.jsx(Sa,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((B,z)=>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(Hn,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:B})]},z))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(G,{size:"lg",onClick:()=>{var B;return(B=document.getElementById("pricing"))==null?void 0:B.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(ya,{className:"ml-2 w-5 h-5"})]}),e.jsxs(G,{size:"lg",variant:"outline",onClick:()=>T(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(rn,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:FBt,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:UBt.map((B,z)=>e.jsx(Ne,{className:"bg-muted/30 border-0",children:e.jsxs(De,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(F=>e.jsx(Qn,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},F))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',B.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:B.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:B.role})]})]})},z))})]})}),e.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[e.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",e.jsx("span",{className:"italic",children:"Today"})]}),e.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),e.jsx("div",{className:"pt-4",children:e.jsxs(G,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>A("individual_agent"),children:["Start Free Trial",e.jsx(Ga,{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(Ne,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ot,{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(Bi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(zt,{className:"text-xl font-sans",children:mh.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:mh.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:mh.individual_agent.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:mh.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(cn,{className:"w-4 h-4"}),mh.individual_agent.trial]})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:mh.individual_agent.features.map((B,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Hn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:B})]},z))})}),e.jsxs(HO,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(G,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(Ne,{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(Ot,{className:"pb-4 pt-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(Sa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-xl font-sans",children:mh.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mh.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:mh.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:mh.brokerage_under_25.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:mh.brokerage_under_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:mh.brokerage_under_25.features.map((B,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Hn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:B})]},z))})}),e.jsx(HO,{className:"pt-4",children:e.jsx(G,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(Ne,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ot,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Sa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-xl font-sans",children:mh.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mh.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:mh.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:mh.brokerage_over_25.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:mh.brokerage_over_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:mh.brokerage_over_25.features.map((B,z)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Hn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:B})]},z))})}),e.jsx(HO,{className:"pt-4",children:e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(G,{size:"lg",onClick:()=>{var B;return(B=document.getElementById("pricing"))==null?void 0:B.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(Ga,{className:"ml-2 w-5 h-5"})]}),e.jsx(G,{size:"lg",onClick:()=>r("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:Xue,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(BBt,{open:S,onOpenChange:T}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Fr,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":(l==null?void 0:l.tier)==="brokerage_under_25"?"Subscribe to Brokerage (Under 25 Agents)":"Subscribe to Brokerage (Over 25 Agents)"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"dialog-name",type:"text",placeholder:"John Smith",value:x,onChange:B=>g(B.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:h,onChange:B=>m(B.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(ke,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:v,onChange:B=>j(B.target.value),className:"mt-1"})]})]}),e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:D,disabled:b,children:b?"Loading...":"Continue to Checkout"})]})})]})},lFe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," We use your information to deliver the services you requested, send transactional and informational messages, and improve your experience."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),cFe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp Consulting Group, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including but not limited to account notifications, service updates, AI concierge replies, and customer support communications. Message frequency varies. Message and data rates may apply."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["Your mobile phone number and opt-in data will not be shared with or sold to third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),VBt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(il,{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"})]})]})]})]})})]}),dFe="I agree to receive recurring SMS/MMS messages from LevelUp Consulting Group, including AI concierge replies, account notifications, service updates, and customer support communications. Message frequency varies. Message & data rates may apply. Reply STOP to opt out at any time, or HELP for assistance.",HBt=M_({name:oo().trim().min(1,"Name is required").max(200),phone:oo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:oo().trim().email("Enter a valid email").max(320).optional().or(Ng(""))});function GBt(){const[s,t]=k.useState(""),[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState(!1),x=async g=>{var b;if(g.preventDefault(),!l){ue.error("Please check the consent box to opt in.");return}const v=HBt.safeParse({name:s,phone:r,email:a});if(!v.success){ue.error(((b=v.error.issues[0])==null?void 0:b.message)??"Please check your inputs.");return}d(!0);const{error:j}=await H.from("sms_opt_in_consents").insert({name:v.data.name,phone:v.data.phone,email:v.data.email||null,consent_text:dFe,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),j){ue.error("Something went wrong. Please try again.");return}m(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(il,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS messages from LevelUp Consulting Group's AI concierge. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://tile-portal.lovable.app/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(bi,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp Consulting Group — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Join the LevelUp SMS Concierge. Text our AI assistant from your phone to get help with social posts, listing info, reminders, and more."})]}),h?e.jsxs(Ne,{className:"p-8 text-center",children:[e.jsx(Mn,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["Text our concierge at"," ",e.jsx("span",{className:"font-semibold text-foreground",children:"+1 (888) 593-6381"})," ","from your mobile to get started. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(Ne,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:x,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Full Name *"}),e.jsx(ke,{id:"name",value:s,onChange:g=>t(g.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(ke,{id:"phone",type:"tel",value:r,onChange:g=>n(g.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email (optional)"}),e.jsx(ke,{id:"email",type:"email",value:a,onChange:g=>i(g.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ei,{id:"consent",checked:l,onCheckedChange:g=>o(g===!0),className:"mt-0.5"}),e.jsx(he,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:dFe})]})}),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(Kn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Kn,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," AI concierge replies, account notifications, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"Your mobile phone number and opt-in data will not be shared with or sold to third parties for marketing or promotional purposes."})]}),e.jsx(G,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(a0,{className:"w-3.5 h-3.5"}),"Secure consent record stored for compliance."]})]})}),e.jsx("footer",{className:"text-center mt-8 text-xs text-muted-foreground",children:e.jsxs("p",{children:["LevelUp Consulting Group · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const WBt=M_({email:oo().email("Invalid email address"),password:oo().min(6,"Password must be at least 6 characters")}),KBt=()=>{const{signIn:s,user:t}=As(),r=vr(),[n,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(!1);k.useEffect(()=>{if(t){const j=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),r(j)}},[t,r]);const g=async j=>{j.preventDefault(),l({}),a(!0);const b=new FormData(j.currentTarget),N=b.get("email"),S=b.get("password");try{WBt.parse({email:N,password:S}),await s(N,S)}catch(T){if(T instanceof n1){const A={};T.errors.forEach(P=>{P.path[0]&&(A[P.path[0]]=P.message)}),l(A)}}finally{a(!1)}},v=async()=>{if(!o){ue.error("Please enter your email address");return}h(!0);try{const{error:j}=await H.functions.invoke("send-password-reset",{body:{email:o,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(j)throw j;ue.success("Password reset email sent! Check your inbox."),x(!1),c("")}catch(j){ue.error(j.message||"Failed to send reset email")}finally{h(!1)}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:e.jsxs("div",{className:"absolute inset-0 opacity-30",children:[e.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),e.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[e.jsx("header",{className:"p-6",children:e.jsxs(Kn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(wa,{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:t3e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(Ne,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ot,{className:"space-y-1 text-center pb-4",children:[e.jsx(zt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Nr,{className:"text-gray-600",children:"Sign in to access your dashboard"})]}),e.jsx(De,{children:e.jsxs("form",{onSubmit:g,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(ke,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.email&&e.jsx("p",{className:"text-sm text-red-600",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(ke,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.password&&e.jsx("p",{className:"text-sm text-red-600",children:i.password})]}),e.jsx(G,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:n,children:n?"Signing in...":"Sign In"}),e.jsxs(vs,{open:m,onOpenChange:x,children:[e.jsx(Ni,{asChild:!0,children:e.jsx(G,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(ys,{className:"bg-white",children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Fr,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(ke,{id:"reset-email",type:"email",placeholder:"your@email.com",value:o,onChange:j=>c(j.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(G,{onClick:v,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:d,children:d?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(Kn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},YBt=()=>{const[s]=Lc(),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(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{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(mi,{className:"w-10 h-10 text-green-500"})}),e.jsx(zt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Nr,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(De,{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(Qs,{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."})})]})]})})},krt=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 H.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=H.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 H.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=H.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);r(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},Srt=async s=>{const t=new Map;return await Promise.all(s.map(async r=>{try{const{data:n}=await H.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:a}=H.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);t.set(r,a.publicUrl)}}catch{}})),t},ZBt=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 H.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),r(m=>({...m,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const m=new Date().getTime(),x=new Date(d).getTime(),g=Math.ceil((x-m)/(1e3*60*60*24)),v=g<=0;r({isTrial:!0,isExpired:v,expiresAt:d,daysLeft:v?0:g,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},Crt=()=>{const{data:s,isLoading:t}=gt({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:a}=await H.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")}},uFe="community_last_seen_post_at";function XBt(){const{user:s}=As(),t=sc(),[r,n]=k.useState(0),[a,i]=k.useState(null);k.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${uFe}_${s.id}`);i(o)},[s]),k.useEffect(()=>{if(!s)return;(async()=>{let c=H.from("community_posts").select("id",{count:"exact",head:!0});a&&(c=c.gt("created_at",a));const{data:d}=await H.from("profiles").select("brokerage_id").eq("id",s.id).single(),{count:h,error:m}=await c;!m&&h!==null&&n(h)})()},[s,a]),k.useEffect(()=>{if(!s)return;const o=H.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const h=t.pathname==="/community";h||n(j=>j+1);const{data:m}=await H.from("profiles").select("name").eq("id",d.user_id).single(),x=(m==null?void 0:m.name)||"Someone",g=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),v=g.length>50?g.substring(0,50)+"...":g;h||ue("New Community Post",{description:`${x}: ${v}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{H.removeChannel(o)}},[s,t.pathname]);const l=k.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${uFe}_${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 QBt(){const{isAdmin:s}=As(),{data:t=0}=gt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await H.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 zpe="Collapsible",[JBt]=yd(zpe),[ezt,c5e]=JBt(zpe),Trt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Lh({prop:n,defaultProp:a??!1,onChange:l,caller:zpe});return e.jsx(ezt,{scope:r,disabled:i,contentId:Qu(),open:c,onOpenToggle:k.useCallback(()=>d(h=>!h),[d]),children:e.jsx(pn.div,{"data-state":u5e(c),"data-disabled":i?"":void 0,...o,ref:t})})});Trt.displayName=zpe;var Ert="CollapsibleTrigger",Art=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,...n}=s,a=c5e(Ert,r);return e.jsx(pn.button,{type:"button","aria-controls":a.open?a.contentId:void 0,"aria-expanded":a.open||!1,"data-state":u5e(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...n,ref:t,onClick:Or(s.onClick,a.onOpenToggle)})});Art.displayName=Ert;var d5e="CollapsibleContent",Mrt=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=c5e(d5e,s.__scopeCollapsible);return e.jsx(qd,{present:r||a.open,children:({present:i})=>e.jsx(tzt,{...n,ref:t,present:i})})});Mrt.displayName=d5e;var tzt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,present:n,children:a,...i}=s,l=c5e(d5e,r),[o,c]=k.useState(n),d=k.useRef(null),h=Qa(t,d),m=k.useRef(0),x=m.current,g=k.useRef(0),v=g.current,j=l.open||o,b=k.useRef(j),N=k.useRef(void 0);return k.useEffect(()=>{const S=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(S)},[]),fd(()=>{const S=d.current;if(S){N.current=N.current||{transitionDuration:S.style.transitionDuration,animationName:S.style.animationName},S.style.transitionDuration="0s",S.style.animationName="none";const T=S.getBoundingClientRect();m.current=T.height,g.current=T.width,b.current||(S.style.transitionDuration=N.current.transitionDuration,S.style.animationName=N.current.animationName),c(n)}},[l.open,n]),e.jsx(pn.div,{"data-state":u5e(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!j,...i,ref:h,style:{"--radix-collapsible-content-height":x?`${x}px`:void 0,"--radix-collapsible-content-width":v?`${v}px`:void 0,...s.style},children:j&&a})});function u5e(s){return s?"open":"closed"}var szt=Trt;const bx=szt,_x=Art,wx=Mrt,rzt="/assets/levelup-logo-Eif24dqY.png",nzt="/assets/levelup-logo-icon-C-7iromj.png",azt="/assets/levelup-logo-mobile-B9skSjUG.png";var QB=s=>s.type==="checkbox",G4=s=>s instanceof Date,Zh=s=>s==null;const Irt=s=>typeof s=="object";var dd=s=>!Zh(s)&&!Array.isArray(s)&&Irt(s)&&!G4(s),U2e=s=>dd(s)&&s.target?QB(s.target)?s.target.checked:s.target.value:s,Prt=(s,t)=>t.split(".").some((r,n,a)=>!isNaN(Number(r))&&s.has(a.slice(0,n).join("."))),Lrt=s=>{const t=s.constructor&&s.constructor.prototype;return dd(t)&&t.hasOwnProperty("isPrototypeOf")},$pe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Sd(s){if(s instanceof Date)return new Date(s);const t=typeof FileList<"u"&&s instanceof FileList;if($pe&&(s instanceof Blob||t))return s;const r=Array.isArray(s);if(!r&&!(dd(s)&&Lrt(s)))return s;const n=r?[]:Object.create(Object.getPrototypeOf(s));for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&(n[a]=Sd(s[a]));return n}const Jw={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Gy={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Dy={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z1e="form",Drt="root",Rrt=["__proto__","constructor","prototype"];var JB=s=>/^\w*$/.test(s),Ec=s=>s===void 0,Upe=s=>s.split(/[.[\]'"]/g).filter(Boolean),Pn=(s,t,r)=>{if(!t||!dd(s))return r;const n=JB(t)?[t]:Upe(t);if(n.some(i=>Rrt.includes(i)))return r;const a=n.reduce((i,l)=>Zh(i)?void 0:i[l],s);return Ec(a)||a===s?Ec(s[t])?r:s[t]:a},nx=s=>typeof s=="boolean",Mm=s=>typeof s=="function",vl=(s,t,r)=>{let n=-1;const a=JB(t)?[t]:Upe(t),i=a.length,l=i-1;for(;++nwt.useContext(h5e);var Ort=(s,t,r,n=!0)=>{const a={};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==Gy.all&&(t._proxyFormState[l]=!n||Gy.all),r&&(r[l]=!0),s[l]}});return a};const f5e=$pe?wt.useLayoutEffect:wt.useEffect;function izt(s){const t=m5e(),{control:r=t,disabled:n,name:a,exact:i}=s||{},[l,o]=wt.useState(()=>({...r._formState,defaultValues:r._defaultValues})),c=wt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return f5e(()=>r._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!n&&o({...r._formState,...d,defaultValues:r._defaultValues})}}),[a,n,i]),wt.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),wt.useMemo(()=>Ort(l,r,c.current,!1),[l,r])}var Pm=s=>typeof s=="string",q2e=(s,t,r,n,a)=>Pm(s)?(n&&t.watch.add(s),Pn(r,s,a)):Array.isArray(s)?s.map(i=>(n&&t.watch.add(i),Pn(r,i))):(n&&(t.watchAll=!0),r),V2e=s=>Zh(s)||!Irt(s);const hFe=(s,t)=>t.length===0&&!Array.isArray(s)&&!Lrt(s);function ax(s,t,r=new WeakSet){if(s===t)return!0;if(V2e(s)||V2e(t))return Object.is(s,t);if(G4(s)&&G4(t))return Object.is(s.getTime(),t.getTime());const n=Object.keys(s),a=Object.keys(t);if(n.length!==a.length)return!1;if(hFe(s,n)||hFe(t,a))return Object.is(s,t);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(!(i in t))return!1;if(i!=="ref"){const o=t[i];if(G4(l)&&G4(o)||(dd(l)||Array.isArray(l))&&(dd(o)||Array.isArray(o))?!ax(l,o,r):!Object.is(l,o))return!1}}return!0}function ozt(s){const t=m5e(),{control:r=t,name:n,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=wt.useRef(a),d=wt.useRef(o),h=wt.useRef(void 0),m=wt.useRef(r),x=wt.useRef(n);d.current=o;const[g,v]=wt.useState(()=>{const A=r._getWatch(n,c.current);return d.current?d.current(A):A}),j=wt.useCallback(A=>{const P=q2e(n,r._names,A||r._formValues,!1,c.current);return d.current?d.current(P):P},[r._formValues,r._names,n]),b=wt.useCallback(A=>{if(!i){const P=q2e(n,r._names,A||r._formValues,!1,c.current);if(d.current){const D=d.current(P);ax(D,h.current)||(v(D),h.current=D)}else v(P)}},[r._formValues,r._names,i,n]);f5e(()=>((m.current!==r||!ax(x.current,n))&&(m.current=r,x.current=n,b()),r._subscribe({name:n,formState:{values:!0},exact:l,callback:A=>{b(A.values)}})),[r,l,n,b]),wt.useEffect(()=>r._removeUnmounted());const N=m.current!==r,S=x.current,T=wt.useMemo(()=>{if(i)return null;const A=!N&&!ax(S,n);return N||A?j():null},[i,N,n,S,j]);return T!==null?T:g}function lzt(s){const t=m5e(),{name:r,disabled:n,control:a=t,shouldUnregister:i,defaultValue:l,exact:o=!0}=s,c=Prt(a._names.array,r),d=wt.useMemo(()=>Pn(a._formValues,r,Pn(a._defaultValues,r,l)),[a,r,l]),h=ozt({control:a,name:r,defaultValue:d,exact:o}),m=izt({control:a,name:r,exact:o}),x=wt.useRef(s),g=wt.useRef(a.register(r,{...s.rules,value:h,...nx(s.disabled)?{disabled:s.disabled}:{}}));x.current=s;const v=wt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Pn(m.errors,r)},isDirty:{enumerable:!0,get:()=>!!Pn(m.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!Pn(m.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!Pn(m.validatingFields,r)},error:{enumerable:!0,get:()=>Pn(m.errors,r)}}),[m,r]),j=wt.useCallback(T=>{const A=U2e(T);Pn(a._fields,r)||(g.current=a.register(r,{...x.current.rules,value:A})),g.current.onChange({target:{value:U2e(T),name:r},type:Jw.CHANGE})},[r,a]),b=wt.useCallback(()=>g.current.onBlur({target:{value:Pn(a._formValues,r),name:r},type:Jw.BLUR}),[r,a._formValues]),N=wt.useCallback(T=>{const A=Pn(a._fields,r);A&&A._f&&T&&(A._f.ref={focus:()=>Mm(T.focus)&&T.focus(),select:()=>Mm(T.select)&&T.select(),setCustomValidity:P=>Mm(T.setCustomValidity)&&T.setCustomValidity(P),reportValidity:()=>Mm(T.reportValidity)&&T.reportValidity()})},[a._fields,r]),S=wt.useMemo(()=>({name:r,value:h,...nx(n)||m.disabled?{disabled:m.disabled||n}:{},onChange:j,onBlur:b,ref:N}),[r,n,m.disabled,j,b,N,h]);return wt.useEffect(()=>{const T=a._options.shouldUnregister||i;a.register(r,{...x.current.rules,...nx(x.current.disabled)?{disabled:x.current.disabled}:{}});const A=(P,D)=>{const B=Pn(a._fields,P);B&&B._f&&(B._f.mount=D)};if(A(r,!0),T){const P=Sd(Pn(i?a._defaultValues:a._options.values||a._defaultValues,r,Pn(a._options.defaultValues,r,x.current.defaultValue)));vl(a._defaultValues,r,P),Ec(Pn(a._formValues,r))&&vl(a._formValues,r,P)}return!c&&a.register(r),()=>{(c?T&&!a._state.action:T)?a.unregister(r):A(r,!1)}},[r,a,c,i]),wt.useEffect(()=>{a._setDisabledField({disabled:n,name:r})},[n,r,a]),wt.useMemo(()=>({field:S,formState:m,fieldState:v}),[S,m,v])}const czt=s=>s.render(lzt(s)),p5e=wt.createContext(null);p5e.displayName="HookFormContext";const dzt=()=>wt.useContext(p5e),uzt=({children:s,watch:t,getValues:r,getFieldState:n,setError:a,clearErrors:i,setValue:l,setValues:o,trigger:c,formState:d,resetField:h,reset:m,handleSubmit:x,unregister:g,control:v,register:j,setFocus:b,subscribe:N})=>{const S=wt.useMemo(()=>({watch:t,getValues:r,getFieldState:n,setError:a,clearErrors:i,setValue:l,setValues:o,trigger:c,formState:d,resetField:h,reset:m,handleSubmit:x,unregister:g,control:v,register:j,setFocus:b,subscribe:N}),[i,v,d,n,r,x,j,m,h,a,b,l,o,N,c,g,t]);return wt.createElement(p5e.Provider,{value:S},wt.createElement(h5e.Provider,{value:S.control},s))};var Frt=(s,t,r,n,a)=>t?{...r[s],types:{...r[s]&&r[s].types?r[s].types:{},[n]:a||!0}}:{},Brt=s=>Array.isArray(s)?s.filter(Boolean):[],jde=s=>Array.isArray(s)?s:[s],mFe=()=>{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=[]}}};function zrt(s,t){const r={};for(const n in s)if(s.hasOwnProperty(n)){const a=s[n],i=t[n];if(a&&dd(a)&&i){const l=zrt(a,i);dd(l)&&(r[n]=l)}else s[n]&&(r[n]=i)}return r}var gh=s=>dd(s)&&!Object.keys(s).length,x5e=s=>s.type==="file",Que=s=>{if(!$pe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},$rt=s=>s.type==="select-multiple",g5e=s=>s.type==="radio",hzt=s=>g5e(s)||QB(s),$1e=s=>Que(s)&&s.isConnected;function mzt(s,t){const r=t.slice(0,-1).length;let n=0;for(;n{for(const t in s)if(Mm(s[t]))return!0;return!1};function Urt(s){return Array.isArray(s)||dd(s)&&!pzt(s)}function H2e(s,t={}){for(const r in s){const n=s[r];Urt(n)?(t[r]=Array.isArray(n)?[]:{},H2e(n,t[r])):Ec(n)||(t[r]=!0)}return t}function G2e(s){if(s!==!1){if(s===!0)return!0;if(Array.isArray(s)){const t=s.map(r=>G2e(r));return t.some(r=>r!==void 0)?t:void 0}if(dd(s)){const t={};for(const r in s){const n=G2e(s[r]);Ec(n)||(t[r]=n)}return Object.keys(t).length?t:void 0}}}function T4(s,t,r){r||(r=H2e(t));for(const n in s){const a=s[n];if(Urt(a))Ec(t)||V2e(r[n])?r[n]=H2e(a,Array.isArray(a)?[]:{}):T4(a,Zh(t)?{}:t[n],r[n]);else{const i=t[n];r[n]=!ax(a,i)}}return G2e(r)||{}}const fFe={value:!1,isValid:!1},pFe={value:!0,isValid:!0};var qrt=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&&!Ec(s[0].attributes.value)?Ec(s[0].value)||s[0].value===""?pFe:{value:s[0].value,isValid:!0}:pFe:fFe}return fFe},Vrt=(s,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>Ec(s)?s:t?s===""?NaN:s&&+s:r&&Pm(s)?new Date(s):n?n(s):s;const xFe={isValid:!1,value:null};var Hrt=s=>Array.isArray(s)?s.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,xFe):xFe;function gFe(s){const t=s.ref;return x5e(t)?t.files:g5e(t)?Hrt(s.refs).value:$rt(t)?[...t.selectedOptions].map(({value:r})=>r):QB(t)?qrt(s.refs).value:Vrt(Ec(t.value)?s.ref.value:t.value,s)}var xzt=(s,t,r,n)=>{const a={};for(const i of s){const l=Pn(t,i);l&&vl(a,i,l._f)}return{criteriaMode:r,names:[...s],fields:a,shouldUseNativeValidation:n}},Jue=s=>s instanceof RegExp,UD=s=>Ec(s)?s:Jue(s)?s.source:dd(s)?Jue(s.value)?s.value.source:s.value:s,yFe=s=>({isOnSubmit:!s||s===Gy.onSubmit,isOnBlur:s===Gy.onBlur,isOnChange:s===Gy.onChange,isOnAll:s===Gy.all,isOnTouch:s===Gy.onTouched});const vFe="AsyncFunction";var gzt=s=>!!s&&!!s.validate&&!!(Mm(s.validate)&&s.validate.constructor.name===vFe||dd(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===vFe)),yzt=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),bFe=(s,t,r)=>!r&&(t.watchAll||t.watch.has(s)||[...t.watch].some(n=>s.startsWith(`${n}.`)));const JO=(s,t,r,n)=>{for(const a of r||Object.keys(s)){const i=Pn(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(JO(o,t))break}else if(dd(o)&&JO(o,t))break}}};function _Fe(s,t,r){const n=Pn(s,r);if(n||JB(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const i=a.join("."),l=Pn(t,i),o=Pn(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 vzt=(s,t,r,n)=>{r(s);const{name:a,...i}=s;return gh(i)||n&&Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!n||Gy.all))},bzt=(s,t,r)=>!s||!t||s===t||jde(s).some(n=>n&&(r?n===t:n.startsWith(t)||t.startsWith(n))),_zt=(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,wzt=(s,t)=>!Brt(Pn(s,t)).length&&xu(s,t),wFe=(s,t,r)=>{const n=Pn(s,r),a=Array.isArray(n)?n:[];return vl(a,Drt,t[r]),vl(s,r,a),s};function jFe(s,t,r="validate"){if(Pm(s)||Array.isArray(s)&&s.every(Pm)||nx(s)&&!s)return{type:r,message:Pm(s)?s:"",ref:t}}var OE=s=>dd(s)&&!Jue(s)?s:{value:s,message:""},NFe=async(s,t,r,n,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:h,min:m,max:x,pattern:g,validate:v,name:j,valueAsNumber:b,mount:N}=s._f,S=Pn(r,j);if(!N||t.has(j))return{};const T=o?o[0]:l,A=K=>{a&&T.reportValidity&&(T.setCustomValidity(nx(K)?"":K||""),T.reportValidity())},P={},D=g5e(l),B=QB(l),z=D||B,F=(b||x5e(l))&&Ec(l.value)&&Ec(S)||Que(l)&&l.value===""||S===""||Array.isArray(S)&&!S.length,$=Frt.bind(null,j,n,P),X=(K,Q,Y,ne=Dy.maxLength,de=Dy.minLength)=>{const ce=K?Q:Y;P[j]={type:K?ne:de,message:ce,ref:l,...$(K?ne:de,ce)}};if(i?!Array.isArray(S)||!S.length:c&&(!z&&(F||Zh(S))||nx(S)&&!S||B&&!qrt(o).isValid||D&&!Hrt(o).isValid)){const{value:K,message:Q}=Pm(c)?{value:!!c,message:c}:OE(c);if(K&&(P[j]={type:Dy.required,message:Q,ref:T,...$(Dy.required,Q)},!n))return A(Q),P}if(!F&&(!Zh(m)||!Zh(x))){let K,Q;const Y=OE(x),ne=OE(m);if(!Zh(S)&&!isNaN(S)){const de=l.valueAsNumber||S&&+S;Zh(Y.value)||(K=de>Y.value),Zh(ne.value)||(Q=denew Date(new Date().toDateString()+" "+me),ae=l.type=="time",ie=l.type=="week";Pm(Y.value)&&S&&(K=ae?ce(S)>ce(Y.value):ie?S>Y.value:de>new Date(Y.value)),Pm(ne.value)&&S&&(Q=ae?ce(S)+K.value,ne=!Zh(Q.value)&&S.length<+Q.value;if((Y||ne)&&(X(Y,K.message,Q.message),!n))return A(P[j].message),P}if(g&&!F&&Pm(S)){const{value:K,message:Q}=OE(g);if(Jue(K)&&!S.match(K)&&(P[j]={type:Dy.pattern,message:Q,ref:l,...$(Dy.pattern,Q)},!n))return A(Q),P}if(v){if(Mm(v)){const K=await v(S,r),Q=jFe(K,T);if(Q&&(P[j]={...Q,...$(Dy.validate,Q.message)},!n))return A(Q.message),P}else if(dd(v)){let K={};for(const Q in v){if(!gh(K)&&!n)break;const Y=jFe(await v[Q](S,r),T,Q);Y&&(K={...Y,...$(Q,Y.message)},A(Y.message),n&&(P[j]=K))}if(!gh(K)&&(P[j]={ref:T,...K},!n))return P}}return A(!0),P};const jzt={mode:Gy.onSubmit,reValidateMode:Gy.onChange,shouldFocusError:!0},Grt={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function Nzt(s={}){let t={...jzt,...s},r={...Sd(Grt),isLoading:Mm(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},n={},a=dd(t.defaultValues)||dd(t.values)?Sd(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Sd(a),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set},c,d=0;const h={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},m={...h};let x={...m};const g={array:mFe(),state:mFe()},v=t.criteriaMode===Gy.all,j=Ie=>et=>{clearTimeout(d),d=setTimeout(Ie,et)},b=async Ie=>{if(!l.keepIsValid&&!t.disabled&&(m.isValid||x.isValid||Ie)){let et;t.resolver?(et=gh((await $()).errors),N()):et=await Q({fields:n,onlyCheckValid:!0,eventType:Jw.VALID}),et!==r.isValid&&g.state.next({isValid:et})}},N=(Ie,et)=>{!t.disabled&&(m.isValidating||m.validatingFields||x.isValidating||x.validatingFields)&&((Ie||Array.from(o.mount)).forEach(Dt=>{Dt&&(et?vl(r.validatingFields,Dt,et):xu(r.validatingFields,Dt))}),g.state.next({validatingFields:r.validatingFields,isValidating:!gh(r.validatingFields)}))},S=()=>{r.dirtyFields=T4(a,i)},T=(Ie,et=[],Dt,Jt,cs=!0,Ht=!0)=>{if(Jt&&Dt&&!t.disabled){if(l.action=!0,Ht&&Array.isArray(Pn(n,Ie))){const dt=Dt(Pn(n,Ie),Jt.argA,Jt.argB);cs&&vl(n,Ie,dt)}if(Ht&&Array.isArray(Pn(r.errors,Ie))){const dt=Dt(Pn(r.errors,Ie),Jt.argA,Jt.argB);cs&&vl(r.errors,Ie,dt),wzt(r.errors,Ie)}if((m.touchedFields||x.touchedFields)&&Ht&&Array.isArray(Pn(r.touchedFields,Ie))){const dt=Dt(Pn(r.touchedFields,Ie),Jt.argA,Jt.argB);cs&&vl(r.touchedFields,Ie,dt)}(m.dirtyFields||x.dirtyFields)&&S(),g.state.next({name:Ie,isDirty:ne(Ie,et),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else vl(i,Ie,et)},A=(Ie,et)=>{vl(r.errors,Ie,et),g.state.next({errors:r.errors})},P=Ie=>{r.errors=Ie,g.state.next({errors:r.errors,isValid:!1})},D=Ie=>{const et=JB(Ie)?[Ie]:Upe(Ie);let Dt=i,Jt=a;for(let cs=0;cs{const cs=Pn(n,Ie);if(cs){if(D(Ie))return;const Ht=Ec(Pn(i,Ie)),dt=Pn(i,Ie,Ec(Dt)?Pn(a,Ie):Dt);Ec(dt)||Jt&&Jt.defaultChecked||et?vl(i,Ie,et?dt:gFe(cs._f)):ae(Ie,dt),l.mount&&!l.action&&(b(),Ht&&r.isDirty&&(m.isDirty||x.isDirty)&&(ne()||(r.isDirty=!1,g.state.next({...r}))))}},z=(Ie,et,Dt,Jt,cs)=>{let Ht=!1,dt=!1;const Qt={name:Ie};if(!t.disabled){if(!Dt||Jt){(m.isDirty||x.isDirty)&&(dt=r.isDirty,r.isDirty=Qt.isDirty=ne(),Ht=dt!==Qt.isDirty);const yt=ax(Pn(a,Ie),et);dt=!!Pn(r.dirtyFields,Ie),yt!==r.isDirty?r.dirtyFields=T4(a,i):yt?xu(r.dirtyFields,Ie):vl(r.dirtyFields,Ie,!0),Qt.dirtyFields=r.dirtyFields,Ht=Ht||(m.dirtyFields||x.dirtyFields)&&dt!==!yt}if(Dt){const yt=Pn(r.touchedFields,Ie);yt||(vl(r.touchedFields,Ie,Dt),Qt.touchedFields=r.touchedFields,Ht=Ht||(m.touchedFields||x.touchedFields)&&yt!==Dt)}Ht&&cs&&g.state.next(Qt)}return Ht?Qt:{}},F=(Ie,et,Dt,Jt)=>{const cs=Pn(r.errors,Ie),Ht=(m.isValid||x.isValid)&&nx(et)&&r.isValid!==et;if(t.delayError&&Dt?(c=j(()=>A(Ie,Dt)),c(t.delayError)):(clearTimeout(d),c=null,Dt?vl(r.errors,Ie,Dt):xu(r.errors,Ie)),(Dt?!ax(cs,Dt):cs)||!gh(Jt)||Ht){const dt={...Jt,...Ht&&nx(et)?{isValid:et}:{},errors:r.errors,name:Ie};r={...r,...dt},g.state.next(dt)}},$=async Ie=>(N(Ie,!0),await t.resolver(i,t.context,xzt(Ie||o.mount,n,t.criteriaMode,t.shouldUseNativeValidation))),X=async Ie=>{const{errors:et}=await $(Ie);if(N(Ie),Ie)for(const Dt of Ie){const Jt=Pn(et,Dt);Jt?o.array.has(Dt)&&dd(Jt)&&!Object.keys(Jt).some(cs=>!Number.isNaN(Number(cs)))?wFe(r.errors,{[Dt]:Jt},Dt):vl(r.errors,Dt,Jt):xu(r.errors,Dt)}else r.errors=et;return et},K=async({name:Ie,eventType:et})=>{if(s.validate){const Dt=await s.validate({formValues:i,formState:r,name:Ie,eventType:et});if(dd(Dt))for(const Jt in Dt){const cs=Dt[Jt];cs&&Se(`${z1e}.${Jt}`,{message:Pm(cs.message)?cs.message:"",type:cs.type||Dy.validate})}else Pm(Dt)||!Dt?Se(z1e,{message:Dt||"",type:Dy.validate}):$e(z1e);return Dt}return!0},Q=async({fields:Ie,onlyCheckValid:et,name:Dt,eventType:Jt,context:cs={valid:!0,runRootValidation:!1}})=>{if(s.validate&&(cs.runRootValidation=!0,!await K({name:Dt,eventType:Jt})&&(cs.valid=!1,et)))return cs.valid;for(const Ht in Ie){const dt=Ie[Ht];if(dt){const{_f:Qt,...yt}=dt;if(Qt){const ss=o.array.has(Qt.name),Is=dt._f&&gzt(dt._f),fs=m.validatingFields||m.isValidating||x.validatingFields||x.isValidating;Is&&fs&&N([Qt.name],!0);const ar=await NFe(dt,o.disabled,i,v,t.shouldUseNativeValidation&&!et,ss);if(Is&&fs&&N([Qt.name]),ar[Qt.name]&&(cs.valid=!1,et)||(!et&&(Pn(ar,Qt.name)?ss?wFe(r.errors,ar,Qt.name):vl(r.errors,Qt.name,ar[Qt.name]):xu(r.errors,Qt.name)),s.shouldUseNativeValidation&&ar[Qt.name]))break}!gh(yt)&&await Q({context:cs,onlyCheckValid:et,fields:yt,name:Ht,eventType:Jt})}}return cs.valid},Y=()=>{for(const Ie of o.unMount){const et=Pn(n,Ie);et&&(et._f.refs?et._f.refs.every(Dt=>!$1e(Dt)):!$1e(et._f.ref))&&ct(Ie)}o.unMount=new Set},ne=(Ie,et)=>!t.disabled&&(Ie&&et&&vl(i,Ie,et),!ax(Pe(),a)),de=(Ie,et,Dt)=>q2e(Ie,o,{...l.mount?i:Ec(et)?a:Pm(Ie)?{[Ie]:et}:et},Dt,et),ce=Ie=>Brt(Pn(l.mount?i:a,Ie,t.shouldUnregister?Pn(a,Ie,[]):[])),ae=(Ie,et,Dt={},Jt=!1)=>{const cs=Pn(n,Ie);let Ht=et;if(cs){const dt=cs._f;dt&&(!dt.disabled&&vl(i,Ie,Vrt(et,dt)),Ht=Que(dt.ref)&&Zh(et)?"":et,$rt(dt.ref)?[...dt.ref.options].forEach(Qt=>Qt.selected=Ht.includes(Qt.value)):dt.refs?QB(dt.ref)?dt.refs.forEach(Qt=>{(!Qt.defaultChecked||!Qt.disabled)&&(Array.isArray(Ht)?Qt.checked=!!Ht.find(yt=>yt===Qt.value):Qt.checked=Ht===Qt.value||!!Ht)}):dt.refs.forEach(Qt=>Qt.checked=Qt.value===Ht):x5e(dt.ref)?dt.ref.value="":(dt.ref.value=Ht,dt.ref.type||g.state.next({name:Ie,values:Jt?i:Sd(i)})))}(Dt.shouldDirty||Dt.shouldTouch)&&z(Ie,Ht,Dt.shouldTouch,Dt.shouldDirty,!0),Dt.shouldValidate&&Me(Ie)},ie=(Ie,et,Dt,Jt=!1)=>{for(const cs in et){if(!et.hasOwnProperty(cs))return;const Ht=et[cs],dt=Ie+"."+cs,Qt=Pn(n,dt);(o.array.has(Ie)||dd(Ht)||Qt&&!Qt._f)&&!G4(Ht)?ie(dt,Ht,Dt,Jt):ae(dt,Ht,Dt,Jt)}},me=(Ie,et,Dt,Jt)=>{const cs=Pn(n,Ie),Ht=o.array.has(Ie),dt=Jt?et:Sd(et),Qt=Pn(i,Ie),yt=ax(Qt,dt);if(yt||vl(i,Ie,dt),Ht)g.array.next({name:Ie,values:Jt?i:Sd(i)}),(m.isDirty||m.dirtyFields||x.isDirty||x.dirtyFields)&&Dt.shouldDirty&&(S(),g.state.next({name:Ie,dirtyFields:r.dirtyFields,isDirty:ne(Ie,dt)}));else{const ss=Array.isArray(dt)&&!dt.length||gh(dt);!cs||cs._f||Zh(dt)||ss?ae(Ie,dt,Dt,Jt):ie(Ie,dt,Dt,Jt)}if(!yt){const ss=bFe(Ie,o),Is=Jt?i:Sd(i);g.state.next({...ss&&r,name:l.mount||ss?Ie:void 0,values:Is})}},oe=(Ie,et,Dt={})=>me(Ie,et,Dt,!1),ge=(Ie,et={})=>{const Dt=Mm(Ie)?Ie(i):Ie;if(!ax(i,Dt)){i={...i,...Dt};for(const Jt of o.mount)me(Jt,Pn(Dt,Jt),et,!0);g.state.next({...r,name:void 0,type:void 0,values:i}),et.shouldValidate&&b()}},be=async Ie=>{l.mount=!0;const et=Ie.target;let Dt=et.name,Jt=!0;const cs=Pn(n,Dt),Ht=yt=>{Jt=Number.isNaN(yt)||G4(yt)&&isNaN(yt.getTime())||ax(yt,Pn(i,Dt,yt))},dt=yFe(t.mode),Qt=yFe(t.reValidateMode);if(cs){let yt,ss;const Is=et.type?gFe(cs._f):U2e(Ie),fs=Ie.type===Jw.BLUR||Ie.type===Jw.FOCUS_OUT,ar=!yzt(cs._f)&&!s.validate&&!t.resolver&&!Pn(r.errors,Dt)&&!cs._f.deps||_zt(fs,Pn(r.touchedFields,Dt),r.isSubmitted,Qt,dt),Er=bFe(Dt,o,fs);vl(i,Dt,Is),fs?(!et||!et.readOnly)&&(cs._f.onBlur&&cs._f.onBlur(Ie),c&&c(0)):cs._f.onChange&&cs._f.onChange(Ie);const Tr=z(Dt,Is,fs),Lr=!gh(Tr)||Er;if(!fs&&g.state.next({name:Dt,type:Ie.type,values:Sd(i)}),ar)return(m.isValid||x.isValid)&&(t.mode==="onBlur"?fs&&b():fs||b()),Lr&&g.state.next({name:Dt,...Er?{}:Tr});if(!t.resolver&&s.validate&&await K({name:Dt,eventType:Ie.type}),!fs&&Er&&g.state.next({...r}),t.resolver){const{errors:$r}=await $([Dt]);if(N([Dt]),Ht(Is),!Jt){!gh(Tr)&&g.state.next(Tr);return}const kr=_Fe(r.errors,n,Dt),Sr=_Fe($r,n,kr.name||Dt);yt=Sr.error,Dt=Sr.name,ss=gh($r)}else N([Dt],!0),yt=(await NFe(cs,o.disabled,i,v,t.shouldUseNativeValidation))[Dt],N([Dt]),Ht(Is),Jt&&(yt?ss=!1:(m.isValid||x.isValid)&&(ss=await Q({fields:n,onlyCheckValid:!0,name:Dt,eventType:Ie.type})));Jt&&(cs._f.deps&&(!Array.isArray(cs._f.deps)||cs._f.deps.length>0)&&Me(cs._f.deps),F(Dt,ss,yt,Tr))}},Oe=(Ie,et)=>{if(Pn(r.errors,et)&&Ie.focus)return Ie.focus(),1},Me=async(Ie,et={})=>{let Dt,Jt;const cs=jde(Ie);if(t.resolver){const Ht=await X(Ec(Ie)?Ie:cs);Dt=gh(Ht),Jt=Ie?!cs.some(dt=>Pn(Ht,dt)):Dt}else Ie?(Jt=(await Promise.all(cs.map(async Ht=>{const dt=Pn(n,Ht);return await Q({fields:dt&&dt._f?{[Ht]:dt}:dt,eventType:Jw.TRIGGER})}))).every(Boolean),!(!Jt&&!r.isValid)&&b()):Jt=Dt=await Q({fields:n,name:Ie,eventType:Jw.TRIGGER});return g.state.next({...!Pm(Ie)||(m.isValid||x.isValid)&&Dt!==r.isValid?{}:{name:Ie},...t.resolver||!Ie?{isValid:Dt}:{},errors:r.errors}),et.shouldFocus&&!Jt&&JO(n,Oe,Ie?cs:o.mount),Jt},Pe=(Ie,et)=>{let Dt={...l.mount?i:a};return et&&(Dt=zrt(et.dirtyFields?r.dirtyFields:r.touchedFields,Dt)),Ec(Ie)?Dt:Pm(Ie)?Pn(Dt,Ie):Ie.map(Jt=>Pn(Dt,Jt))},Ee=(Ie,et)=>({invalid:!!Pn((et||r).errors,Ie),isDirty:!!Pn((et||r).dirtyFields,Ie),error:Pn((et||r).errors,Ie),isValidating:!!Pn(r.validatingFields,Ie),isTouched:!!Pn((et||r).touchedFields,Ie)}),$e=Ie=>{const et=Ie?jde(Ie):void 0;et==null||et.forEach(Dt=>xu(r.errors,Dt)),et?et.forEach(Dt=>{g.state.next({name:Dt,errors:r.errors})}):g.state.next({errors:{}})},Se=(Ie,et,Dt)=>{const Jt=(Pn(n,Ie,{_f:{}})._f||{}).ref,cs=Pn(r.errors,Ie)||{},{ref:Ht,message:dt,type:Qt,...yt}=cs;vl(r.errors,Ie,{...yt,...et,ref:Jt}),g.state.next({name:Ie,errors:r.errors,isValid:!1}),Dt&&Dt.shouldFocus&&Jt&&Jt.focus&&Jt.focus()},ze=(Ie,et)=>Mm(Ie)?g.state.subscribe({next:Dt=>"values"in Dt&&Ie(Dt.values||de(void 0,et),Dt)}):de(Ie,et,!0),Te=Ie=>g.state.subscribe({next:et=>{if(bzt(Ie.name,et.name,Ie.exact)&&vzt(et,Ie.formState||m,it,Ie.reRenderRoot)){const Dt={...i};Ie.callback({values:Dt,...r,...et,defaultValues:a})}}}).unsubscribe,ye=Ie=>(l.mount=!0,x={...x,...Ie.formState},Te({...Ie,formState:{...h,...Ie.formState}})),ct=(Ie,et={})=>{for(const Dt of Ie?jde(Ie):o.mount)o.mount.delete(Dt),o.array.delete(Dt),et.keepValue||(xu(n,Dt),xu(i,Dt)),!et.keepError&&xu(r.errors,Dt),!et.keepDirty&&xu(r.dirtyFields,Dt),!et.keepTouched&&xu(r.touchedFields,Dt),!et.keepIsValidating&&xu(r.validatingFields,Dt),!t.shouldUnregister&&!et.keepDefaultValue&&xu(a,Dt);g.state.next({values:Sd(i)}),g.state.next({...r,...et.keepDirty?{isDirty:ne()}:{}}),!et.keepIsValid&&b()},ve=({disabled:Ie,name:et})=>{if(nx(Ie)&&l.mount||Ie||o.disabled.has(et)){const cs=o.disabled.has(et)!==!!Ie;Ie?o.disabled.add(et):o.disabled.delete(et),cs&&l.mount&&!l.action&&b()}},rt=(Ie,et={})=>{let Dt=Pn(n,Ie);const Jt=nx(et.disabled)||nx(t.disabled),cs=!o.registerName.has(Ie)&&Dt&&Dt._f&&!Dt._f.mount;return vl(n,Ie,{...Dt||{},_f:{...Dt&&Dt._f?Dt._f:{ref:{name:Ie}},name:Ie,mount:!0,...et}}),o.mount.add(Ie),Dt&&!cs?ve({disabled:nx(et.disabled)?et.disabled:t.disabled,name:Ie}):B(Ie,!0,et.value),{...Jt?{disabled:et.disabled||t.disabled}:{},...t.progressive?{required:!!et.required,min:UD(et.min),max:UD(et.max),minLength:UD(et.minLength),maxLength:UD(et.maxLength),pattern:UD(et.pattern)}:{},name:Ie,onChange:be,onBlur:be,ref:Ht=>{if(Ht){o.registerName.add(Ie),rt(Ie,et),o.registerName.delete(Ie),Dt=Pn(n,Ie);const dt=Ec(Ht.value)&&Ht.querySelectorAll&&Ht.querySelectorAll("input,select,textarea")[0]||Ht,Qt=hzt(dt),yt=Dt._f.refs||[];if(Qt?yt.find(ss=>ss===dt):dt===Dt._f.ref)return;vl(n,Ie,{_f:{...Dt._f,...Qt?{refs:[...yt.filter($1e),dt,...Array.isArray(Pn(a,Ie))?[{}]:[]],ref:{type:dt.type,name:Ie}}:{ref:dt}}}),B(Ie,!1,void 0,dt)}else Dt=Pn(n,Ie,{}),Dt._f&&(Dt._f.mount=!1),(t.shouldUnregister||et.shouldUnregister)&&!(Prt(o.array,Ie)&&l.action)&&o.unMount.add(Ie)}}},Re=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&JO(n,Oe,o.mount),Qe=Ie=>{nx(Ie)&&(g.state.next({disabled:Ie}),JO(n,(et,Dt)=>{const Jt=Pn(n,Dt);Jt&&(et.disabled=Jt._f.disabled||Ie,Array.isArray(Jt._f.refs)&&Jt._f.refs.forEach(cs=>{cs.disabled=Jt._f.disabled||Ie}))},0,!1))},Ke=(Ie,et)=>async Dt=>{let Jt;Dt&&(Dt.preventDefault&&Dt.preventDefault(),Dt.persist&&Dt.persist());let cs=Sd(i);if(g.state.next({isSubmitting:!0}),t.resolver){const{errors:Ht,values:dt}=await $();N(),r.errors=Ht,cs=Sd(dt)}else await Q({fields:n,eventType:Jw.SUBMIT});if(o.disabled.size)for(const Ht of o.disabled)xu(cs,Ht);if(xu(r.errors,Drt),gh(r.errors)){g.state.next({errors:{}});try{await Ie(cs,Dt)}catch(Ht){Jt=Ht}}else et&&await et({...r.errors},Dt),Re(),setTimeout(Re);if(g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:gh(r.errors)&&!Jt,submitCount:r.submitCount+1,errors:r.errors}),Jt)throw Jt},Ce=(Ie,et={})=>{Pn(n,Ie)&&(Ec(et.defaultValue)?oe(Ie,Sd(Pn(a,Ie))):(oe(Ie,et.defaultValue),vl(a,Ie,Sd(et.defaultValue))),et.keepTouched||xu(r.touchedFields,Ie),et.keepDirty||(xu(r.dirtyFields,Ie),r.isDirty=et.defaultValue?ne(Ie,Sd(Pn(a,Ie))):ne()),et.keepError||(xu(r.errors,Ie),m.isValid&&b()),g.state.next({...r}))},nt=(Ie,et={})=>{const Dt=Ie?Sd(Ie):a,Jt=Sd(Dt),cs=gh(Ie),Ht=Jt;if(et.keepDefaultValues||(a=Dt),!et.keepValues){if(et.keepDirtyValues){const dt=new Set([...o.mount,...Object.keys(T4(a,i))]);for(const Qt of Array.from(dt)){const yt=Pn(r.dirtyFields,Qt),ss=Pn(i,Qt),Is=Pn(Ht,Qt);yt&&!Ec(ss)?vl(Ht,Qt,ss):!yt&&!Ec(Is)&&oe(Qt,Is)}}else{if($pe&&Ec(Ie))for(const dt of o.mount){const Qt=Pn(n,dt);if(Qt&&Qt._f){const yt=Array.isArray(Qt._f.refs)?Qt._f.refs[0]:Qt._f.ref;if(Que(yt)){const ss=yt.closest("form");if(ss){ss.reset();break}}}}if(et.keepFieldsRef)for(const dt of o.mount)oe(dt,Pn(Ht,dt));else n={}}if(t.shouldUnregister){if(i=et.keepDefaultValues?Sd(a):{},et.keepFieldsRef)for(const dt of o.mount)vl(i,dt,Pn(Ht,dt))}else i=Sd(Ht);g.array.next({values:{...Ht}}),g.state.next({values:{...Ht}})}o={mount:et.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!m.isValid||!!et.keepIsValid||!!et.keepDirtyValues||!t.shouldUnregister&&!gh(Ht),l.watch=!!t.shouldUnregister,l.keepIsValid=!!et.keepIsValid,l.action=!1,et.keepErrors||(r.errors={}),g.state.next({submitCount:et.keepSubmitCount?r.submitCount:0,isDirty:cs?!1:et.keepDirty?r.isDirty:et.keepValues?ne():!!(et.keepDefaultValues&&!ax(Ie,a)),isSubmitted:et.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:cs?{}:et.keepDirtyValues?et.keepDefaultValues&&i?T4(a,i):r.dirtyFields:et.keepDefaultValues&&Ie?T4(a,Ie):et.keepDirty?r.dirtyFields:{},touchedFields:et.keepTouched?r.touchedFields:{},errors:et.keepErrors?r.errors:{},isSubmitSuccessful:et.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},$t=(Ie,et)=>nt(Mm(Ie)?Ie(i):Ie,{...t.resetOptions,...et}),lt=(Ie,et={})=>{const Dt=Pn(n,Ie),Jt=Dt&&Dt._f;if(Jt){const cs=Jt.refs?Jt.refs[0]:Jt.ref;cs.focus&&setTimeout(()=>{cs.focus(),et.shouldSelect&&Mm(cs.select)&&cs.select()})}},it=Ie=>{r={...r,...Ie}},at={control:{register:rt,unregister:ct,getFieldState:Ee,handleSubmit:Ke,setError:Se,_subscribe:Te,_runSchema:$,_updateIsValidating:N,_focusError:Re,_getWatch:de,_getDirty:ne,_setValid:b,_setFieldArray:T,_setDisabledField:ve,_setErrors:P,_getFieldArray:ce,_reset:nt,_resetDefaultValues:()=>Mm(t.defaultValues)&&t.defaultValues().then(Ie=>{$t(Ie,t.resetOptions),g.state.next({isLoading:!1})}),_removeUnmounted:Y,_disableForm:Qe,_subjects:g,_proxyFormState:m,get _fields(){return n},get _formValues(){return i},get _state(){return l},set _state(Ie){l=Ie},get _defaultValues(){return a},get _names(){return o},set _names(Ie){o=Ie},get _formState(){return r},get _options(){return t},set _options(Ie){t={...t,...Ie}}},subscribe:ye,trigger:Me,register:rt,handleSubmit:Ke,watch:ze,setValue:oe,setValues:ge,getValues:Pe,reset:$t,resetField:Ce,resetDefaultValues:(Ie,et={})=>{if(a=Sd(Ie),!et.keepDirty){const Dt=T4(a,i);r.dirtyFields=Dt,r.isDirty=!gh(Dt)}et.keepIsValid||b(),g.state.next({...r,defaultValues:a})},clearErrors:$e,unregister:ct,setError:Se,setFocus:lt,getFieldState:Ee};return{...at,formControl:at}}function qpe(s={}){const t=wt.useRef(void 0),r=wt.useRef(void 0),[n,a]=wt.useState(()=>({...Sd(Grt),isLoading:Mm(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1,defaultValues:Mm(s.defaultValues)?void 0:s.defaultValues}));if(!t.current)if(s.formControl)t.current={...s.formControl,formState:n},s.defaultValues&&!Mm(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=Nzt(s);t.current={...o,formState:n}}const i=t.current.control;return i._options=s,f5e(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState,defaultValues:i._defaultValues}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),wt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),wt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),wt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),wt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),wt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==n.isDirty&&i._subjects.state.next({isDirty:l})}},[i,n.isDirty]),wt.useEffect(()=>{var l;s.values&&!ax(s.values,r.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),!((l=i._options.resetOptions)===null||l===void 0)&&l.keepIsValid||i._setValid(),r.current=s.values,a(o=>({...o}))):i._resetDefaultValues()},[i,s.values]),wt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=wt.useMemo(()=>Ort(n,i),[i,n]),t.current}const kFe=(s,t,r)=>{if(s&&"reportValidity"in s){const n=Pn(r,t);s.setCustomValidity(n&&n.message||""),s.reportValidity()}},Wrt=(s,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?kFe(n.ref,r,s):n.refs&&n.refs.forEach(a=>kFe(a,r,s))}},kzt=(s,t)=>{t.shouldUseNativeValidation&&Wrt(s,t);const r={};for(const n in s){const a=Pn(t.fields,n),i=Object.assign(s[n]||{},{ref:a&&a.ref});if(Szt(t.names||Object.keys(s),n)){const l=Object.assign({},Pn(r,n));vl(l,"root",i),vl(r,n,l)}else vl(r,n,i)}return r},Szt=(s,t)=>s.some(r=>r.startsWith(t+"."));var Czt=function(s,t){for(var r={};s.length;){var n=s[0],a=n.code,i=n.message,l=n.path.join(".");if(!r[l])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[l]={message:o.message,type:o.code}}else r[l]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return s.push(m)})}),t){var c=r[l].types,d=c&&c[n.code];r[l]=Frt(l,t,r,a,d?[].concat(d,n.message):n.message)}s.shift()}return r},Vpe=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&&Wrt({},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:kzt(Czt(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Hpe=uzt,Krt=k.createContext({}),rd=({...s})=>e.jsx(Krt.Provider,{value:{name:s.name},children:e.jsx(czt,{...s})}),Gpe=()=>{const s=k.useContext(Krt),t=k.useContext(Yrt),{getFieldState:r,formState:n}=dzt(),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}},Yrt=k.createContext({}),$c=k.forwardRef(({className:s,...t},r)=>{const n=k.useId();return e.jsx(Yrt.Provider,{value:{id:n},children:e.jsx("div",{ref:r,className:Bt("space-y-2",s),...t})})});$c.displayName="FormItem";const Uc=k.forwardRef(({className:s,...t},r)=>{const{error:n,formItemId:a}=Gpe();return e.jsx(he,{ref:r,className:Bt(n&&"text-destructive",s),htmlFor:a,...t})});Uc.displayName="FormLabel";const qc=k.forwardRef(({...s},t)=>{const{error:r,formItemId:n,formDescriptionId:a,formMessageId:i}=Gpe();return e.jsx(c4e,{ref:t,id:n,"aria-describedby":r?`${a} ${i}`:`${a}`,"aria-invalid":!!r,...s})});qc.displayName="FormControl";const Nde=k.forwardRef(({className:s,...t},r)=>{const{formDescriptionId:n}=Gpe();return e.jsx("p",{ref:r,id:n,className:Bt("text-sm text-muted-foreground",s),...t})});Nde.displayName="FormDescription";const yf=k.forwardRef(({className:s,children:t,...r},n)=>{const{error:a,formMessageId:i}=Gpe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:n,id:i,className:Bt("text-sm font-medium text-destructive",s),...r,children:l}):null});yf.displayName="FormMessage";const Tzt=M_({category:rtt(["general","technology","crm","marketing"]),subject:oo().min(5,"Subject must be at least 5 characters").max(200),description:oo().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),Ezt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function W2e({trigger:s}){const[t,r]=k.useState(!1),[n,a]=k.useState(!1),{user:i}=As(),l=qpe({resolver:Vpe(Tzt),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ue.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await H.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await H.functions.invoke("support-ticket-notify",{body:{category:Ezt[c.category],subject:c.subject}})}catch(h){console.log("Notification send attempted:",h)}ue.success("Support ticket submitted successfully!"),l.reset(),r(!1)}catch(d){console.error("Error submitting ticket:",d),ue.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(vs,{open:t,onOpenChange:r,children:[e.jsx(Ni,{asChild:!0,children:s||e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(xO,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(ys,{className:"sm:max-w-[500px]",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Need Help?"}),e.jsx(Fr,{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(Nn,{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(Hpe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(rd,{control:l.control,name:"category",render:({field:c})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Category"}),e.jsxs(zs,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(qc,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a category"})})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"general",children:"General Support"}),e.jsx(mt,{value:"technology",children:"Technology Support"}),e.jsx(mt,{value:"crm",children:"CRM Support"}),e.jsx(mt,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(yf,{})]})}),e.jsx(rd,{control:l.control,name:"subject",render:({field:c})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Subject"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"Brief description of your issue",...c})}),e.jsx(yf,{})]})}),e.jsx(rd,{control:l.control,name:"description",render:({field:c})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Description"}),e.jsx(qc,{children:e.jsx(ur,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(yf,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}const Azt=()=>{const{user:s}=As(),t=vr(),[r,n]=k.useState([]),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s)return;const v=`notification_last_read_${s.id}`;let j=c;if(!j){const S=localStorage.getItem(v);S&&(j=S,d(S))}(async()=>{const{data:S,error:T}=await H.from("push_notifications").select("*").order("created_at",{ascending:!1}).limit(20);if(!T&&S){n(S);const A=j?new Date(j):null,P=S.filter(D=>A?new Date(D.created_at)>A:!0);i(P.length)}})();const N=H.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},S=>{const T=S.new;n(P=>[T,...P].slice(0,20));const A=j?new Date(j):null;(!A||new Date(T.created_at)>A)&&i(P=>P+1),Notification.permission==="granted"&&new Notification(T.title,{body:T.body,icon:"/favicon.ico"})}).subscribe();return()=>{H.removeChannel(N)}},[s,c]);const h=v=>{const j=v.toLowerCase();return j.includes("community")||j.includes("post")?bi:j.includes("academy")||j.includes("video")?sn:j.includes("template")?pl:j.includes("event")?rn:j.includes("newsletter")?Vv:j.includes("brokerage")?Yu:j.includes("swag")||j.includes("social")?li:j.includes("toolbox")||j.includes("tool")?i0:j.includes("brief")?jr:bi},m=v=>{o(!1),v.url&&v.url!=="/"&&t(v.url)},x=()=>{if(!s)return;const v=new Date().toISOString(),j=`notification_last_read_${s.id}`;localStorage.setItem(j,v),d(v),i(0)},g=v=>{o(v),v&&a>0&&x()};return e.jsxs(lu,{open:l,onOpenChange:g,children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Rm,{className:"h-5 w-5"}),a>0&&e.jsx(Ge,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:a>9?"9+":a})]})}),e.jsxs(Vd,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:x,children:"Mark all read"})]}),e.jsx(ti,{className:"h-[300px]",children:r.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(v=>{const j=h(v.title);return e.jsxs(Da,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(v),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(j,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:v.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:v.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:al(new Date(v.created_at),{addSuffix:!0})})]})]},v.id)})})]})]})};var SFe=1,Mzt=.9,Izt=.8,Pzt=.17,U1e=.1,q1e=.999,Lzt=.9999,Dzt=.99,Rzt=/[\\\/_+.#"@\[\(\{&]/,Ozt=/[\\\/_+.#"@\[\(\{&]/g,Fzt=/[\s-]/,Zrt=/[\s-]/g;function K2e(s,t,r,n,a,i,l){if(i===t.length)return a===s.length?SFe:Dzt;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=n.charAt(i),d=r.indexOf(c,a),h=0,m,x,g,v;d>=0;)m=K2e(s,t,r,n,d+1,i+1,l),m>h&&(d===a?m*=SFe:Rzt.test(s.charAt(d-1))?(m*=Izt,g=s.slice(a,d-1).match(Ozt),g&&a>0&&(m*=Math.pow(q1e,g.length))):Fzt.test(s.charAt(d-1))?(m*=Mzt,v=s.slice(a,d-1).match(Zrt),v&&a>0&&(m*=Math.pow(q1e,v.length))):(m*=Pzt,a>0&&(m*=Math.pow(q1e,d-a))),s.charAt(d)!==t.charAt(i)&&(m*=Lzt)),(mm&&(m=x*U1e)),m>h&&(h=m),d=r.indexOf(c,d+1);return l[o]=h,h}function CFe(s){return s.toLowerCase().replace(Zrt," ")}function Bzt(s,t,r){return s=r&&r.length>0?`${s+" "+r.join(" ")}`:s,K2e(s,t,CFe(s),CFe(t),0,0,{})}var qD='[cmdk-group=""]',V1e='[cmdk-group-items=""]',zzt='[cmdk-group-heading=""]',Xrt='[cmdk-item=""]',TFe=`${Xrt}:not([aria-disabled="true"])`,Y2e="cmdk-item-select",cA="data-value",$zt=(s,t,r)=>Bzt(s,t,r),Qrt=k.createContext(void 0),ez=()=>k.useContext(Qrt),Jrt=k.createContext(void 0),y5e=()=>k.useContext(Jrt),ent=k.createContext(void 0),tnt=k.forwardRef((s,t)=>{let r=dA(()=>{var ge,be;return{search:"",value:(be=(ge=s.value)!=null?ge:s.defaultValue)!=null?be:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=dA(()=>new Set),a=dA(()=>new Map),i=dA(()=>new Map),l=dA(()=>new Set),o=snt(s),{label:c,children:d,value:h,onValueChange:m,filter:x,shouldFilter:g,loop:v,disablePointerSelection:j=!1,vimBindings:b=!0,...N}=s,S=Qu(),T=Qu(),A=Qu(),P=k.useRef(null),D=Qzt();_5(()=>{if(h!==void 0){let ge=h.trim();r.current.value=ge,B.emit()}},[h]),_5(()=>{D(6,Q)},[]);let B=k.useMemo(()=>({subscribe:ge=>(l.current.add(ge),()=>l.current.delete(ge)),snapshot:()=>r.current,setState:(ge,be,Oe)=>{var Me,Pe,Ee,$e;if(!Object.is(r.current[ge],be)){if(r.current[ge]=be,ge==="search")K(),$(),D(1,X);else if(ge==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(A);Se?Se.focus():(Me=document.getElementById(S))==null||Me.focus()}if(D(7,()=>{var Se;r.current.selectedItemId=(Se=Y())==null?void 0:Se.id,B.emit()}),Oe||D(5,Q),((Pe=o.current)==null?void 0:Pe.value)!==void 0){let Se=be??"";($e=(Ee=o.current).onValueChange)==null||$e.call(Ee,Se);return}}B.emit()}},emit:()=>{l.current.forEach(ge=>ge())}}),[]),z=k.useMemo(()=>({value:(ge,be,Oe)=>{var Me;be!==((Me=i.current.get(ge))==null?void 0:Me.value)&&(i.current.set(ge,{value:be,keywords:Oe}),r.current.filtered.items.set(ge,F(be,Oe)),D(2,()=>{$(),B.emit()}))},item:(ge,be)=>(n.current.add(ge),be&&(a.current.has(be)?a.current.get(be).add(ge):a.current.set(be,new Set([ge]))),D(3,()=>{K(),$(),r.current.value||X(),B.emit()}),()=>{i.current.delete(ge),n.current.delete(ge),r.current.filtered.items.delete(ge);let Oe=Y();D(4,()=>{K(),(Oe==null?void 0:Oe.getAttribute("id"))===ge&&X(),B.emit()})}),group:ge=>(a.current.has(ge)||a.current.set(ge,new Set),()=>{i.current.delete(ge),a.current.delete(ge)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:S,inputId:A,labelId:T,listInnerRef:P}),[]);function F(ge,be){var Oe,Me;let Pe=(Me=(Oe=o.current)==null?void 0:Oe.filter)!=null?Me:$zt;return ge?Pe(ge,r.current.search,be):0}function $(){if(!r.current.search||o.current.shouldFilter===!1)return;let ge=r.current.filtered.items,be=[];r.current.filtered.groups.forEach(Me=>{let Pe=a.current.get(Me),Ee=0;Pe.forEach($e=>{let Se=ge.get($e);Ee=Math.max(Se,Ee)}),be.push([Me,Ee])});let Oe=P.current;ne().sort((Me,Pe)=>{var Ee,$e;let Se=Me.getAttribute("id"),ze=Pe.getAttribute("id");return((Ee=ge.get(ze))!=null?Ee:0)-(($e=ge.get(Se))!=null?$e:0)}).forEach(Me=>{let Pe=Me.closest(V1e);Pe?Pe.appendChild(Me.parentElement===Pe?Me:Me.closest(`${V1e} > *`)):Oe.appendChild(Me.parentElement===Oe?Me:Me.closest(`${V1e} > *`))}),be.sort((Me,Pe)=>Pe[1]-Me[1]).forEach(Me=>{var Pe;let Ee=(Pe=P.current)==null?void 0:Pe.querySelector(`${qD}[${cA}="${encodeURIComponent(Me[0])}"]`);Ee==null||Ee.parentElement.appendChild(Ee)})}function X(){let ge=ne().find(Oe=>Oe.getAttribute("aria-disabled")!=="true"),be=ge==null?void 0:ge.getAttribute(cA);B.setState("value",be||void 0)}function K(){var ge,be,Oe,Me;if(!r.current.search||o.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Pe=0;for(let Ee of n.current){let $e=(be=(ge=i.current.get(Ee))==null?void 0:ge.value)!=null?be:"",Se=(Me=(Oe=i.current.get(Ee))==null?void 0:Oe.keywords)!=null?Me:[],ze=F($e,Se);r.current.filtered.items.set(Ee,ze),ze>0&&Pe++}for(let[Ee,$e]of a.current)for(let Se of $e)if(r.current.filtered.items.get(Se)>0){r.current.filtered.groups.add(Ee);break}r.current.filtered.count=Pe}function Q(){var ge,be,Oe;let Me=Y();Me&&(((ge=Me.parentElement)==null?void 0:ge.firstChild)===Me&&((Oe=(be=Me.closest(qD))==null?void 0:be.querySelector(zzt))==null||Oe.scrollIntoView({block:"nearest"})),Me.scrollIntoView({block:"nearest"}))}function Y(){var ge;return(ge=P.current)==null?void 0:ge.querySelector(`${Xrt}[aria-selected="true"]`)}function ne(){var ge;return Array.from(((ge=P.current)==null?void 0:ge.querySelectorAll(TFe))||[])}function de(ge){let be=ne()[ge];be&&B.setState("value",be.getAttribute(cA))}function ce(ge){var be;let Oe=Y(),Me=ne(),Pe=Me.findIndex($e=>$e===Oe),Ee=Me[Pe+ge];(be=o.current)!=null&&be.loop&&(Ee=Pe+ge<0?Me[Me.length-1]:Pe+ge===Me.length?Me[0]:Me[Pe+ge]),Ee&&B.setState("value",Ee.getAttribute(cA))}function ae(ge){let be=Y(),Oe=be==null?void 0:be.closest(qD),Me;for(;Oe&&!Me;)Oe=ge>0?Zzt(Oe,qD):Xzt(Oe,qD),Me=Oe==null?void 0:Oe.querySelector(TFe);Me?B.setState("value",Me.getAttribute(cA)):ce(ge)}let ie=()=>de(ne().length-1),me=ge=>{ge.preventDefault(),ge.metaKey?ie():ge.altKey?ae(1):ce(1)},oe=ge=>{ge.preventDefault(),ge.metaKey?de(0):ge.altKey?ae(-1):ce(-1)};return k.createElement(pn.div,{ref:t,tabIndex:-1,...N,"cmdk-root":"",onKeyDown:ge=>{var be;(be=N.onKeyDown)==null||be.call(N,ge);let Oe=ge.nativeEvent.isComposing||ge.keyCode===229;if(!(ge.defaultPrevented||Oe))switch(ge.key){case"n":case"j":{b&&ge.ctrlKey&&me(ge);break}case"ArrowDown":{me(ge);break}case"p":case"k":{b&&ge.ctrlKey&&oe(ge);break}case"ArrowUp":{oe(ge);break}case"Home":{ge.preventDefault(),de(0);break}case"End":{ge.preventDefault(),ie();break}case"Enter":{ge.preventDefault();let Me=Y();if(Me){let Pe=new Event(Y2e);Me.dispatchEvent(Pe)}}}}},k.createElement("label",{"cmdk-label":"",htmlFor:z.inputId,id:z.labelId,style:e7t},c),Wpe(s,ge=>k.createElement(Jrt.Provider,{value:B},k.createElement(Qrt.Provider,{value:z},ge))))}),Uzt=k.forwardRef((s,t)=>{var r,n;let a=Qu(),i=k.useRef(null),l=k.useContext(ent),o=ez(),c=snt(s),d=(n=(r=c.current)==null?void 0:r.forceMount)!=null?n:l==null?void 0:l.forceMount;_5(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let h=rnt(a,i,[s.value,s.children,i],s.keywords),m=y5e(),x=T2(D=>D.value&&D.value===h.current),g=T2(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(Y2e,v),()=>D.removeEventListener(Y2e,v)},[g,s.onSelect,s.disabled]);function v(){var D,B;j(),(B=(D=c.current).onSelect)==null||B.call(D,h.current)}function j(){m.setState("value",h.current,!0)}if(!g)return null;let{disabled:b,value:N,onSelect:S,forceMount:T,keywords:A,...P}=s;return k.createElement(pn.div,{ref:y2(i,t),...P,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!x,"data-disabled":!!b,"data-selected":!!x,onPointerMove:b||o.getDisablePointerSelection()?void 0:j,onClick:b?void 0:v},s.children)}),qzt=k.forwardRef((s,t)=>{let{heading:r,children:n,forceMount:a,...i}=s,l=Qu(),o=k.useRef(null),c=k.useRef(null),d=Qu(),h=ez(),m=T2(g=>a||h.filter()===!1?!0:g.search?g.filtered.groups.has(l):!0);_5(()=>h.group(l),[]),rnt(l,o,[s.value,s.heading,c]);let x=k.useMemo(()=>({id:l,forceMount:a}),[a]);return k.createElement(pn.div,{ref:y2(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),Wpe(s,g=>k.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},k.createElement(ent.Provider,{value:x},g))))}),Vzt=k.forwardRef((s,t)=>{let{alwaysRender:r,...n}=s,a=k.useRef(null),i=T2(l=>!l.search);return!r&&!i?null:k.createElement(pn.div,{ref:y2(a,t),...n,"cmdk-separator":"",role:"separator"})}),Hzt=k.forwardRef((s,t)=>{let{onValueChange:r,...n}=s,a=s.value!=null,i=y5e(),l=T2(d=>d.search),o=T2(d=>d.selectedItemId),c=ez();return k.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),k.createElement(pn.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)}})}),Gzt=k.forwardRef((s,t)=>{let{children:r,label:n="Suggestions",...a}=s,i=k.useRef(null),l=k.useRef(null),o=T2(d=>d.selectedItemId),c=ez();return k.useEffect(()=>{if(l.current&&i.current){let d=l.current,h=i.current,m,x=new ResizeObserver(()=>{m=requestAnimationFrame(()=>{let g=d.offsetHeight;h.style.setProperty("--cmdk-list-height",g.toFixed(1)+"px")})});return x.observe(d),()=>{cancelAnimationFrame(m),x.unobserve(d)}}},[]),k.createElement(pn.div,{ref:y2(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":n,id:c.listId},Wpe(s,d=>k.createElement("div",{ref:y2(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Wzt=k.forwardRef((s,t)=>{let{open:r,onOpenChange:n,overlayClassName:a,contentClassName:i,container:l,...o}=s;return k.createElement(xpe,{open:r,onOpenChange:n},k.createElement(gpe,{container:l},k.createElement(SP,{"cmdk-overlay":"",className:a}),k.createElement(CP,{"aria-label":s.label,"cmdk-dialog":"",className:i},k.createElement(tnt,{ref:t,...o}))))}),Kzt=k.forwardRef((s,t)=>T2(r=>r.filtered.count===0)?k.createElement(pn.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),Yzt=k.forwardRef((s,t)=>{let{progress:r,children:n,label:a="Loading...",...i}=s;return k.createElement(pn.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Wpe(s,l=>k.createElement("div",{"aria-hidden":!0},l)))}),bp=Object.assign(tnt,{List:Gzt,Item:Uzt,Input:Hzt,Group:qzt,Separator:Vzt,Dialog:Wzt,Empty:Kzt,Loading:Yzt});function Zzt(s,t){let r=s.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function Xzt(s,t){let r=s.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function snt(s){let t=k.useRef(s);return _5(()=>{t.current=s}),t}var _5=typeof window>"u"?k.useEffect:k.useLayoutEffect;function dA(s){let t=k.useRef();return t.current===void 0&&(t.current=s()),t}function T2(s){let t=y5e(),r=()=>s(t.snapshot());return k.useSyncExternalStore(t.subscribe,r,r)}function rnt(s,t,r,n=[]){let a=k.useRef(),i=ez();return _5(()=>{var l;let o=(()=>{var d;for(let h of r){if(typeof h=="string")return h.trim();if(typeof h=="object"&&"current"in h)return h.current?(d=h.current.textContent)==null?void 0:d.trim():a.current}})(),c=n.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(cA,o),a.current=o}),a}var Qzt=()=>{let[s,t]=k.useState(),r=dA(()=>new Map);return _5(()=>{r.current.forEach(n=>n()),r.current=new Map},[s]),(n,a)=>{r.current.set(n,a),t({})}};function Jzt(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function Wpe({asChild:s,children:t},r){return s&&k.isValidElement(t)?k.cloneElement(Jzt(t),{ref:t.ref},r(t.props.children)):r(t)}var e7t={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ix=k.forwardRef(({className:s,...t},r)=>e.jsx(bp,{ref:r,className:Bt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Ix.displayName=bp.displayName;const t7t=({children:s,...t})=>e.jsx(vs,{...t,children:e.jsx(ys,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Ix,{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})})}),Px=k.forwardRef(({className:s,...t},r)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(fn,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(bp.Input,{ref:r,className:Bt("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})]}));Px.displayName=bp.Input.displayName;const Lx=k.forwardRef(({className:s,...t},r)=>e.jsx(bp.List,{ref:r,className:Bt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Lx.displayName=bp.List.displayName;const Dx=k.forwardRef((s,t)=>e.jsx(bp.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Dx.displayName=bp.Empty.displayName;const Rx=k.forwardRef(({className:s,...t},r)=>e.jsx(bp.Group,{ref:r,className:Bt("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}));Rx.displayName=bp.Group.displayName;const s7t=k.forwardRef(({className:s,...t},r)=>e.jsx(bp.Separator,{ref:r,className:Bt("-mx-1 h-px bg-border",s),...t}));s7t.displayName=bp.Separator.displayName;const vf=k.forwardRef(({className:s,...t},r)=>e.jsx(bp.Item,{ref:r,className:Bt("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}));vf.displayName=bp.Item.displayName;const r7t={event:{label:"Events",icon:pd,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:pl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Od,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:i0,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:jr,color:"bg-fuchsia-500/10 text-fuchsia-600"}},EFe=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=vr();k.useEffect(()=>{const x=g=>{g.key==="k"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),t(v=>!v))};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[]);const d=k.useCallback(async x=>{if(!x.trim()){i([]);return}o(!0);const g=`%${x}%`;try{const[v,j,b,N,S]=await Promise.all([H.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5),H.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${g},description.ilike.${g}`).limit(5),H.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5),H.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${g},description.ilike.${g}`).limit(5),H.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${g},description.ilike.${g}`).limit(5)]),T=[];v.data&&v.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),j.data&&j.data.forEach(A=>{T.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),b.data&&b.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),N.data&&N.data.forEach(A=>{T.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),S.data&&S.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(T)}catch(v){console.error("Search error:",v)}finally{o(!1)}},[]);k.useEffect(()=>{const x=setTimeout(()=>{d(r)},300);return()=>clearTimeout(x)},[r,d]);const h=x=>{t(!1),n(""),c(x)},m=a.reduce((x,g)=>(x[g.type]||(x[g.type]=[]),x[g.type].push(g),x),{});return e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>t(!0),children:[e.jsx(fn,{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(t7t,{open:s,onOpenChange:t,children:[e.jsx(Px,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),e.jsxs(Lx,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&r&&a.length===0&&e.jsxs(Dx,{children:['No results found for "',r,'"']}),!l&&!r&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(m).map(([x,g])=>{const v=r7t[x],j=v.icon;return e.jsx(Rx,{heading:v.label,children:g.map(b=>e.jsxs(vf,{value:`${b.type}-${b.id}-${b.title}`,onSelect:()=>h(b.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${v.color}`,children:e.jsx(j,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:b.title}),b.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:b.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs",children:v.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:al(new Date(b.date),{addSuffix:!0})})]})]},`${b.type}-${b.id}`))},x)})]})]})]})},n7t=({expiresAt:s,className:t,showUpgradeButton:r=!0})=>{const[n,a]=k.useState(null),i=vr();if(k.useEffect(()=>{const d=()=>{const m=new Date().getTime(),g=new Date(s).getTime()-m;if(g<=0){a({days:0,hours:0,minutes:0});return}const v=Math.floor(g/(1e3*60*60*24)),j=Math.floor(g%(1e3*60*60*24)/(1e3*60*60)),b=Math.floor(g%(1e3*60*60)/(1e3*60));a({days:v,hours:j,minutes:b})};d();const h=setInterval(d,6e4);return()=>clearInterval(h)},[s]),!n)return null;const l=n.days===0&&n.hours===0&&n.minutes===0,o=n.days<=1,c=n.days<=3&&!o;return l?e.jsxs("div",{className:Bt("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(od,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&e.jsxs(G,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Bt("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(cn,{className:Bt("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:Bt("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:Bt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.days,"d"]}),e.jsxs("span",{className:Bt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),e.jsxs("span",{className:Bt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),e.jsx("span",{className:Bt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&e.jsxs(G,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Bt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},a7t=()=>{const s=vr();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(Ne,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Ot,{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(od,{className:"h-8 w-8 text-destructive"})}),e.jsx(zt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Nr,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(Ne,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(De,{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(fr,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(G,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(Ne,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(De,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Sa,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs(G,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Nn,{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(Qs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},i7t=({hasUnseenBrief:s,onClick:t,className:r})=>e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"icon",onClick:t,className:Bt("relative transition-colors",s&&"text-primary hover:text-primary",r),children:[e.jsx(Cu,{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(Wl,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var v5e="Radio",[o7t,nnt]=yd(v5e),[l7t,Kpe]=o7t(v5e);function ant(s){const{__scopeRadio:t,checked:r=!1,children:n,disabled:a,form:i,name:l,onCheck:o,required:c,value:d="on",internal_do_not_use_render:h}=s,[m,x]=k.useState(null),[g,v]=k.useState(null),j=k.useRef(!1),b=m?!!i||!!m.closest("form"):!0,N={checked:r,disabled:a,required:c,name:l,form:i,value:d,control:m,setControl:x,hasConsumerStoppedPropagationRef:j,isFormControl:b,bubbleInput:g,setBubbleInput:v,onCheck:()=>o==null?void 0:o()};return e.jsx(l7t,{scope:t,...N,children:d7t(h)?h(N):n})}var int="RadioTrigger",b5e=k.forwardRef(({__scopeRadio:s,onClick:t,...r},n)=>{const{checked:a,disabled:i,value:l,setControl:o,onCheck:c,hasConsumerStoppedPropagationRef:d,isFormControl:h,bubbleInput:m}=Kpe(int,s),x=Qa(n,o);return e.jsx(pn.button,{type:"button",role:"radio","aria-checked":a,"data-state":dnt(a),"data-disabled":i?"":void 0,disabled:i,value:l,...r,ref:x,onClick:Or(t,g=>{a||c(),m&&h&&(d.current=g.isPropagationStopped(),d.current||g.stopPropagation())})})});b5e.displayName=int;var c7t=k.forwardRef((s,t)=>{const{__scopeRadio:r,name:n,checked:a,required:i,disabled:l,value:o,onCheck:c,form:d,...h}=s;return e.jsx(ant,{__scopeRadio:r,checked:a,disabled:l,required:i,onCheck:c,name:n,form:d,value:o,internal_do_not_use_render:({isFormControl:m})=>e.jsxs(e.Fragment,{children:[e.jsx(b5e,{...h,ref:t,__scopeRadio:r}),m&&e.jsx(_5e,{__scopeRadio:r})]})})});c7t.displayName=v5e;var ont="RadioIndicator",lnt=k.forwardRef((s,t)=>{const{__scopeRadio:r,forceMount:n,...a}=s,i=Kpe(ont,r);return e.jsx(qd,{present:n||i.checked,children:e.jsx(pn.span,{"data-state":dnt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});lnt.displayName=ont;var cnt="RadioBubbleInput",_5e=k.forwardRef(({__scopeRadio:s,...t},r)=>{const{control:n,checked:a,required:i,disabled:l,name:o,value:c,form:d,bubbleInput:h,setBubbleInput:m,hasConsumerStoppedPropagationRef:x}=Kpe(cnt,s),g=Qa(r,m),v=HB(a),j=MB(n);k.useEffect(()=>{const N=h;if(!N)return;const S=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(S,"checked").set,P=!x.current;if(v!==a&&A){const D=new Event("click",{bubbles:P});A.call(N,a),N.dispatchEvent(D)}},[h,v,a,x]);const b=k.useRef(a);return e.jsx(pn.input,{type:"radio","aria-hidden":!0,defaultChecked:b.current,required:i,disabled:l,name:o,value:c,form:d,...t,tabIndex:-1,ref:g,style:{...t.style,...j,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});_5e.displayName=cnt;function d7t(s){return typeof s=="function"}function dnt(s){return s?"checked":"unchecked"}var u7t=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ype="RadioGroup",[h7t]=yd(Ype,[U2,nnt]),unt=U2(),Zpe=nnt(),[m7t,f7t]=h7t(Ype),w5e=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:h=!0,onValueChange:m,...x}=s,g=unt(r),v=$2(d),[j,b]=Lh({prop:i,defaultProp:a??null,onChange:m,caller:Ype});return e.jsx(m7t,{scope:r,name:n,required:l,disabled:o,value:j,onValueChange:b,children:e.jsx(lpe,{asChild:!0,...g,orientation:c,dir:v,loop:h,children:e.jsx(pn.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:v,...x,ref:t})})})});w5e.displayName=Ype;var p7t="RadioGroupItem",x7t="RadioGroupItemProvider",hnt="RadioGroupItemTrigger",g7t="RadioGroupItemBubbleInput";function y7t(s){const{__scopeRadioGroup:t,value:r,disabled:n,children:a,internal_do_not_use_render:i}=s,l=f7t(x7t,t),o=Zpe(t),c=l.disabled||n;return e.jsx(ant,{...o,checked:l.value===r,disabled:c,required:l.required,name:l.name,value:r,onCheck:()=>l.onValueChange(r),internal_do_not_use_render:i,children:a})}var mnt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=unt(r),i=Zpe(r),{checked:l,disabled:o}=Kpe(hnt,i.__scopeRadio),c=k.useRef(null),d=Qa(t,c),h=k.useRef(!1);return k.useEffect(()=>{const m=g=>{u7t.includes(g.key)&&(h.current=!0)},x=()=>h.current=!1;return document.addEventListener("keydown",m),document.addEventListener("keyup",x),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",x)}},[]),e.jsx(cpe,{asChild:!0,...a,focusable:!o,active:l,children:e.jsx(b5e,{...i,...n,ref:d,onKeyDown:Or(n.onKeyDown,m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:Or(n.onFocus,()=>{var m;h.current&&((m=c.current)==null||m.click())})})})});mnt.displayName=hnt;var j5e=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,value:n,disabled:a,...i}=s;return e.jsx(y7t,{__scopeRadioGroup:r,value:n,disabled:a,internal_do_not_use_render:({isFormControl:l})=>e.jsxs(e.Fragment,{children:[e.jsx(mnt,{...i,ref:t,__scopeRadioGroup:r}),l&&e.jsx(fnt,{__scopeRadioGroup:r})]})})});j5e.displayName=p7t;var fnt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=Zpe(r);return e.jsx(_5e,{...a,...n,ref:t})});fnt.displayName=g7t;var v7t="RadioGroupIndicator",pnt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=Zpe(r);return e.jsx(lnt,{...a,...n,ref:t})});pnt.displayName=v7t;const Vb=k.forwardRef(({className:s,...t},r)=>e.jsx(w5e,{className:Bt("grid gap-2",s),...t,ref:r}));Vb.displayName=w5e.displayName;const Qd=k.forwardRef(({className:s,...t},r)=>e.jsx(j5e,{ref:r,className:Bt("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(pnt,{className:"flex items-center justify-center",children:e.jsx(Bd,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Qd.displayName=j5e.displayName;const b7t=({brief:s,open:t,onClose:r,onDismiss:n})=>{const{user:a}=As(),[i,l]=k.useState({}),[o,c]=k.useState({}),[d,h]=k.useState([]);k.useEffect(()=>{t&&a&&s.polls.length>0&&m()},[t,a,s.polls]);const m=async()=>{if(!a)return;const b=s.polls.map(S=>S.id),{data:N}=await H.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",b);if(N){const S={};N.forEach(T=>{S[T.poll_id]||(S[T.poll_id]=[]),S[T.poll_id].push(T.option_id)}),c(S)}},x=(b,N)=>{l(S=>({...S,[b]:N}))},g=(b,N,S)=>{l(T=>{const A=T[b]||[];return S?{...T,[b]:[...A,N]}:{...T,[b]:A.filter(P=>P!==N)}})},v=async b=>{if(!a)return;const N=i[b];if(!N||Array.isArray(N)&&N.length===0){ue.error("Please select an option");return}h(S=>[...S,b]);try{await H.from("levelup_brief_poll_responses").delete().eq("poll_id",b).eq("user_id",a.id);const S=Array.isArray(N)?N:[N],T=S.map(P=>({poll_id:b,option_id:P,user_id:a.id})),{error:A}=await H.from("levelup_brief_poll_responses").insert(T);if(A)throw A;c(P=>({...P,[b]:S})),ue.success("Response submitted!")}catch(S){console.error("Error submitting poll response:",S),ue.error("Failed to submit response")}finally{h(S=>S.filter(T=>T!==b))}},j=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(Cu,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Ge,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(bs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(ti,{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:j(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(b=>e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.open(b.url,"_blank"),className:"gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),b.title]},b.id))})]}),s.polls.map(b=>{var T,A;const N=((T=o[b.id])==null?void 0:T.length)>0,S=d.includes(b.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:b.question}),N&&e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),"Responded"]})]}),b.poll_type==="single"?e.jsx(Vb,{value:i[b.id]||((A=o[b.id])==null?void 0:A[0])||"",onValueChange:P=>x(b.id,P),className:"space-y-2",children:b.options.map(P=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:P.id,id:P.id}),e.jsx(he,{htmlFor:P.id,className:"cursor-pointer",children:P.option_text})]},P.id))}):e.jsx("div",{className:"space-y-2",children:b.options.map(P=>{const B=(i[b.id]||o[b.id]||[]).includes(P.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ei,{id:P.id,checked:B,onCheckedChange:z=>g(b.id,P.id,z)}),e.jsx(he,{htmlFor:P.id,className:"cursor-pointer",children:P.option_text})]},P.id)})}),e.jsx(G,{size:"sm",onClick:()=>v(b.id),disabled:S,children:S?"Submitting...":N?"Update Response":"Submit"})]},b.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(G,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},_7t=()=>{const{user:s}=As(),[t,r]=k.useState(null),[n,a]=k.useState(!1),[i,l]=k.useState(!0),[o,c]=k.useState(!1),d=k.useCallback(async()=>{if(!s){l(!1);return}try{const{data:v,error:j}=await H.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(j||!v){l(!1);return}const{data:b}=await H.from("levelup_brief_views").select("*").eq("brief_id",v.id).eq("user_id",s.id).maybeSingle(),[N,S]=await Promise.all([H.from("levelup_brief_links").select("*").eq("brief_id",v.id).order("sort_order"),H.from("levelup_brief_polls").select("*").eq("brief_id",v.id).order("sort_order")]),T=[];if(S.data)for(const z of S.data){const{data:F}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",z.id).order("sort_order");T.push({...z,options:F||[]})}const A={brief:v,links:N.data||[],polls:T};r(A);const P=!!b,D=(b==null?void 0:b.dismissed_at)!=null,B=localStorage.getItem(`brief-dismissed-${v.id}`)==="true";if(D||B)c(!1),a(!1);else if(!P)a(!0),c(!0);else if(v.show_frequency==="every_login")a(!0),c(!0);else if(v.show_frequency==="daily"){const z=new Date(b.viewed_at);(new Date().getTime()-z.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(v){console.error("Error fetching brief:",v)}finally{l(!1)}},[s]);k.useEffect(()=>{d()},[d]);const h=async()=>{if(!(!s||!t))try{const{data:v}=await H.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();v?await H.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",v.id):await H.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(v){console.error("Error marking brief as viewed:",v)}};return{currentBrief:t,shouldShowPopup:n,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),h()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:v,error:j}=await H.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(j&&console.error("Error checking existing brief view:",j),v){const{error:b}=await H.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",v.id).eq("user_id",s.id);b&&console.error("Error updating brief dismiss:",b)}else{const{error:b}=await H.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});b&&console.error("Error inserting brief dismiss:",b)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(v){console.error("Error dismissing brief:",v),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function w7t(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1),[a,i]=k.useState(null);k.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(m),t(!0);const x=g=>{g.preventDefault(),i(g)};return window.addEventListener("beforeinstallprompt",x),()=>{window.removeEventListener("beforeinstallprompt",x)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(Xa,{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(AO,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&a&&e.jsx(G,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(_r,{className:"h-4 w-4"})})]})]})}):null}const j7t=({children:s,onRefresh:t})=>{const[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(0),h=es(),m=80,x=120,g=k.useCallback(S=>{const T=c.current;T&&T.scrollTop<=0&&(d.current=S.touches[0].clientY,n(!0))},[]),v=k.useCallback(S=>{if(!r||l)return;const T=c.current;if(!T||T.scrollTop>0){n(!1),i(0);return}const P=S.touches[0].clientY-d.current;if(P>0){const B=Math.min(P*.5,x);i(B),B>10&&S.preventDefault()}},[r,l]),j=k.useCallback(async()=>{if(r)if(n(!1),a>=m&&!l){o(!0),i(m);try{t?await t():await h.invalidateQueries()}catch(S){console.error("Refresh failed:",S)}finally{o(!1),i(0)}}else i(0)},[r,a,l,t,h]),b=Math.min(a/m,1),N=b*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:g,onTouchMove:v,onTouchEnd:j,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:b},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${N}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Di,{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})]})},xnt=()=>{const{user:s}=As(),[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:g}=await H.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(g){a(!0),r(!1),c(!1);return}const{data:v}=await H.from("profiles").select("login_count").eq("id",s.id).single(),j=(v==null?void 0:v.login_count)||0;l(j);const b=sessionStorage.getItem("review-prompt-dismissed");r(j>=4&&!b)}catch(g){console.error("Error checking review eligibility:",g)}finally{c(!1)}})()},[s]);const d=k.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),h=k.useCallback(async(x,g)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:v}=await H.from("membership_reviews").insert({user_id:s.id,rating:x,review_text:g});if(v)throw v;return a(!0),r(!1),{success:!0,pointsAwarded:25}}catch(v){return console.error("Error submitting review:",v),{success:!1,error:v.message}}},[s]),m=k.useCallback(async()=>{if(s)try{await H.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(x){console.error("Error updating Google review status:",x)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:n,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:h,markPostedToGoogle:m}},N7t="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",k7t=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:r,submitReview:n,markPostedToGoogle:a}=xnt(),[i,l]=k.useState(!1),[o,c]=k.useState("review"),[d,h]=k.useState(0),[m,x]=k.useState(0),[g,v]=k.useState(""),[j,b]=k.useState(!1),[N,S]=k.useState(!1);if(t||!s&&!N)return null;const T=async()=>{if(d===0){nn({title:"Please select a rating",variant:"destructive"});return}b(!0);const D=await n(d,g);b(!1),D.success?(S(!0),nn({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):nn({title:"Error submitting review",description:D.error,variant:"destructive"})},A=async D=>{D&&(await navigator.clipboard.writeText(g||`${d} star rating for LevelUp!`),nn({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(N7t,"_blank")),l(!1),r()},P=()=>{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(Qn,{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:P,children:e.jsx(ys,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Fr,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(D=>e.jsx("button",{type:"button",onClick:()=>h(D),onMouseEnter:()=>x(D),onMouseLeave:()=>x(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Qn,{className:Bt("h-8 w-8 transition-colors",(m||d)>=D?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},D))}),e.jsx(ur,{placeholder:"Tell us about your experience (optional)",value:g,onChange:D=>v(D.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:P,className:"flex-1",children:"Maybe Later"}),e.jsx(G,{onClick:T,disabled:j||d===0,className:"flex-1",children:j?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Fr,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(G,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function S7t(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 j="vapid_public_key";let b=localStorage.getItem(j);if(!b){const{data:T,error:A}=await H.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(b=(T==null?void 0:T.vapidPublicKey)??null,!b)throw new Error("Missing VAPID public key");localStorage.setItem(j,b)}h(b);const N=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(N),r(Notification.permission);const S=await N.pushManager.getSubscription();a(!!S)}catch(j){console.error("Error initializing push notifications:",j)}finally{l(!1)}})()},[m]);const x=k.useCallback(async()=>{if(!m||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ue.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const v=await o.pushManager.getSubscription();if(v){try{await v.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:T}=await H.from("push_subscriptions").delete().eq("user_id",s.id);T&&console.warn("Failed to cleanup push_subscriptions rows:",T)}if(Notification.permission!=="granted"){const T=await Notification.requestPermission();if(r(T),T!=="granted")return T==="denied"?ue.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ue.error("Notification permission was dismissed. Please try again."),!1}const j=S7t(d);let b;try{b=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:j})}catch(T){console.error("PushManager.subscribe() failed:",T);const A=(T==null?void 0:T.message)||String(T);return A.includes("permission")?ue.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ue.error("Push configuration error. Please contact support."):A.includes("AbortError")?ue.error("Push subscription was cancelled. Please try again."):ue.error(`Failed to subscribe: ${A}`),!1}const N=b.toJSON(),{error:S}=await H.from("push_subscriptions").upsert({user_id:s.id,endpoint:N.endpoint,p256dh_key:N.keys.p256dh,auth_key:N.keys.auth},{onConflict:"user_id,endpoint"});if(S)throw console.error("Error saving subscription:",S),ue.error("Failed to save notification preferences. Please try again."),S;return a(!0),ue.success("Push notifications enabled!"),!0}catch(v){if(console.error("Error subscribing to push notifications:",v),!(v instanceof Error&&v.message.includes("toast"))){const j=v instanceof Error?v.message:"Unknown error";ue.error("Failed to enable push notifications: "+j)}return!1}finally{l(!1)}},[m,o,s,d]),g=k.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const v=await o.pushManager.getSubscription();return v&&await v.unsubscribe(),await H.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ue.success("Push notifications disabled"),!0}catch(v){console.error("Error unsubscribing:",v);const j=v instanceof Error?v.message:"Unknown error";return ue.error("Failed to disable push notifications: "+j),!1}finally{l(!1)}},[o,s]);return{isSupported:m,permission:t,isSubscribed:n,isLoading:i,vapidPublicKey:d,subscribe:x,unsubscribe:g}}const H1e="push_notification_prompt_dismissed",C7t=["/dashboard","/admin"],T7t=()=>{const{user:s}=As(),{isSupported:t,isSubscribed:r,isLoading:n,subscribe:a}=gnt(),i=sc(),[l,o]=k.useState(!1),[c,d]=k.useState(!1),h=C7t.some(g=>i.pathname===g||i.pathname.startsWith(`${g}/`));k.useEffect(()=>{if(h){o(!1);return}if(!s||!t||r||n||localStorage.getItem(`${H1e}_${s.id}`))return;const v=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(v)},[s,t,r,n,h]);const m=async()=>{d(!0);const g=await a();d(!1),g&&(s&&localStorage.setItem(`${H1e}_${s.id}`,"true"),o(!1))},x=()=>{s&&localStorage.setItem(`${H1e}_${s.id}`,"true"),o(!1)};return!t||r||h?null:e.jsx(vs,{open:l,onOpenChange:g=>!g&&x(),children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:e.jsx(Rm,{className:"h-6 w-6 text-primary"})}),e.jsx(bs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Fr,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),e.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(G,{onClick:m,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(G,{variant:"ghost",onClick:x,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},AFe=s=>{let t;const r=new Set,n=(d,h)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const x=t;t=h??(typeof m!="object"||m===null)?m:Object.assign({},t,m),r.forEach(g=>g(t,x))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=t=s(n,a,o);return o},E7t=s=>s?AFe(s):AFe,A7t=s=>s;function M7t(s,t=A7t){const r=wt.useSyncExternalStore(s.subscribe,wt.useCallback(()=>t(s.getState()),[s,t]),wt.useCallback(()=>t(s.getInitialState()),[s,t]));return wt.useDebugValue(r),r}const MFe=s=>{const t=E7t(s),r=n=>M7t(t,n);return Object.assign(r,t),r},I7t=s=>s?MFe(s):MFe;function P7t(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 Z2e=s=>t=>{try{const r=s(t);return r instanceof Promise?r:{then(n){return Z2e(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return Z2e(n)(r)}}}},L7t=(s,t)=>(r,n,a)=>{let i={storage:P7t(()=>window.localStorage),partialize:b=>b,version:0,merge:(b,N)=>({...N,...b}),...t},l=!1,o=0;const c=new Set,d=new Set;let h=i.storage;if(!h)return s((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),r(...b)},n,a);const m=()=>{const b=i.partialize({...n()});return h.setItem(i.name,{state:b,version:i.version})},x=a.setState;a.setState=(b,N)=>(x(b,N),m());const g=s((...b)=>(r(...b),m()),n,a);a.getInitialState=()=>g;let v;const j=()=>{var b,N;if(!h)return;const S=++o;l=!1,c.forEach(A=>{var P;return A((P=n())!=null?P:g)});const T=((N=i.onRehydrateStorage)==null?void 0:N.call(i,(b=n())!=null?b:g))||void 0;return Z2e(h.getItem.bind(h))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const P=i.migrate(A.state,A.version);return P instanceof Promise?P.then(D=>[!0,D]):[!0,P]}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 P;if(S!==o)return;const[D,B]=A;if(v=i.merge(B,(P=n())!=null?P:g),r(v,!0),D)return m()}).then(()=>{S===o&&(T==null||T(n(),void 0),v=n(),l=!0,d.forEach(A=>A(v)))}).catch(A=>{S===o&&(T==null||T(void 0,A))})};return a.persist={setOptions:b=>{i={...i,...b},b.storage&&(h=b.storage)},clearStorage:()=>{h==null||h.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>j(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},i.skipHydration||j(),v||g},D7t=L7t,Xpe=I7t()(D7t((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 ey(){const{user:s}=As(),{data:t,isLoading:r}=gt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:n,error:a}=await H.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw a;return n},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:r,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const IFe="dashboard-sidebar-collapsed",_s=({children:s,title:t})=>{var ve;const{user:r,signOut:n,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=As(),{isAssistant:c,actingAsAgent:d,hasPermission:h}=$4e(),{isImpersonating:m}=ipe(),g=(c&&!!d?40:0)+(m?40:0),{avatarUrl:v}=krt(r==null?void 0:r.id),{isTrial:j,isExpired:b,expiresAt:N}=ZBt(r==null?void 0:r.id),{isMarketplaceEnabled:S}=Crt(),{currentBrief:T,shouldShowPopup:A,hasUnseenBrief:P,openBrief:D,closeBrief:B,dismissBrief:z}=_7t(),{unreadCount:F}=XBt(),{openCount:$}=QBt(),{data:X}=Xg(),K=!!X,Y=Xpe(rt=>rt.cartItems).reduce((rt,Re)=>rt+Re.quantity,0),{leadSite:ne,hasLeadSite:de,siteUrl:ce}=ey(),ae=vr(),ie=sc(),[me,oe]=k.useState(null);k.useEffect(()=>{r!=null&&r.id&&H.from("profiles").select("name").eq("id",r.id).single().then(({data:rt})=>{rt!=null&&rt.name&&oe(rt.name)})},[r==null?void 0:r.id]);const ge=me||((ve=r==null?void 0:r.user_metadata)==null?void 0:ve.name)||(r==null?void 0:r.email)||"User",[be,Oe]=k.useState(()=>typeof window<"u"?localStorage.getItem(IFe)==="true":!1);k.useEffect(()=>{localStorage.setItem(IFe,String(be))},[be]);const[Me,Pe]=k.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),Ee=rt=>{Pe(Re=>({...Re,[rt]:!Re[rt]}))},$e=rt=>rt.split(" ").map(Re=>Re[0]).join("").toUpperCase().slice(0,2),Se=rt=>ie.pathname===rt,ze=rt=>rt.some(Re=>ie.pathname===Re),Te=({path:rt,icon:Re,label:Qe,badgeCount:Ke})=>{const Ce=e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Se(rt)&&"bg-sidebar-accent text-sidebar-accent-foreground",be?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ae(rt),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Re,{className:"h-4 w-4 shrink-0"}),be&&Ke!=null&&Ke>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!be&&Qe,!be&&Ke!=null&&Ke>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ke>9?"9+":Ke})]});return be?e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:Ce}),e.jsxs(Wl,{side:"right",className:"flex items-center gap-2",children:[Qe,Ke!=null&&Ke>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ke>9?"9+":Ke})]})]}):Ce},ye=({id:rt,label:Re,icon:Qe,children:Ke,activePaths:Ce,showBetaBadge:nt,defaultPath:$t,badgeCount:lt})=>{if(be){const it=$t||Ce[0];return e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:Bt("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",ze(Ce)&&"text-primary"),onClick:()=>ae(it),children:e.jsxs("div",{className:"relative",children:[e.jsx(Qe,{className:"h-4 w-4"}),lt!=null&<>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(Wl,{side:"right",className:"flex items-center gap-2",children:[Re,nt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),lt!=null&<>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:lt>9?"9+":lt})]})]})}return e.jsxs(bx,{open:Me[rt],onOpenChange:()=>Ee(rt),children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ze(Ce)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(Qe,{className:"h-4 w-4"}),Re,nt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[lt!=null&<>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:lt>9?"9+":lt}),e.jsx(so,{className:Bt("h-4 w-4 transition-transform duration-200",Me[rt]&&"rotate-180")})]})]})}),e.jsx(wx,{className:"pl-4 space-y-1 mt-1",children:Ke})]})},ct=({isMobile:rt=!1})=>{const Re=rt?!1:be;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Bt("p-3 border-b border-sidebar-border",Re?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[Re?e.jsx("img",{src:nzt,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:rzt,alt:"LevelUp",className:"h-8 w-auto"}),!rt&&e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Oe(!Re),children:e.jsx(Vo,{className:Bt("h-4 w-4 transition-transform duration-300",Re&&"rotate-180")})})}),e.jsx(Wl,{side:"right",children:Re?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(ti,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Bt("p-3 space-y-1",Re&&"flex flex-col items-center"),children:[rt&&j&&!b&&e.jsx("button",{type:"button",onClick:()=>ae("/subscription"),className:Bt("relative w-full overflow-hidden rounded-md p-[1.5px] mb-2","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(jr,{className:"h-4 w-4 text-amber-500 animate-pulse"}),e.jsx("span",{className:"flex-1 text-left bg-[linear-gradient(90deg,#f59e0b,#ef4444,#a855f7)] bg-clip-text text-transparent",children:"Ready to Upgrade?"}),N&&e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30",children:[Math.max(0,Math.ceil((new Date(N).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(Te,{path:"/dashboard",icon:A3,label:"Dashboard"}),e.jsx(Te,{path:"/apps",icon:bg,label:"Apps & Tools"}),be?e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/levelup-u"),children:[e.jsx(Od,{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(Wl,{side:"right",className:"flex items-center gap-2",children:["LevelUp U",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/levelup-u"),children:[e.jsx(Od,{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(Te,{path:"/events",icon:pd,label:"Events"}),e.jsxs(ye,{id:"agentos",label:"Agent OS",icon:XA,activePaths:["/mission-control","/mission-control/contacts","/mission-control/plans","/mission-control/popbys","/mission-control/video-library","/mission-control/scorecard","/mission-control/listings","/mission-control/pipeline","/mission-control/tasks","/mission-control/smart-drips","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/signals","/mission-control/connect-page","/mission-control/client-portals","/mission-control/vendors","/mission-control/portal-referrals"],showBetaBadge:!0,defaultPath:"/mission-control",children:[h("contacts")&&e.jsx(Te,{path:"/mission-control",icon:hi,label:"Mission Control"}),h("contacts")&&!Re&&e.jsxs(bx,{open:Me.contacts,onOpenChange:()=>Ee("contacts"),children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ze(["/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(fr,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(so,{className:Bt("h-3.5 w-3.5 transition-transform duration-200",Me.contacts&&"rotate-180")})]})}),e.jsxs(wx,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(Te,{path:"/mission-control/contacts",icon:fr,label:"All Contacts"}),e.jsx(Te,{path:"/mission-control/relationship-scorecard",icon:Ch,label:"Relationship Report"}),e.jsx(Te,{path:"/mission-control/sphere-gaps",icon:TO,label:"Sphere Gaps"}),e.jsx(Te,{path:"/mission-control/sent-emails",icon:Zr,label:"Sent Emails"}),e.jsx(Te,{path:"/mission-control/connect-page",icon:rl,label:"Connect Page"})]})]}),h("contacts")&&Re&&e.jsx(Te,{path:"/mission-control/contacts",icon:fr,label:"Contacts"}),h("contacts")&&e.jsx(Te,{path:"/mission-control/plans",icon:pd,label:"TouchPlans"}),h("pipeline")&&e.jsx(Te,{path:"/mission-control/pipeline",icon:Uv,label:"Deal Pipeline"}),h("pipeline")&&e.jsx(Te,{path:"/mission-control/tasks",icon:Lb,label:"Tasks"}),h("popbys")&&e.jsx(Te,{path:"/mission-control/popbys",icon:li,label:"Popbys"}),h("videos")&&e.jsx(Te,{path:"/mission-control/video-library",icon:sn,label:"Video Library"}),h("scorecard")&&e.jsx(Te,{path:"/mission-control/scorecard",icon:ao,label:"Scorecard"}),h("listings")&&e.jsx(Te,{path:"/mission-control/listings",icon:Sa,label:"Listing Exchange"}),e.jsx(Te,{path:"/mission-control/client-portals",icon:jr,label:"Client Portals"}),e.jsx(Te,{path:"/mission-control/signals",icon:hM,label:"Signals"}),!Re&&e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/mission-control/smart-drips"),children:[e.jsx(Xu,{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"})]}),Re&&e.jsx(Te,{path:"/mission-control/smart-drips",icon:Xu,label:"Smart Drips"})]}),de&&ne&&e.jsxs(ye,{id:"website",label:"My Website",icon:gc,activePaths:[`/admin/lead-sites/${ne.id}/edit`],defaultPath:`/admin/lead-sites/${ne.id}/edit`,children:[Re?e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ce||"#","_blank"),children:e.jsx(jn,{className:"h-4 w-4"})})}),e.jsx(Wl,{side:"right",children:"View Site"})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ce||"#","_blank"),children:[e.jsx(jn,{className:"h-4 w-4"}),"View Site",e.jsx(Yr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(Te,{path:`/my-website/${ne.id}/edit`,icon:Ta,label:"Edit Website"}),e.jsx(Te,{path:"/my-website/mls-listings",icon:Cn,label:"MLS Listings"}),e.jsx(Te,{path:"/my-website/market-report",icon:ao,label:"Market Reports"}),e.jsx(Te,{path:"/mission-control/website-activity",icon:Ch,label:"Website Activity"}),e.jsx(Te,{path:"/m",icon:zg,label:"Mobile Command"})]}),e.jsxs(ye,{id:"marketing",label:"Marketing",icon:Cu,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps"],defaultPath:"/templates",children:[e.jsx(Te,{path:"/templates",icon:pl,label:"Templates"}),e.jsx(Te,{path:"/social-swag-2",icon:zg,label:"Social Swag"}),be?e.jsxs(hc,{delayDuration:0,children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/newsletters"),children:[e.jsx(Vv,{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(Wl,{side:"right",className:"flex items-center gap-2",children:["Newsletter Pro",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/newsletters"),children:[e.jsx(Vv,{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(Te,{path:"/website-apps",icon:jr,label:"Website Apps"})]}),e.jsxs(ye,{id:"learning",label:"Learning",icon:Th,activePaths:["/academy","/toolbox"],defaultPath:"/academy",children:[e.jsx(Te,{path:"/academy",icon:Od,label:"Academy"}),e.jsx(Te,{path:"/toolbox",icon:i0,label:"Toolbox"})]}),e.jsxs(ye,{id:"community",label:"Community",icon:bi,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:F,children:[e.jsx(Te,{path:"/community",icon:fr,label:"Community",badgeCount:F}),e.jsx(Te,{path:"/wishlist",icon:Yj,label:"Wishlist",badgeCount:$}),!Re&&e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open("https://www.facebook.com/share/g/1CC6thti2V/","_blank"),children:[e.jsx(Yr,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(ye,{id:"goods",label:"The Goods",icon:lp,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[S&&!Re&&e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ie.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/marketplace"),children:[e.jsx(lp,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),S&&Re&&e.jsx(Te,{path:"/marketplace",icon:lp,label:"Marketplace"}),e.jsx(Te,{path:"/reward-store",icon:Zi,label:"Reward Store"}),e.jsx(Te,{path:"/refer-friends",icon:li,label:"Refer & Earn"})]}),e.jsxs(ye,{id:"help",label:"Help & Services",icon:Ab,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(Te,{path:"/support",icon:oM,label:"Support"}),e.jsx(Te,{path:"/additional-services",icon:jr,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(Te,{path:"/coaching",icon:Od,label:"Coaching"})}),e.jsx(R7t,{}),a&&e.jsxs(e.Fragment,{children:[!Re&&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"})}),Re?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(Te,{path:"/admin",icon:Kc,label:"Admin Dashboard"})}):e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ie.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/admin"),children:[e.jsx(Kc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!Re&&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"})}),Re?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(Te,{path:"/my-brokerage",icon:Sa,label:"My Brokerage"}),e.jsx(Te,{path:"/brokerage/help-board",icon:Hy,label:"Help Board"}),e.jsx(Te,{path:"/brokerage-content",icon:Th,label:"Brokerage Content"})]}),K&&!i&&e.jsx(Te,{path:"/my-team",icon:fr,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Te,{path:"/brokerage/dashboard",icon:lo,label:"Manage Brokerages"}),e.jsx(Te,{path:"/brokerage/teams",icon:fr,label:"Teams"}),e.jsx(Te,{path:"/brokerage/recruiting",icon:Cu,label:"Recruiting"}),e.jsx(Te,{path:"/brokerage/vendors",icon:Gj,label:"Vendors"}),e.jsx(Te,{path:"/brokerage-resources",icon:Yu,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/my-brokerage"),children:[e.jsx(Sa,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage/help-board"),children:[e.jsx(Hy,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage-content"),children:[e.jsx(Th,{className:"h-4 w-4"}),"Brokerage Content"]})]}),K&&!i&&e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/my-team"),children:[e.jsx(fr,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage/dashboard"),children:[e.jsx(lo,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage/teams"),children:[e.jsx(fr,{className:"h-4 w-4"}),"Teams",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"New"})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage/recruiting"),children:[e.jsx(Cu,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage/vendors"),children:[e.jsx(Gj,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/brokerage-resources"),children:[e.jsx(Yu,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Se("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ae("/profile"),children:[e.jsx(Bi,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:n,children:[e.jsx(cM,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(A_,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[j&&b&&ie.pathname!=="/subscription"&&e.jsx(a7t,{}),typeof document<"u"&&pf.createPortal(e.jsx("aside",{className:Bt("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",be?"w-16":"w-56"),style:{top:`${g}px`,height:`calc(100vh - ${g}px)`},children:e.jsx(ct,{})}),document.body),e.jsxs("div",{className:Bt("flex-1 flex flex-col overflow-hidden transition-all duration-300",be?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${g}px)`,marginTop:`${g}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(G2,{children:[e.jsx(C3e,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(D3,{className:"h-5 w-5"})})}),e.jsx(I_,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(ct,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:azt,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(EFe,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[j&&!b&&N&&e.jsx(n7t,{expiresAt:N,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(EFe,{})}),T&&e.jsx(i7t,{hasUnseenBrief:P,onClick:D}),S&&e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ae("/marketplace/cart"),children:[e.jsx(lp,{className:"h-5 w-5"}),Y>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:Y>99?"99+":Y})]}),e.jsx(Azt,{}),e.jsx(W2e,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ge.split(" ")[0],"!"]}),e.jsxs(lu,{children:[e.jsx(cu,{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(vn,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(ga,{src:v||void 0}),e.jsx(bn,{className:"bg-primary text-primary-foreground font-medium text-sm",children:$e(ge)})]})})}),e.jsxs(Vd,{align:"end",className:"w-48",children:[e.jsxs(Da,{onClick:()=>ae("/profile"),className:"cursor-pointer",children:[e.jsx(Bi,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Da,{onClick:()=>ae("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(B3,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Da,{onClick:()=>ae("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(B3,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(y_,{}),e.jsxs(Da,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(cM,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(j7t,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),T&&e.jsx(b7t,{brief:T,open:A,onClose:B,onDismiss:z}),e.jsx(w7t,{}),e.jsx(k7t,{}),e.jsx(T7t,{})]})]})})};function R7t(){const{user:s}=As(),t=sc(),r=vr(),{data:n}=gt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await H.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!n)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsxs(G,{variant:"ghost",size:"sm",className:`w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>r("/my-coach"),children:[e.jsx(Od,{className:"h-4 w-4"}),"My Coach"]})})}const O7t=()=>{const{user:s}=As(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(""),o=async m=>{var x;if(!(s!=null&&s.email)){ue.error("Please sign in to upgrade");return}r(!0),a(m);try{const{data:g,error:v}=await H.functions.invoke("create-checkout",{body:{tier:m,email:s.email,name:((x=s.user_metadata)==null?void 0:x.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(v)throw v;if(g!=null&&g.url)window.open(g.url,"_blank","noopener,noreferrer"),ue.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(g){console.error("Checkout error:",g),ue.error(g.message||"Failed to start checkout. Please try again.")}finally{r(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],h=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(_s,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(he,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(ke,{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(Ne,{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(Ot,{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(fr,{className:"h-7 w-7 text-primary"})}),e.jsx(zt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Nr,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hn,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&n==="individual_agent"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(Ne,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Sa,{className:"h-7 w-7 text-amber-600"})}),e.jsx(zt,{className:"text-xl",children:"Brokerage"}),e.jsx(Nr,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hn,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&n==="brokerage_under_25"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(Ne,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-purple-500/10 flex items-center justify-center",children:e.jsx(Sa,{className:"h-7 w-7 text-purple-600"})}),e.jsx(zt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Nr,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:h.map((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hn,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&n==="brokerage_over_25"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(Ne,{className:"bg-muted/50",children:e.jsxs(De,{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(Nn,{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(Qs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},F7t=()=>{const{user:s,loading:t,isBrokerageManager:r,brokerageId:n}=As(),a=vr(),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(!1);k.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),k.useEffect(()=>{!t&&s&&n&&a("/profile?setup=true")},[s,t,n,a]);const m=async()=>{if(!i.trim()){ue.error("Please enter a brokerage name");return}const{data:x}=await H.auth.getSession(),g=x.session;if(!s||!g){ue.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!g,userId:s==null?void 0:s.id});const{data:v,error:j}=await H.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:v,error:j}),j)throw j;if(!(v!=null&&v.ok))throw new Error((v==null?void 0:v.error)||"Failed to create brokerage");c(!1),h(!0),ue.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(v){console.error("Error creating brokerage:",v),ue.error(v.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{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(zt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Nr,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(mi,{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(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Sa,{className:"w-10 h-10 text-primary"})}),e.jsx(zt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Nr,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ke,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:x=>l(x.target.value),onKeyDown:x=>x.key==="Enter"&&m()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(fr,{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(mi,{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(mi,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(mi,{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(mi,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(G,{onClick:m,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(Ga,{className:"w-4 h-4 ml-2"})]})]})]})})},PFe=()=>{const s=vr(),[t,r]=k.useState("verifying"),[n,a]=k.useState("");k.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await H.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await H.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 H.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(h){console.log("Trial claim hook (non-critical):",h)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{r("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),r("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{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(zt,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(Nr,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&n]})]}),(t==="already_claimed"||t==="error")&&e.jsx(De,{children:e.jsx(G,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},B7t=()=>{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:t3e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(Ne,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx(zt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Nr,{className:"text-gray-600 pt-2",children:n?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(De,{className:"space-y-4",children:[n?e.jsx(G,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx(G,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},z7t=()=>{const s=vr(),[t]=Lc(),[r,n]=k.useState(t.get("code")||""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,P]=k.useState(null),[D,B]=k.useState(null),[z,F]=k.useState(null);k.useEffect(()=>{const Q=t.get("code");Q&&(n(Q),$(Q))},[t]);const $=async Q=>{j(!0);const{data:Y,error:ne}=await H.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(ne||!Y){ue.error("Invalid invite code"),j(!1);return}if(!Y.is_active){ue.error("This invite code is no longer active"),j(!1);return}if(Y.max_uses&&Y.uses_count>=Y.max_uses){ue.error("This invite code has reached its maximum uses"),j(!1);return}if(Y.expires_at&&new Date(Y.expires_at){Q.preventDefault(),$(r)},K=async Q=>{var Y;if(Q.preventDefault(),!c.trim()){ue.error("Please enter your name");return}if(l.length<6){ue.error("Password must be at least 6 characters");return}g(!0);try{const ne=`${window.location.origin}/`,{data:de,error:ce}=await H.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:ne,data:{name:c.trim()}}});if(ce){ce.message.includes("already registered")?ue.error("This email is already registered. Please sign in instead."):ue.error(ce.message);return}de.user&&(await H.rpc("add_default_signup_tag",{user_id:de.user.id}),A?await H.functions.invoke("assign-brokerage",{body:{userId:de.user.id,brokerageId:A}}):z?await H.functions.invoke("assign-brokerage",{body:{userId:de.user.id,trialDays:z}}):await H.functions.invoke("assign-brokerage",{body:{userId:de.user.id,grandfathered:!0}}),S&&await H.from("invite_codes").update({uses_count:((Y=(await H.from("invite_codes").select("uses_count").eq("id",S).single()).data)==null?void 0:Y.uses_count)+1}).eq("id",S),ue.success("Account created! You can now access the dashboard."),s("/dashboard"))}catch(ne){console.error("Signup error:",ne),ue.error("An unexpected error occurred")}finally{g(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx(zt,{className:"text-2xl font-bold text-primary",children:D?`Join ${D}`:"Join LevelUp"}),e.jsx(Nr,{children:b?D?`Create your account to join ${D}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(De,{children:b?e.jsxs("form",{onSubmit:K,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Full Name"}),e.jsx(ke,{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(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{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(he,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:"password",type:h?"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(!h),children:h?e.jsx(am,{className:"h-4 w-4"}):e.jsx(jn,{className:"h-4 w-4"})})]})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:x,children:x?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:X,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(ke,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:r,onChange:Q=>n(Q.target.value),required:!0,autoFocus:!0})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},Qpe=()=>{const{user:s,isCoach:t}=As();return gt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:r,error:n}=await H.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return r}})},$7t=()=>{const{data:s}=Qpe();return gt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await H.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 H.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}))}})},U7t=()=>{const{user:s}=As();return gt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await H.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 H.from("coaches").select("*").eq("id",n.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await H.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...n,coach:a,coachProfile:i}}})},q7t=s=>gt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await H.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return null;const{data:n}=await H.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:n}}}),ynt=s=>gt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await H.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(r)throw r;return t||[]}}),vnt=s=>gt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await H.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(r)throw r;return t||[]}}),V7t=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function H7t(){const s=vr(),{data:t,isLoading:r}=Qpe(),{data:n=[],isLoading:a}=$7t();if(r)return e.jsx(_s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(_s,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Od,{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."})]})});V7t.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(_s,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(jr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(G1e,{icon:Od,label:"Active agents",value:i}),e.jsx(G1e,{icon:pd,label:"This month",value:"—"}),e.jsx(G1e,{icon:xc,label:"Momentum",value:"🔥"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Your Roster"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):n.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(l=>{var o,c,d,h;return e.jsx(Ne,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(De,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(vn,{className:"h-14 w-14",children:[e.jsx(ga,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(bn,{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(Ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(h=l.agent)==null?void 0:h.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Ge,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",al(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function G1e({icon:s,label:t,value:r}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-white/15 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:r}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}var Jpe="Tabs",[G7t]=yd(Jpe,[U2]),bnt=U2(),[W7t,N5e]=G7t(Jpe),_nt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,h=$2(o),[m,x]=Lh({prop:n,onChange:a,defaultProp:i??"",caller:Jpe});return e.jsx(W7t,{scope:r,baseId:Qu(),value:m,onValueChange:x,orientation:l,dir:h,activationMode:c,children:e.jsx(pn.div,{dir:h,"data-orientation":l,...d,ref:t})})});_nt.displayName=Jpe;var wnt="TabsList",jnt=k.forwardRef((s,t)=>{const{__scopeTabs:r,loop:n=!0,...a}=s,i=N5e(wnt,r),l=bnt(r);return e.jsx(lpe,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:n,children:e.jsx(pn.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});jnt.displayName=wnt;var Nnt="TabsTrigger",knt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,disabled:a=!1,...i}=s,l=N5e(Nnt,r),o=bnt(r),c=Tnt(l.baseId,n),d=Ent(l.baseId,n),h=n===l.value;return e.jsx(cpe,{asChild:!0,...o,focusable:!a,active:h,children:e.jsx(pn.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:Or(s.onMouseDown,m=>{!a&&m.button===0&&m.ctrlKey===!1?l.onValueChange(n):m.preventDefault()}),onKeyDown:Or(s.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&l.onValueChange(n)}),onFocus:Or(s.onFocus,()=>{const m=l.activationMode!=="manual";!h&&!a&&m&&l.onValueChange(n)})})})});knt.displayName=Nnt;var Snt="TabsContent",Cnt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,forceMount:a,children:i,...l}=s,o=N5e(Snt,r),c=Tnt(o.baseId,n),d=Ent(o.baseId,n),h=n===o.value,m=k.useRef(h);return k.useEffect(()=>{const x=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(x)},[]),e.jsx(qd,{present:a||h,children:({present:x})=>e.jsx(pn.div,{"data-state":h?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!x,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:m.current?"0s":void 0},children:x&&i})})});Cnt.displayName=Snt;function Tnt(s,t){return`${s}-trigger-${t}`}function Ent(s,t){return`${s}-content-${t}`}var K7t=_nt,Ant=jnt,Mnt=knt,Int=Cnt;const Rn=K7t,Dn=k.forwardRef(({className:s,...t},r)=>e.jsx(Ant,{ref:r,className:Bt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Dn.displayName=Ant.displayName;const Xt=k.forwardRef(({className:s,...t},r)=>e.jsx(Mnt,{ref:r,className:Bt("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}));Xt.displayName=Mnt.displayName;const as=k.forwardRef(({className:s,...t},r)=>e.jsx(Int,{ref:r,className:Bt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));as.displayName=Int.displayName;function Pnt({assignmentId:s}){const{user:t}=As(),r=es(),[n,a]=k.useState(""),[i,l]=k.useState(!1),o=k.useRef(null),{data:c=[]}=gt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await H.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(m)throw m;return h||[]}});k.useEffect(()=>{if(!s)return;const h=H.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()=>{H.removeChannel(h)}},[s,r]),k.useEffect(()=>{var h;(h=o.current)==null||h.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const h=n.trim();if(!h||!t)return;l(!0);const{error:m}=await H.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:h});l(!1),m||a("")};return e.jsxs(Ne,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(h=>{const m=h.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Bt("flex gap-2",m?"justify-end":"justify-start"),children:[!m&&e.jsx(vn,{className:"h-8 w-8 mt-1",children:e.jsx(bn,{className:"text-xs",children:(h.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Bt("max-w-[75%] rounded-2xl px-3 py-2 text-sm",m?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:h.body}),e.jsx("p",{className:Bt("text-[10px] mt-1",m?"text-white/70":"text-muted-foreground"),children:al(new Date(h.created_at),{addSuffix:!0})})]})]},h.id)})}),e.jsx(De,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(ur,{value:n,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx(G,{onClick:d,disabled:i||!n.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Zr,{className:"h-4 w-4"})})]})})]})}var k5e="Progress",S5e=100,[Y7t]=yd(k5e),[Z7t,X7t]=Y7t(k5e),Lnt=k.forwardRef((s,t)=>{const{__scopeProgress:r,value:n=null,max:a,getValueLabel:i=Q7t,...l}=s;(a||a===0)&&!LFe(a)&&console.error(J7t(`${a}`,"Progress"));const o=LFe(a)?a:S5e;n!==null&&!DFe(n,o)&&console.error(e9t(`${n}`,"Progress"));const c=DFe(n,o)?n:null,d=ehe(c)?i(c,o):void 0;return e.jsx(Z7t,{scope:r,value:c,max:o,children:e.jsx(pn.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":ehe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":Ont(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});Lnt.displayName=k5e;var Dnt="ProgressIndicator",Rnt=k.forwardRef((s,t)=>{const{__scopeProgress:r,...n}=s,a=X7t(Dnt,r);return e.jsx(pn.div,{"data-state":Ont(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...n,ref:t})});Rnt.displayName=Dnt;function Q7t(s,t){return`${Math.round(s/t*100)}%`}function Ont(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function ehe(s){return typeof s=="number"}function LFe(s){return ehe(s)&&!isNaN(s)&&s>0}function DFe(s,t){return ehe(s)&&!isNaN(s)&&s<=t&&s>=0}function J7t(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${S5e}\`.`}function e9t(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 ${S5e} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var Fnt=Lnt,t9t=Rnt;const ri=k.forwardRef(({className:s,value:t,...r},n)=>e.jsx(Fnt,{ref:n,className:Bt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...r,children:e.jsx(t9t,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ri.displayName=Fnt.displayName;function Bnt({agentUserId:s}){const t=new Date().getFullYear(),r=`${t}-01-01`,n=`${t}-12-31`,{data:a=[]}=gt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:j,error:b}=await H.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 j||[]}}),{data:i}=gt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:j}=await H.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return j}}),l=a.filter(j=>j.is_win),o=l.length,c=l.reduce((j,b)=>j+(Number(b.sale_price)||0),0),d=l.reduce((j,b)=>j+(Number(b.commission_amount)||0),0),h=i,m=(h==null?void 0:h.transactions_goal)||0,x=(h==null?void 0:h.volume_goal)||0,g=(h==null?void 0:h.gci_goal)||0,v=j=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(j);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(_o,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(W1e,{icon:Xl,label:"Transactions",value:o.toString(),goal:m,current:o,suffix:m?`/ ${m}`:""}),e.jsx(W1e,{icon:_o,label:"Volume",value:v(c),goal:x,current:c,suffix:x?`of ${v(x)}`:""}),e.jsx(W1e,{icon:_l,label:"GCI",value:v(d),goal:g,current:d,suffix:g?`of ${v(g)}`:""})]}),o===0&&e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function W1e({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(Ne,{children:e.jsxs(De,{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(ri,{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 znt({assignmentId:s,canEdit:t}){const r=es(),[n,a]=k.useState(!1),[i,l]=k.useState(null),{data:o=[]}=gt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:h}=await H.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(h)throw h;return d||[]}}),c=()=>r.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(zd,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(G,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const h=Number(d.target_value||0),m=Number(d.current_value||0),x=h>0?Math.min(100,m/h*100):0;return e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})})]}),h>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[m.toLocaleString()," / ",h.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[x.toFixed(0),"%"]})]}),e.jsx(ri,{value:x})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Ss(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(s9t,{open:n,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function s9t({open:s,onOpenChange:t,assignmentId:r,goal:n,onSaved:a}){var A,P;const[i,l]=k.useState((n==null?void 0:n.title)||""),[o,c]=k.useState((n==null?void 0:n.description)||""),[d,h]=k.useState((n==null?void 0:n.target_metric)||""),[m,x]=k.useState(((A=n==null?void 0:n.target_value)==null?void 0:A.toString())||""),[g,v]=k.useState(((P=n==null?void 0:n.current_value)==null?void 0:P.toString())||"0"),[j,b]=k.useState((n==null?void 0:n.due_date)||""),[N,S]=k.useState(!1);k.useState(()=>{var D,B;l((n==null?void 0:n.title)||""),c((n==null?void 0:n.description)||""),h((n==null?void 0:n.target_metric)||""),x(((D=n==null?void 0:n.target_value)==null?void 0:D.toString())||""),v(((B=n==null?void 0:n.current_value)==null?void 0:B.toString())||"0"),b((n==null?void 0:n.due_date)||"")});const T=async()=>{if(!i.trim())return;S(!0);const D={assignment_id:r,title:i,description:o||null,target_metric:d||null,target_value:m?Number(m):null,current_value:g?Number(g):0,due_date:j||null},{error:B}=n!=null&&n.id?await H.from("coaching_goals").update(D).eq("id",n.id):await H.from("coaching_goals").insert(D);if(S(!1),B)return ue.error(B.message);ue.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(js,{children:e.jsx(bs,{children:n!=null&&n.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ke,{placeholder:"Title",value:i,onChange:D=>l(D.target.value)}),e.jsx(ur,{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(ke,{placeholder:"transactions",value:d,onChange:D=>h(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(ke,{type:"number",value:m,onChange:D=>x(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(ke,{type:"number",value:g,onChange:D=>v(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(ke,{type:"date",value:j,onChange:D=>b(D.target.value)})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:N,children:n!=null&&n.id?"Save":"Create"})]})]})})}function $nt({assignmentId:s}){const t=es(),{user:r}=As(),n=k.useRef(null),[a,i]=k.useState(!1),{data:l=[]}=gt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:m,error:x}=await H.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(x)throw x;return m||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async m=>{var g;const x=(g=m.target.files)==null?void 0:g[0];if(!(!x||!r)){i(!0);try{const v=`${s}/${Date.now()}-${x.name}`,{error:j}=await H.storage.from("coaching-files").upload(v,x);if(j)throw j;const{error:b}=await H.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:r.id,file_url:v,file_name:x.name,file_size_bytes:x.size,mime_type:x.type});if(b)throw b;ue.success("File uploaded"),o()}catch(v){ue.error(v.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}}},d=async m=>{const{data:x,error:g}=await H.storage.from("coaching-files").createSignedUrl(m.file_url,60);if(g||!x)return ue.error("Could not get download link");window.open(x.signedUrl,"_blank")},h=async m=>{confirm("Delete this file?")&&(await H.storage.from("coaching-files").remove([m.file_url]),await H.from("coaching_shared_files").delete().eq("id",m.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(G,{size:"sm",onClick:()=>{var m;return(m=n.current)==null?void 0:m.click()},disabled:a,children:[e.jsx(oa,{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(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(ln,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.file_size_bytes?`${(m.file_size_bytes/1024).toFixed(0)} KB · `:"",Ss(new Date(m.created_at),"PP")]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>d(m),children:e.jsx(Xa,{className:"h-4 w-4"})}),m.uploaded_by===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h(m),children:e.jsx(yr,{className:"h-4 w-4"})})]})},m.id))})]})}function r9t(){var x,g,v,j;const{id:s}=Xi(),t=vr(),r=es(),{data:n,isLoading:a}=q7t(s),{data:i=[]}=ynt(s),{data:l=[]}=vnt(s),[o,c]=k.useState(!1),[d,h]=k.useState(!1);if(a)return e.jsx(_s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!n)return e.jsx(_s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const m=n;return e.jsxs(_s,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(De,{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(vn,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(ga,{src:((x=m.agent)==null?void 0:x.avatar_url)||void 0}),e.jsx(bn,{className:"text-2xl",children:(((g=m.agent)==null?void 0:g.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((v=m.agent)==null?void 0:v.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(j=m.agent)==null?void 0:j.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Ge,{variant:"secondary",className:"capitalize",children:(m.pipeline_stage||"active").replace("_"," ")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:m.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(n9t,{value:m.pipeline_stage||"active",onChange:async b=>{await H.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(Rn,{defaultValue:"sessions",children:[e.jsxs(Dn,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Xt,{value:"sessions",children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Xt,{value:"actions",children:[e.jsx(t_,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Xt,{value:"goals",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Xt,{value:"kpis",children:[e.jsx(_o,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Xt,{value:"messages",children:[e.jsx(bi,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Xt,{value:"files",children:[e.jsx(im,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Xt,{value:"notes",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(as,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs(G,{size:"sm",onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:Ss(new Date(b.scheduled_at),"PPp")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:b.status}),b.template&&e.jsx(Ge,{variant:"secondary",children:b.template})]}),b.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:b.summary}),b.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Kc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:b.private_notes})]})]})})})},b.id))})]}),e.jsxs(as,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs(G,{size:"sm",onClick:()=>h(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Ei,{checked:b.status==="done",onCheckedChange:async N=>{await H.from("coaching_action_items").update({status:N?"done":"open",completed_at:N?new Date().toISOString():null}).eq("id",b.id),r.invalidateQueries({queryKey:["coaching-action-items",m.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Ge,{variant:"outline",children:Ss(new Date(b.due_date),"MMM d")}),e.jsx(Ge,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))})]}),e.jsx(as,{value:"goals",children:e.jsx(znt,{assignmentId:m.id,canEdit:!0})}),e.jsx(as,{value:"kpis",children:m.agent_id&&e.jsx(Bnt,{agentUserId:m.agent_id})}),e.jsx(as,{value:"messages",children:e.jsx(Pnt,{assignmentId:m.id})}),e.jsx(as,{value:"files",children:e.jsx($nt,{assignmentId:m.id})}),e.jsx(as,{value:"notes",className:"space-y-4",children:e.jsx(Ne,{children:e.jsx(De,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(a9t,{open:o,onOpenChange:c,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-sessions",m.id]})}),e.jsx(i9t,{open:d,onOpenChange:h,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-action-items",m.id]})})]})}function n9t({value:s,onChange:t}){return e.jsxs(zs,{value:s,onValueChange:t,children:[e.jsx(Os,{className:"w-40",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"onboarding",children:"Onboarding"}),e.jsx(mt,{value:"active",children:"Active"}),e.jsx(mt,{value:"thriving",children:"Thriving"}),e.jsx(mt,{value:"at_risk",children:"At Risk"}),e.jsx(mt,{value:"graduated",children:"Graduated"})]})]})}function a9t({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=k.useState(60),[c,d]=k.useState("weekly_1on1"),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(!1),[b,N]=k.useState(!0),[S,T]=k.useState(null),[A,P]=k.useState(!1),D=async()=>{P(!0);const{data:z,error:F}=await H.functions.invoke("coaching-prep-brief",{body:{assignmentId:r}});if(P(!1),F||z!=null&&z.error)return ue.error((z==null?void 0:z.error)||(F==null?void 0:F.message)||"Failed to generate brief");T(z.brief||"No brief returned.")},B=async()=>{j(!0);const{data:z,error:F}=await H.from("coaching_sessions").insert({assignment_id:r,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:h,private_notes:x,status:"completed"}).select("id").maybeSingle();if(F)return j(!1),ue.error(F.message);if(ue.success("Session saved"),b&&h.trim()&&(z!=null&&z.id)){const{error:$}=await H.functions.invoke("coaching-send-recap",{body:{sessionId:z.id}});$?ue.error("Saved, but recap email failed: "+$.message):ue.success("Recap emailed to agent")}j(!1),n==null||n(),t(!1),m(""),g(""),T(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(js,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(bs,{children:"New Session"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:D,disabled:A,children:[A?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[S&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(jr,{className:"h-3 w-3"})," AI Brief"]}),S]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(ke,{type:"datetime-local",value:a,onChange:z=>i(z.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(ke,{type:"number",value:l,onChange:z=>o(Number(z.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(zs,{value:c,onValueChange:d,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(mt,{value:"grow",children:"GROW Model"}),e.jsx(mt,{value:"goal_review",children:"Goal Review"}),e.jsx(mt,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(ur,{rows:4,value:h,onChange:z=>m(z.target.value),placeholder:"Key takeaways, wins, focus areas…"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(ur,{rows:3,value:x,onChange:z=>g(z.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(Ei,{checked:b,onCheckedChange:z=>N(!!z)}),e.jsx(Zr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:B,disabled:v,children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function i9t({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState("medium"),[x,g]=k.useState(!1),v=async()=>{if(!a.trim())return;g(!0);const{error:j}=await H.from("coaching_action_items").insert({assignment_id:r,title:a,description:l||null,due_date:c||null,priority:h});if(g(!1),j)return ue.error(j.message);ue.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(js,{children:e.jsx(bs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ke,{placeholder:"Title",value:a,onChange:j=>i(j.target.value)}),e.jsx(ur,{rows:3,placeholder:"Description (optional)",value:l,onChange:j=>o(j.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(ke,{type:"date",value:c,onChange:j=>d(j.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(zs,{value:h,onValueChange:m,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"low",children:"Low"}),e.jsx(mt,{value:"medium",children:"Medium"}),e.jsx(mt,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:v,disabled:x,children:"Add"})]})]})})}function X2e({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(Qn,{style:{width:t,height:t},className:n<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},n))})}function o9t({coachId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l}=await H.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 H.from("profiles").select("id, name, avatar_url").in("id",c),h=new Map((d||[]).map(m=>[m.id,m]));o.forEach(m=>m.profile=h.get(m.agent_id))}r(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return n||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(X2e,{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(Ne,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(vn,{className:"h-9 w-9",children:[e.jsx(ga,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(bn,{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(X2e,{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 l9t({coachId:s,assignmentId:t}){const{user:r}=As(),[n,a]=k.useState(null),[i,l]=k.useState(0),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(!1);k.useEffect(()=>{r&&(async()=>{const{data:v}=await H.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",r.id).maybeSingle();v&&(a(v),l(v.rating),c(v.title||""),h(v.body||""))})()},[r,s]);const g=async()=>{if(!r)return;if(!i)return ue.error("Pick a rating");x(!0);const v={coach_id:s,agent_id:r.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:j}=n?await H.from("coaching_reviews").update(v).eq("id",n.id):await H.from("coaching_reviews").insert(v);if(x(!1),j)return ue.error(j.message);ue.success("Thanks for your review!"),a({...v,id:n==null?void 0:n.id})};return e.jsx(Ne,{children:e.jsxs(De,{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(X2e,{value:i,size:28,onChange:l}),e.jsx(ke,{placeholder:"Title (optional)",value:o,onChange:v=>c(v.target.value)}),e.jsx(ur,{rows:4,placeholder:"What was your experience like?",value:d,onChange:v=>h(v.target.value)}),e.jsx(G,{onClick:g,disabled:m,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:m?"Saving…":n?"Update review":"Submit review"})]})})}function c9t(){var m,x,g,v,j,b;const{user:s}=As(),{data:t,isLoading:r,refetch:n}=U7t(),a=es(),i=t==null?void 0:t.id,{data:l=[]}=ynt(i),{data:o=[]}=vnt(i);if(k.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&H.functions.invoke("coaching-verify-checkout").then(()=>{n(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[n,a]),r)return e.jsx(_s,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(_s,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Od,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(N=>N.status!=="done"),h=o.length-d.length;return e.jsx(_s,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(Ne,{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(vn,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(ga,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(bn,{className:"text-2xl bg-white/20 text-white",children:(((x=c.coachProfile)==null?void 0:x.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(jr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((g=c.coachProfile)==null?void 0:g.name)||"Your Coach"}),((v=c.coach)==null?void 0:v.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((j=c.coach)==null?void 0:j.is_certified)&&e.jsx(Ge,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Ge,{variant:"secondary",className:"bg-white/15 text-white border-white/20",children:"Active Program"})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(K1e,{icon:t_,label:"Open action items",value:d.length}),e.jsx(K1e,{icon:zd,label:"Completed",value:h}),e.jsx(K1e,{icon:rn,label:"Sessions",value:l.length})]}),((b=c.coach)==null?void 0:b.id)&&e.jsx(l9t,{coachId:c.coach.id,assignmentId:i}),e.jsxs(Rn,{defaultValue:"actions",children:[e.jsxs(Dn,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Xt,{value:"actions",children:[e.jsx(t_,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Xt,{value:"sessions",children:[e.jsx(rn,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Xt,{value:"goals",children:[e.jsx(zd,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Xt,{value:"kpis",children:[e.jsx(_o,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Xt,{value:"messages",children:[e.jsx(bi,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Xt,{value:"files",children:[e.jsx(im,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(as,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(N=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Ei,{checked:N.status==="done",onCheckedChange:async S=>{await H.from("coaching_action_items").update({status:S?"done":"open",completed_at:S?new Date().toISOString():null}).eq("id",N.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:N.status==="done"?"line-through text-muted-foreground":"font-medium",children:N.title}),N.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:N.description})]}),N.due_date&&e.jsx(Ge,{variant:"outline",children:Ss(new Date(N.due_date),"MMM d")}),e.jsx(Ge,{variant:"secondary",className:"capitalize",children:N.priority})]})},N.id))}),e.jsx(as,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(N=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Ss(new Date(N.scheduled_at),"PPp")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:N.status})]}),N.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},N.id))}),e.jsx(as,{value:"goals",children:e.jsx(znt,{assignmentId:i,canEdit:!1})}),e.jsx(as,{value:"kpis",children:s&&e.jsx(Bnt,{agentUserId:s.id})}),e.jsx(as,{value:"messages",children:e.jsx(Pnt,{assignmentId:i})}),e.jsx(as,{value:"files",children:e.jsx($nt,{assignmentId:i})})]})]})})}function K1e({icon:s,label:t,value:r}){return e.jsx(Ne,{children:e.jsxs(De,{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 d9t(){const s=es(),[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(null),{data:o=[],isLoading:c}=gt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:m,error:x}=await H.from("coaches").select("*").order("created_at",{ascending:!1});if(x)throw x;if(!(m!=null&&m.length))return[];const g=m.map(b=>b.user_id),{data:v}=await H.from("profiles").select("id, name, email, avatar_url").in("id",g),j=new Map((v||[]).map(b=>[b.id,b]));return m.map(b=>({...b,profile:j.get(b.user_id)}))}});k.useEffect(()=>{const m=t.trim();if(m.length<2){a([]);return}const x=setTimeout(async()=>{const{data:g}=await H.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${m}%,name.ilike.%${m}%`).limit(10);a(g||[])},250);return()=>clearTimeout(x)},[t]);const d=async m=>{const{error:x}=await H.functions.invoke("manage-user-roles",{body:{userId:m.id,role:"coach",action:"add"}});if(x)return ue.error(x.message);const{error:g}=await H.from("coaches").insert({user_id:m.id});if(g&&!String(g.message).includes("duplicate"))return ue.error(g.message);ue.success(`${m.name||m.email} is now a coach`),r(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},h=async(m,x)=>{const{error:g}=await H.from("coaches").update({is_certified:x}).eq("id",m);if(g)return ue.error(g.message);ue.success(x?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(_s,{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(Od,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(u9t,{}),e.jsx(m9t,{}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx(ke,{placeholder:"Search by user email or name…",value:t,onChange:m=>r(m.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:n.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):n.map(m=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.name||m.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.email})]}),e.jsxs(G,{size:"sm",onClick:()=>d(m),children:[e.jsx(Ws,{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(Ne,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(m=>{var x,g,v;return e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((x=m.profile)==null?void 0:x.name)||((g=m.profile)==null?void 0:g.email)||m.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(v=m.profile)==null?void 0:v.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[m.is_certified&&e.jsxs(Ge,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Certified"]}),m.accepting_clients&&e.jsx(Ge,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(nl,{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(br,{checked:m.is_certified,onCheckedChange:j=>h(m.id,j)})]})]})},m.id)})})]})]}),e.jsx(h9t,{coachId:i,onClose:()=>l(null)})]})}function u9t(){const[s,t]=k.useState("1500"),[r,n]=k.useState(!1),[a,i]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:c}=await H.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ue.error("Enter a value between 0 and 5000 bps (0–50%)");n(!0);const{error:d}=await H.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(n(!1),d)return ue.error(d.message);ue.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F3,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Platform Fee"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The percentage LevelUp takes from every coaching subscription. Stored as basis points (100 bps = 1%)."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{children:"Fee (bps)"}),e.jsx(ke,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(G,{onClick:l,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:r?"Saving…":"Save"})]})]})})}function h9t({coachId:s,onClose:t}){const[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=es();k.useEffect(()=>{if(!s){n(""),i([]);return}},[s]),k.useEffect(()=>{const h=r.trim();if(h.length<2){i([]);return}o(!0);const m=setTimeout(async()=>{const{data:x}=await H.from("profiles").select("id, name, email").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(15);i(x||[]),o(!1)},250);return()=>clearTimeout(m)},[r]);const d=async h=>{const{error:m}=await H.from("coaching_assignments").insert({coach_id:s,agent_id:h,status:"active",source:"admin",pipeline_stage:"onboarding"});if(m)return ue.error(m.message);ue.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(vs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Assign Agent"})}),e.jsx(ke,{placeholder:"Search agents by name or email…",value:r,onChange:h=>n(h.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:r.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(h=>e.jsxs("button",{onClick:()=>d(h.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]},h.id))}),e.jsx(on,{children:e.jsx(G,{variant:"outline",onClick:t,children:"Close"})})]})})}function m9t(){const s=es(),[t,r]=k.useState("pending"),[n,a]=k.useState(null),{data:i=[],isLoading:l}=gt({queryKey:["coach-applications",t],queryFn:async()=>{let h=H.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(h=h.eq("status",t));const{data:m,error:x}=await h;if(x)throw x;return m||[]}}),{data:o=0}=gt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:h}=await H.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return h||0}}),c=async(h,m)=>{const{error:x}=await H.from("coach_applications").update({status:m,reviewed_at:new Date().toISOString()}).eq("id",h);if(x)return ue.error(x.message);ue.success(`Marked ${m}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=h=>h==="approved"?e.jsxs(Ge,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Hn,{className:"h-3 w-3 mr-1"}),"Approved"]}):h==="rejected"?e.jsxs(Ge,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(_r,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Ge,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(Ne,{children:[e.jsxs(De,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(iM,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Ge,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(h=>e.jsx(G,{size:"sm",variant:t===h?"default":"outline",onClick:()=>r(h),className:t===h?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:h.charAt(0).toUpperCase()+h.slice(1)},h))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(h=>e.jsx("button",{onClick:()=>a(h),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:h.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Qs,{className:"h-3 w-3"}),h.email]}),h.brokerage&&e.jsxs("span",{children:["· ",h.brokerage]}),h.years_experience&&e.jsxs("span",{children:["· ",h.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(h.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(h.created_at).toLocaleDateString()})]})]})},h.id))})]}),e.jsx(vs,{open:!!n,onOpenChange:h=>!h&&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(js,{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(FE,{icon:Qs,label:"Email",value:n.email,link:`mailto:${n.email}`}),n.phone&&e.jsx(FE,{icon:Nn,label:"Phone",value:n.phone,link:`tel:${n.phone}`}),n.brokerage&&e.jsx(FE,{label:"Brokerage",value:n.brokerage}),n.years_experience&&e.jsx(FE,{label:"Years",value:n.years_experience}),n.website_url&&e.jsx(FE,{icon:Yr,label:"Website",value:n.website_url,link:n.website_url}),n.linkedin_url&&e.jsx(FE,{icon:Yr,label:"LinkedIn",value:n.linkedin_url,link:n.linkedin_url})]}),n.specialties&&e.jsx(Y1e,{label:"Specialties",children:n.specialties}),e.jsx(Y1e,{label:"Why they want to coach",children:n.why_coach}),n.results_story&&e.jsx(Y1e,{label:"Results story",children:n.results_story}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(ur,{defaultValue:n.admin_notes||"",rows:3,onBlur:async h=>{const m=h.target.value;m!==(n.admin_notes||"")&&(await H.from("coach_applications").update({admin_notes:m}).eq("id",n.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(on,{className:"gap-2 flex-wrap",children:[n.status!=="rejected"&&e.jsxs(G,{variant:"outline",onClick:()=>c(n.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(_r,{className:"h-4 w-4 mr-1"})," Reject"]}),n.status!=="pending"&&e.jsxs(G,{variant:"outline",onClick:()=>c(n.id,"pending"),children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Move to pending"]}),n.status!=="approved"&&e.jsxs(G,{onClick:()=>c(n.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Hn,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function FE({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 Y1e({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 f9t(){const s=vr(),{data:t}=Qpe(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),{data:d,refetch:h}=gt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await H.functions.invoke("coach-stripe-status");return b}}),{data:m=[]}=gt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await H.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return b||[]}});k.useEffect(()=>{const b=new URLSearchParams(window.location.search);(b.get("onboarded")||b.get("refresh"))&&h()},[h]);const x=async()=>{var T,A;a(!0);const{data:b,error:N}=await H.functions.invoke("coach-stripe-connect");a(!1);let S=b==null?void 0:b.error;if(!S&&N)try{const P=await((A=(T=N==null?void 0:N.context)==null?void 0:T.json)==null?void 0:A.call(T));S=(P==null?void 0:P.error)||N.message}catch{S=N.message}if(S)return ue.error(S,{duration:1e4});b!=null&&b.url&&(window.location.href=b.url)},g=d||{},v=!!(t!=null&&t.use_platform_stripe),j=v||g.connected&&g.charges_enabled;return e.jsx(_s,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(Ne,{children:e.jsxs(De,{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(gx,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),j?e.jsxs(Ge,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"})," ",v?"Using LevelUp billing":"Connected"]}):g.connected?e.jsxs(Ge,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Hi,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Ge,{variant:"outline",children:"Not connected"})]}),!v&&e.jsxs(G,{onClick:x,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[j?"Update Stripe details":g.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Yr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs(G,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!j,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!j&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:m.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[b.name,b.is_active&&b.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(b.price_cents/100).toFixed(0)," / ",b.billing_interval,!b.is_active&&" · Inactive"]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{c(b),l(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await H.from("coaching_packages").delete().eq("id",b.id),r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id))})]})}),e.jsx(p9t,{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 p9t({open:s,onOpenChange:t,coachId:r,pkg:n,onSaved:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState("month"),[g,v]=k.useState(!0),[j,b]=k.useState(!0),[N,S]=k.useState(!1);k.useEffect(()=>{s&&(l((n==null?void 0:n.name)||""),c((n==null?void 0:n.description)||""),h(n?(n.price_cents/100).toString():""),x((n==null?void 0:n.billing_interval)||"month"),v((n==null?void 0:n.is_active)??!0),b((n==null?void 0:n.accepting_clients)??!0))},[s,n]);const T=async()=>{if(!i.trim()||!d)return ue.error("Name and price required");S(!0);const A={coach_id:r,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:m,is_active:g,accepting_clients:j},{error:P}=n!=null&&n.id?await H.from("coaching_packages").update(A).eq("id",n.id):await H.from("coaching_packages").insert(A);if(S(!1),P)return ue.error(P.message);ue.success("Saved"),a==null||a(),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:n!=null&&n.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ke,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(ur,{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(ke,{type:"number",value:d,onChange:A=>h(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"month",children:"Monthly"}),e.jsx(mt,{value:"year",children:"Yearly"}),e.jsx(mt,{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:g,onChange:A=>v(A.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:j,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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:N,children:n!=null&&n.id?"Save":"Create"})]})]})})}function RFe({kind:s,value:t,onChange:r}){const n=k.useRef(null),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),h=k.useRef(null),m=k.useRef(null),x=k.useRef(null),g=k.useRef([]),[v,j]=k.useState(!1),b=s==="photo"?"image/*":"video/*",N=s==="photo"?10*1024*1024:200*1024*1024,S=async(z,F)=>{var ne;const{data:$}=await H.auth.getUser(),X=(ne=$.user)==null?void 0:ne.id;if(!X)return ue.error("Not signed in");if(z.size>N)return ue.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const K=`${X}/${s}-${Date.now()}.${F}`,{error:Q}=await H.storage.from("coach-media").upload(K,z,{upsert:!0,contentType:z.type||(s==="photo"?"image/jpeg":"video/webm")});if(Q)return i(!1),ue.error(Q.message);const{data:Y}=await H.storage.from("coach-media").createSignedUrl(K,60*60*24*365*10);i(!1),Y!=null&&Y.signedUrl&&(r(Y.signedUrl),ue.success("Uploaded"),d(null))},T=async z=>{const F=z.name.split(".").pop()||(s==="photo"?"jpg":"webm");await S(z,F)},A=async()=>{try{const z=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});m.current=z,j(!0),setTimeout(()=>{h.current&&(h.current.srcObject=z,h.current.play())},50);const F=new MediaRecorder(z,{mimeType:"video/webm"});g.current=[],F.ondataavailable=$=>$.data.size>0&&g.current.push($.data),F.onstop=()=>{const $=new Blob(g.current,{type:"video/webm"});d($),z.getTracks().forEach(X=>X.stop())},x.current=F,F.start(),o(!0)}catch(z){ue.error(z.message||"Could not access camera")}},P=()=>{var z;(z=x.current)==null||z.stop(),o(!1)},D=()=>{var z;(z=m.current)==null||z.getTracks().forEach(F=>F.stop()),j(!1),o(!1),d(null)},B=async()=>{c&&(await S(c,"webm"),D())};return k.useEffect(()=>()=>{var z;return(z=m.current)==null?void 0:z.getTracks().forEach(F=>F.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:n,type:"file",accept:b,className:"hidden",onChange:z=>{var $;const F=($=z.target.files)==null?void 0:$[0];F&&T(F),z.target.value=""}}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var z;return(z=n.current)==null?void 0:z.click()},children:[a?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||v,children:[e.jsx(pp,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(""),children:[e.jsx(yr,{className:"h-4 w-4 mr-1"})," Remove"]})]}),v&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:h,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(G,{type:"button",size:"sm",onClick:P,className:"bg-red-600 hover:bg-red-700",children:[e.jsx($g,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(G,{type:"button",size:"sm",onClick:()=>{var z;return(z=x.current)==null?void 0:z.start()},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{type:"button",size:"sm",onClick:B,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:D,children:"Cancel"})]})]})]})}function x9t(){const s=vr(),{data:t,isLoading:r}=Qpe(),n=es(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(!1),[b,N]=k.useState([]),[S,T]=k.useState(""),[A,P]=k.useState(!1);k.useEffect(()=>{if(!t)return;const $=t;i($.slug||""),o($.headline||""),d($.bio||""),m($.photo_url||""),g($.intro_video_url||""),j(!!$.accepting_clients),N($.specialties||[])},[t]);const D=async()=>{if(!t)return;P(!0);const{error:$}=await H.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:h||null,intro_video_url:x||null,accepting_clients:v,specialties:b}).eq("id",t.id);if(P(!1),$)return ue.error($.message);ue.success("Profile saved"),n.invalidateQueries({queryKey:["my-coach-profile"]})},B=()=>{const $=S.trim();if($){if(b.includes($))return T("");N([...b,$]),T("")}};if(r)return e.jsx(_s,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(_s,{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 z=t,F=z.slug?`${window.location.origin}/coaches/${z.slug}`:null;return e.jsx(_s,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[F&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(G,{onClick:D,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),z.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(Ne,{children:e.jsxs(De,{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(br,{checked:v,onCheckedChange:j})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(ke,{value:a,onChange:$=>i($.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(ke,{value:l,onChange:$=>o($.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Bio"}),e.jsx(ur,{rows:6,value:c,onChange:$=>d($.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Profile photo"}),e.jsx(RFe,{kind:"photo",value:h,onChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Intro video"}),e.jsx(RFe,{kind:"video",value:x,onChange:g})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:b.map($=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[$,e.jsx("button",{onClick:()=>N(b.filter(X=>X!==$)),children:e.jsx(_r,{className:"h-3 w-3"})})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:S,onChange:$=>T($.target.value),placeholder:"Add a specialty…",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),B())}}),e.jsx(G,{type:"button",variant:"outline",onClick:B,children:e.jsx(Ws,{className:"h-4 w-4"})})]})]})]})}),e.jsx(Ne,{children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx(G,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(g9t,{coachId:z.id})]})})}function g9t({coachId:s}){const[t,r]=k.useState("");es();const{data:n=[],refetch:a}=gt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await H.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ue.error("Email required");const{error:d}=await H.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ue.error(d.message);r(""),ue.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ue.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await H.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(Ne,{children:e.jsxs(De,{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(xo,{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(ke,{placeholder:"agent@email.com",value:t,onChange:c=>r(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(G,{onClick:i,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(yr,{className:"h-4 w-4"})})]},c.id)),n.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}function y9t(){const{data:s=[],isLoading:t}=gt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:r,error:n}=await H.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 H.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(r||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(jr,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{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(Kn,{to:`/coaches/${r.slug||r.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:n,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:n.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[r.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(jr,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${r.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.accepting_clients?"bg-white":"bg-amber-500"}`}),r.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:n}),r.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:r.headline}),r.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:r.bio}),r.specialties&&r.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:r.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(Ga,{className:"h-4 w-4"})})]})]})]})})},r.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(jr,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Mn,{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(Mn,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Mn,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Kn,{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(Ga,{className:"h-5 w-5"})]}),e.jsx("p",{className:"text-xs text-white/60 mt-3 text-center md:text-left",children:"By application only."})]})]})]})]})]})}function v9t(){var g;const{slug:s}=Xi(),t=vr(),{user:r}=As(),[n,a]=k.useState(null),{data:i,isLoading:l}=gt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),j=H.from("coaches").select("*"),{data:b}=v?await j.eq("id",s).maybeSingle():await j.eq("slug",s).maybeSingle();if(!b)return null;const[{data:N},{data:S}]=await Promise.all([H.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),H.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:N,packages:S||[]}}}),o=async v=>{if(!r){ue.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:j,error:b}=await H.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||j!=null&&j.error){ue.error((j==null?void 0:j.error)||(b==null?void 0:b.message)||"Checkout failed");return}j!=null&&j.url&&(window.location.href=j.url)};if(l)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(i!=null&&i.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:c,profile:d,packages:h}=i,m=c,x=(v,j)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return j==="one_time"?b:`${b} / ${j}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(wa,{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(vn,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(ga,{src:m.photo_url||(d==null?void 0:d.avatar_url)}),e.jsx(bn,{className:"text-3xl bg-white/20",children:((d==null?void 0:d.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[m.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(jr,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(d==null?void 0:d.name)||"Coach"}),m.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:m.headline}),((g=m.specialties)==null?void 0:g.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:m.specialties.map(v=>e.jsx(Ge,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[m.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:m.intro_video_url,controls:!0,className:"w-full h-full"})}),m.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:m.bio})]}),e.jsx(o9t,{coachId:m.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),h.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):h.map(v=>{const j=v.accepting_clients===!1;return e.jsx(Ne,{className:`border-2 transition-colors ${j?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(De,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:v.name}),j&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:x(v.price_cents,v.billing_interval)}),j?e.jsx("div",{className:"mt-4 rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients. Check back soon."}):e.jsxs(G,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>o(v.id),disabled:n===v.id,children:[n===v.id?"Loading…":"Get Started",e.jsx(Hn,{className:"h-4 w-4 ml-1"})]})]})},v.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."})]})]})]})}const b9t=M_({full_name:oo().trim().min(2,"Please enter your full name").max(100),email:oo().trim().email("Enter a valid email").max(255),phone:oo().trim().max(40).optional().or(Ng("")),brokerage:oo().trim().max(150).optional().or(Ng("")),years_experience:oo().trim().max(40).optional().or(Ng("")),specialties:oo().trim().max(500).optional().or(Ng("")),why_coach:oo().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:oo().trim().max(2e3).optional().or(Ng("")),website_url:oo().trim().max(300).optional().or(Ng("")),linkedin_url:oo().trim().max(300).optional().or(Ng(""))});function _9t(){const s=vr(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,h)=>l(m=>({...m,[d]:h})),c=async d=>{var x;d.preventDefault();const h=b9t.safeParse(i);if(!h.success){const g=(x=Object.values(h.error.flatten().fieldErrors)[0])==null?void 0:x[0];return ue.error(g||"Please check the form and try again")}r(!0);const{error:m}=await H.from("coach_applications").insert(h.data);if(r(!1),m)return ue.error(m.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return n?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(Mn,{className:"h-10 w-10"})}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:"Application received."}),e.jsx("p",{className:"text-white/80 text-lg leading-relaxed mb-8",children:"Thank you for applying to the LevelUp Coaching program. Our team personally reviews every application — we'll be in touch within 5 business days."}),e.jsx(G,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(Kn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(wa,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(jr,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(fr,{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(_o,{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(Xl,{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(Mn,{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(Zi,{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(Qn,{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(tv,{label:"Full name *",children:e.jsx(ke,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(tv,{label:"Email *",children:e.jsx(ke,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(tv,{label:"Phone",children:e.jsx(ke,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(tv,{label:"Current brokerage",children:e.jsx(ke,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(tv,{label:"Years in real estate",children:e.jsx(ke,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(tv,{label:"Coaching specialties",children:e.jsx(ke,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(tv,{label:"Website",children:e.jsx(ke,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(tv,{label:"LinkedIn",children:e.jsx(ke,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(tv,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(ur,{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(tv,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(ur,{value:i.results_story,onChange:d=>o("results_story",d.target.value),rows:5,maxLength:2e3,placeholder:"Production numbers, agent breakthroughs, testimonials — anything that shows the impact you've had."})}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2",children:[e.jsx(G,{type:"submit",disabled:t,className:"bg-gradient-to-r from-[#406E71] to-[#2a4c64] hover:opacity-95 text-white font-semibold px-8 py-6 text-base flex-1 sm:flex-none",children:t?"Submitting…":"Submit application"}),e.jsx("p",{className:"text-xs text-slate-500",children:"We review every application within 5 business days."})]})]})]})]})}function tv({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const w9t="/assets/testimonial-avatar-1-BsCQFauB.jpg",j9t="/assets/testimonial-avatar-2-B6VPVc2t.jpg",N9t="/assets/testimonial-avatar-3-GuEFwYUE.jpg",k9t="/assets/testimonial-avatar-4-98iKMtkB.jpg",S9t="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",C9t=[w9t,j9t,N9t,k9t,S9t],T9t=M_({name:oo().trim().min(2,"Name must be at least 2 characters").max(100),email:oo().trim().email("Please enter a valid email address").max(255),phone:oo().trim().min(10,"Please enter a valid phone number").max(20).optional().or(Ng("")),brokerage:oo().trim().max(200).optional().or(Ng(""))}),E9t=[{icon:mf,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:rn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:tc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ln,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:li,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],A9t=[{icon:fr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:jr,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Nn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Eh,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ja,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ao,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:hi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Xu,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],M9t=[{name:"Sarah M.",role:"Top Producer, RE/MAX",quote:"LevelUp completely transformed how I run my business. The templates alone save me hours every week."},{name:"Mike T.",role:"Brokerage Owner",quote:"Onboarding new agents used to take weeks. Now they're productive from day one with all the training resources."},{name:"Jessica L.",role:"Team Lead",quote:"The community is incredible. I've learned more from other agents here than any conference I've attended."}],I9t=()=>{const s=vr(),[t,r]=k.useState(!1),[n,a]=k.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=k.useState({}),o=async c=>{var h,m;c.preventDefault(),l({});const d=T9t.safeParse(n);if(!d.success){const x={};d.error.errors.forEach(g=>{g.path[0]&&(x[g.path[0]]=g.message)}),l(x);return}r(!0);try{const x=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:g,error:v}=await H.functions.invoke("create-trial-signup",{body:{name:n.name.trim(),email:n.email.trim().toLowerCase(),phone:((h=n.phone)==null?void 0:h.trim())||void 0,brokerage:((m=n.brokerage)==null?void 0:m.trim())||void 0,referral_code:x}});if(v){console.error("Trial signup error:",v),ue.error(v.message||"Something went wrong. Please try again.");return}if(g!=null&&g.error){ue.error(g.error);return}ue.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),s("/trial/success")}catch(x){console.error("Trial signup error:",x),ue.error("Something went wrong. Please try again.")}finally{r(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(il,{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:Xue,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(G,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var c;return(c=document.getElementById("features"))==null?void 0:c.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(G,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(jr,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Mn,{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(Mn,{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:C9t.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(Qn,{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(Ne,{className:"bg-white shadow-2xl border-0",children:e.jsxs(De,{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(Gv,{className:"h-8 w-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground font-sans",children:"Start Your Free Trial"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Get instant access • No credit card needed"})]}),e.jsxs("form",{onSubmit:o,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Full Name *"}),e.jsx(ke,{id:"name",type:"text",placeholder:"John Smith",value:n.name,onChange:c=>a({...n,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email Address *"}),e.jsx(ke,{id:"email",type:"email",placeholder:"john@example.com",value:n.email,onChange:c=>a({...n,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ke,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:n.phone,onChange:c=>a({...n,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(ke,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:n.brokerage,onChange:c=>a({...n,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(G,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Ga,{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:E9t.map((c,d)=>e.jsxs(Ne,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ot,{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(zt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(jr,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:A9t.map((c,d)=>e.jsxs(Ne,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ot,{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(zt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(De,{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:M9t.map((c,d)=>e.jsx(Ne,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(De,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(Qn,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Zu,{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(Xu,{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(fr,{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(Ne,{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(De,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs(G,{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(Ga,{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:s3e,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."})]})})})]})]})},P9t=()=>{const s=vr();return e.jsxs(e.Fragment,{children:[e.jsx(il,{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:Xue,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(G,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(Ne,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(De,{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(Mn,{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(iu,{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(Qs,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(G,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(Ga,{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:s3e,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},L9t=M_({viewerName:oo().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:oo().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:oo().max(20,"Phone must be less than 20 characters").optional(),message:oo().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function D9t({shareToken:s,agentName:t,hasContact:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),d=qpe({resolver:Vpe(L9t),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),h=async m=>{a(!0),c(null);try{const{data:x,error:g}=await H.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:m.viewerName,viewerEmail:m.viewerEmail,viewerPhone:m.viewerPhone||void 0,message:m.message}});if(g)throw new Error(g.message);if(!(x!=null&&x.success))throw new Error((x==null?void 0:x.error)||"Failed to send reply");l(!0)}catch(x){console.error("Failed to submit reply:",x),c(x.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(Ne,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(De,{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(Mn,{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(Ne,{children:[e.jsxs(Ot,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(tc,{className:"h-5 w-5 text-primary"}),e.jsx(zt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Nr,{children:r?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(De,{children:e.jsx(Hpe,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(h),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(rd,{control:d.control,name:"viewerName",render:({field:m})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Your Name *"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"John Smith",...m})}),e.jsx(yf,{})]})}),e.jsx(rd,{control:d.control,name:"viewerEmail",render:({field:m})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Email *"}),e.jsx(qc,{children:e.jsx(ke,{type:"email",placeholder:"john@example.com",...m})}),e.jsx(yf,{})]})})]}),!r&&e.jsx(rd,{control:d.control,name:"viewerPhone",render:({field:m})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Phone (optional)"}),e.jsx(qc,{children:e.jsx(ke,{type:"tel",placeholder:"(555) 123-4567",...m})}),e.jsx(yf,{})]})}),e.jsx(rd,{control:d.control,name:"message",render:({field:m})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Message *"}),e.jsx(qc,{children:e.jsx(ur,{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(yf,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(G,{type:"submit",className:"w-full gap-2",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const R9t=()=>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(Qn,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Qn,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Qn,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Qn,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Qn,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(e_,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),O9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(jr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(Qn,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(jr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(Qn,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Qn,{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(e_,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),F9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-pink-200/20 via-rose-100/10 to-purple-200/15"}),e.jsx("div",{className:"absolute top-[5%] left-[5%] opacity-20",children:e.jsx(Yy,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(Yy,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(Yy,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(Yy,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(hi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(hi,{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(hi,{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"})]}),B9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-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(Xl,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Qn,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Xl,{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(Qn,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Qn,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),z9t=()=>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(Yy,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(Yy,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(tM,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),$9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-orange-900/12 via-purple-900/8 to-slate-900/12"}),e.jsx(C3,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(C3,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(jr,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(jr,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),U9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-900/8 via-green-900/5 to-emerald-900/8"}),e.jsx(t2,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(t2,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(t2,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Ev,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Ev,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Ev,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Ev,{className:"absolute top-[8%] left-[70%] w-8 h-8 text-blue-200/20 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[12%] left-[10%] w-5 h-5 rounded-full bg-red-500/25"}),e.jsx("div",{className:"absolute top-[15%] right-[15%] w-4 h-4 rounded-full bg-amber-400/25"}),e.jsx("div",{className:"absolute top-[20%] left-[55%] w-4 h-4 rounded-full bg-green-500/20"}),e.jsx(Qn,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),q9t=()=>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(hi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(hi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),V9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-yellow-900/8 via-amber-900/4 to-purple-900/8"}),e.jsx(Qn,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Qn,{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(Qn,{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(Qn,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(jr,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(iu,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(iu,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),H9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-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(Qn,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(jr,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(jr,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),G9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-green-900/12 via-emerald-900/6 to-teal-900/10"}),e.jsx(qb,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(qb,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(qb,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(qb,{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"})]})]})]}),W9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-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(Qn,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Qn,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Xl,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Xl,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(e_,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),K9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/6 via-rose-900/6 to-purple-900/6"}),e.jsx(Eh,{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(iu,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(li,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),Y9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-rose-900/12 via-pink-900/8 to-red-900/12"}),e.jsx(hi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(hi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(hi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(hi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(hi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(hi,{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(hi,{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(hi,{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"})]}),Z9t=()=>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(n_,{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(n_,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(jr,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(n_,{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"})]}),X9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-teal-900/10 via-cyan-900/6 to-emerald-900/10"}),e.jsx(Cn,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Cn,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(gp,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(gp,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(hi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(hi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(jr,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(iu,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),Q9t=()=>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(iu,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(iu,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(gp,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Cn,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(jr,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(jr,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),J9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsx(gp,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(gp,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(gp,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Cn,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(iu,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(jr,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Qn,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),e$t=()=>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(Cn,{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(gp,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(hi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(jr,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(zv,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),OFe=()=>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"})]}),t$t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(hi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(hi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(hi,{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(hi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),s$t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(zv,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(jr,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Cn,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),r$t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(N3,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(uM,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(N3,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),VD=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(jr,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(iu,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(jr,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),FFe=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Cn,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(jr,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Cn,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),Q2e=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(jr,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(hi,{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(t$t,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(ZR,{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(VD,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(N3,{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(r$t,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(ao,{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(fr,{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(VD,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Xl,{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(OFe,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ja,{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(FFe,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(uM,{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(VD,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Eh,{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(K9t,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(hi,{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(Y9t,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(n_,{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(Z9t,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Qn,{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(V9t,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(tM,{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(z9t,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(Yy,{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(F9t,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Xl,{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(B9t,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(e_,{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(R9t,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(xc,{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(O9t,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Xl,{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(W9t,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(C3,{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($9t,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(hi,{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(q9t,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(t2,{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(U9t,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(jr,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(H9t,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(qb,{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(G9t,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Cn,{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(X9t,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(iu,{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(Q9t,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(rn,{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(FFe,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(_l,{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(VD,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(a_,{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(zv,{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(s$t,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(gp,{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(J9t,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Cn,{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(e$t,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Mh,{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(VD,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Xl,{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(OFe,{})}],n$t=[{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 a$t(s){return Q2e.filter(t=>t.category===s)}function kM(s){return Q2e.find(t=>t.id===s)||Q2e[0]}function BFe(){const{shareToken:s,recipientToken:t}=Xi(),[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!0),[h,m]=k.useState(null),[x,g]=k.useState(!0),v=k.useRef(null),j=k.useRef(0),b=k.useRef(0),N=(()=>{const K=new URLSearchParams(window.location.search);return t||K.get("rt")||null})(),S=k.useCallback((K,Q=!1)=>{if(!N||K<=0)return;const Y=Math.max(1,Math.round(K));if(Y<=b.current)return;const de=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(N)}&e=watch&ws=${Y}`;Q&&navigator.sendBeacon?navigator.sendBeacon(de):fetch(de,{method:"GET",keepalive:Q}).catch(()=>{}),b.current=Math.max(b.current,Y)},[N]);k.useEffect(()=>{var ae;if(!x||!(r!=null&&r.playback_url)||!N)return;let K=!1;const Q=()=>{j.current>0&&S(j.current,!0)},Y=()=>{document.visibilityState==="hidden"&&Q()},ne=()=>{Q()},de=()=>{var me;if(K||!v.current||!((me=window.playerjs)!=null&&me.Player))return;const ie=new window.playerjs.Player(v.current);ie.on("timeupdate",oe=>{const ge=Math.floor(Number((oe==null?void 0:oe.seconds)??0));!Number.isFinite(ge)||ge<=0||(j.current=Math.max(j.current,ge))}),ie.on("pause",()=>{j.current>0&&S(j.current)}),ie.on("ended",()=>{j.current>0&&S(j.current,!0)})},ce=document.querySelector('script[data-bunny-playerjs="true"]');if((ae=window.playerjs)!=null&&ae.Player)de();else if(ce)ce.addEventListener("load",de,{once:!0});else{const ie=document.createElement("script");ie.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ie.async=!0,ie.defer=!0,ie.dataset.bunnyPlayerjs="true",ie.onload=de,document.body.appendChild(ie)}return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",ne),()=>{K=!0,document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",ne),Q()}},[x,r==null?void 0:r.playback_url,N,S]),k.useEffect(()=>{j.current=0,b.current=0},[N,s]),k.useEffect(()=>{const K=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(de=>{document.querySelectorAll(de).forEach(ce=>{ce.style.display="none"})})};K();const Q=[setTimeout(K,500),setTimeout(K,1500),setTimeout(K,3e3)],Y=new MutationObserver(K);return Y.observe(document.body,{childList:!0,subtree:!0}),()=>{Q.forEach(clearTimeout),Y.disconnect()}},[]),k.useEffect(()=>{(async()=>{if(!s){m("Invalid share link"),d(!1);return}const{data:Q,error:Y}=await H.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(Y||!Q){m("Video not found or has been removed"),d(!1);return}n(Q);try{await H.rpc("log_video_view",{p_video_id:Q.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(ne){console.warn("Failed to log video view:",ne)}if(Q.owner_user_id){const{data:ne}=await H.from("profiles").select("id, name, email, phone").eq("id",Q.owner_user_id).single();if(ne){i(ne);try{const{data:de}=await H.storage.from("avatars").list(`${Q.owner_user_id}`);if(de&&de.length>0){const{data:ce}=H.storage.from("avatars").getPublicUrl(`${Q.owner_user_id}/${de[0].name}`);o(ce.publicUrl)}}catch{}}}d(!1)})()},[s]);const T=K=>{if(!K)return"0:00";const Q=Math.floor(K/60),Y=K%60;return`${Q}:${Y.toString().padStart(2,"0")}`},A=K=>K.includes("iframe.mediadelivery.net/play/")?K.replace("/play/","/embed/")+"?autoplay=true&responsive=true":K,P=K=>{if(!K)return"?";const Q=K.split(" ");return Q.length>=2?`${Q[0][0]}${Q[1][0]}`.toUpperCase():K.substring(0,2).toUpperCase()},D=kM((r==null?void 0:r.page_template)||"default"),B=(r==null?void 0:r.recipient_name)||null,z=D.headerText(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(h||!r)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(Ne,{className:"max-w-md w-full",children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(sn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:h||"This video is no longer available."})]})})});const X=D.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsx("title",{children:z}),e.jsx("meta",{name:"description",content:D.subText}),e.jsx("meta",{property:"og:title",content:z}),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:$}),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:z}),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:Bt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",D.gradientClasses),children:[X&&D.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[X&&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:Bt("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:z}),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(vn,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(ga,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(bn,{className:"bg-primary/10 text-primary font-semibold",children:P(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:X?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx(G,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`tel:${a.phone}`,"aria-label":"Call agent",children:e.jsx(Nn,{className:"h-4 w-4"})})}),a.email&&e.jsx(G,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(Qs,{className:"h-4 w-4"})})})]})]}),e.jsx(Ne,{className:"overflow-hidden shadow-lg",children:x&&r.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:v,src:A(r.playback_url),title:r.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>g(!0),children:[r.preview_url||r.thumbnail_url?e.jsx("img",{src:r.preview_url||r.thumbnail_url||"",alt:r.title?`${r.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:K=>{var Y;K.currentTarget.style.display="none";const Q=(Y=K.currentTarget.parentElement)==null?void 0:Y.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(sn,{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(Ho,{className:"h-10 w-10 text-primary ml-1"})})}),r.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:T(r.duration_seconds)})]})}),!X&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:x?"Enjoy the video!":"Click to play the video"})]}),!x&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(G,{size:"lg",onClick:()=>g(!0),className:"gap-2",children:[e.jsx(Ho,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(D9t,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!r.contact_id})]})]})]})}function i$t(){return k.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(VCt,{})}function o$t(){const{token:s}=Xi();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 l$t={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"},c$t={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},BE={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function d$t(){var Oe,Me,Pe,Ee;const{slugOrId:s}=Xi(),[t]=Lc(),{data:r,isLoading:n}=vet(s||""),a=bet(),i=mMt(),l=t.get("ref"),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState("in_person"),[B,z]=k.useState("info"),[F,$]=k.useState(!1),[X,K]=k.useState(!1),[Q,Y]=k.useState(null),[ne,de]=k.useState(!1);k.useEffect(()=>{l&&i.mutate(l)},[l]);const ce=$e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format($e),ae=async $e=>{if($e.preventDefault(),!o.trim()||!m.trim()||!r)return;const Se=B==="showing";if(Se&&!N){ue.error("Please pick a preferred date for your showing");return}$(!0);try{await a.mutateAsync({listingId:r.id,agentId:r.agent_id,firstName:o.trim(),lastName:d.trim(),email:m.trim(),phone:g.trim(),shareToken:l,leadType:Se?"showing_request":"info_request",preferredDate:Se?N:null,preferredTime:Se&&T||null,showingMode:Se?P:null,message:j.trim()||null}),K(!0),ue.success(Se?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(ze){console.error("Lead submission error:",ze),ue.error(`Failed to submit: ${ze.message||"Please try again"}`)}finally{$(!1)}},ie=(r==null?void 0:r.photos)||[],me=ie.find($e=>$e.is_primary)||ie[0],oe=()=>{Q!==null&&Y(Q===0?ie.length-1:Q-1)},ge=()=>{Q!==null&&Y(Q===ie.length-1?0:Q+1)};if(n)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Vs,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Vs,{className:"h-10 w-48 mb-6"}),e.jsx(Vs,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Vs,{className:"h-12 w-48"}),e.jsx(Vs,{className:"h-6 w-full"}),e.jsx(Vs,{className:"h-6 w-3/4"})]}),e.jsx(Vs,{className:"h-64"})]})]})]});if(!r)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Kn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Mue,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(Cn,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing may no longer be available."}),e.jsx(G,{asChild:!0,children:e.jsx(Kn,{to:"/public/listings",children:"Browse All Listings"})})]})]});const be=r.property_address?`${r.property_address} - ${r.city}, ${r.state}`:`${r.city}, ${r.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(il,{children:[e.jsxs("title",{children:[be," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${r.square_footage?r.square_footage.toLocaleString()+" sqft":""} ${BE[r.property_type]} in ${r.city}, ${r.state}. ${((Oe=r.description)==null?void 0:Oe.slice(0,150))||""}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${r.slug||r.id}`}),e.jsx("meta",{property:"og:title",content:be}),e.jsx("meta",{property:"og:description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${BE[r.property_type]} in ${r.city}, ${r.state}. View photos, details, and contact the listing agent.`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${r.slug||r.id}`}),me&&e.jsx("meta",{property:"og:image",content:me.photo_url}),me&&e.jsx("meta",{property:"og:image:alt",content:`${r.property_address||r.city} - ${BE[r.property_type]} for sale`}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:be}),e.jsx("meta",{name:"twitter:description",content:`${ce(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA in ${r.city}, ${r.state}`}),me&&e.jsx("meta",{name:"twitter:image",content:me.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"geo.region",content:`US-${r.state}`}),e.jsx("meta",{name:"geo.placename",content:r.city}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:r.property_address||`${r.city}, ${r.state} Home`,description:r.description||`${BE[r.property_type]} for sale in ${r.city}, ${r.state}`,url:`https://listings.relevelup.com/${r.slug||r.id}`,datePosted:r.created_at,image:ie.map($e=>$e.photo_url),address:{"@type":"PostalAddress",streetAddress:r.property_address||void 0,addressLocality:r.city,addressRegion:r.state,addressCountry:"US"},geo:r.neighborhood?{"@type":"GeoCoordinates",name:r.neighborhood}:void 0,offers:{"@type":"Offer",price:r.price,priceCurrency:"USD",availability:r.status==="sold"?"https://schema.org/SoldOut":r.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:r.bedrooms||void 0,numberOfBathroomsTotal:r.bathrooms||void 0,floorSize:r.square_footage?{"@type":"QuantitativeValue",value:r.square_footage,unitCode:"FTK"}:void 0,yearBuilt:r.year_built||void 0,broker:r.agent?{"@type":"RealEstateAgent",name:r.agent.name,email:r.agent.email,worksFor:(Me=r.agent.brokerage)!=null&&Me.name?{"@type":"RealEstateAgent",name:r.agent.brokerage.name}:void 0}:void 0})})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Kn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Mue,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs(Kn,{to:"/public/listings",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),ie.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>Y(0),children:e.jsx("img",{src:me==null?void 0:me.photo_url,alt:`${r.property_address||r.city+", "+r.state} - ${BE[r.property_type]} main photo`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ie.slice(1,5).map(($e,Se)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>Y(Se+1),children:[e.jsx("img",{src:$e.photo_url,alt:`${r.property_address||r.city} - Photo ${Se+2} of ${ie.length}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),Se===3&&ie.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",ie.length-5," more"]})]},$e.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Ge,{className:`${l$t[r.status]} text-white border-0`,children:c$t[r.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:ce(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ja,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(e0,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(fp,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx($g,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(rn,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),BE[r.property_type]]}),r.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[r.video&&r.video.playback_url&&e.jsx(Ne,{className:"overflow-hidden bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20",children:e.jsxs(De,{className:"p-0",children:[e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>de(!0),children:[r.video.thumbnail_url?e.jsx("img",{src:r.video.thumbnail_url,alt:"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/20 to-primary/30",children:e.jsx(sn,{className:"h-12 w-12 text-primary"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 group-hover:bg-black/40 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/90 group-hover:bg-white flex items-center justify-center transition-colors shadow-lg",children:e.jsx(Ho,{className:"h-8 w-8 text-primary fill-primary ml-1"})})})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs(G,{onClick:()=>de(!0),className:"w-full gap-2",size:"lg",children:[e.jsx(Ho,{className:"h-4 w-4"}),"Watch Video Tour"]}),r.video.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center truncate",children:r.video.title})]})]})}),r.agent&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bi,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"font-semibold text-lg",children:r.agent.name}),((Pe=r.agent.brokerage)==null?void 0:Pe.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),e.jsxs(Ne,{className:"border-primary",children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(De,{children:X?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(Qs,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:B==="showing"?"Showing request sent!":"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:B==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you soon."})]}):e.jsxs(Rn,{value:B,onValueChange:$e=>z($e),children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Xt,{value:"info",className:"gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Get Info"]}),e.jsxs(Xt,{value:"showing",className:"gap-1.5",children:[e.jsx(Bv,{className:"h-3.5 w-3.5"}),"Request Tour"]})]}),e.jsxs("form",{onSubmit:ae,className:"space-y-3",children:[e.jsxs(as,{value:"showing",className:"mt-0 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(ke,{id:"preferredDate",type:"date",value:N,onChange:$e=>S($e.target.value),min:new Date().toISOString().split("T")[0],required:B==="showing"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(zs,{value:T,onValueChange:A,children:[e.jsx(Os,{id:"preferredTime",children:e.jsx(Us,{placeholder:"Any time"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(mt,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(mt,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(zs,{value:P,onValueChange:$e=>D($e),children:[e.jsx(Os,{id:"showingMode",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(mt,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(mt,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"firstName",children:"First Name *"}),e.jsx(ke,{id:"firstName",type:"text",placeholder:"John",value:o,onChange:$e=>c($e.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ke,{id:"lastName",type:"text",placeholder:"Doe",value:d,onChange:$e=>h($e.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email *"}),e.jsx(ke,{id:"email",type:"email",placeholder:"you@example.com",value:m,onChange:$e=>x($e.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"phone",children:["Phone ",B==="showing"&&"*"]}),e.jsx(ke,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:g,onChange:$e=>v($e.target.value),required:B==="showing"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"message",children:B==="showing"?"Anything else?":"Message (optional)"}),e.jsx(ur,{id:"message",placeholder:B==="showing"?"e.g. I have flexibility on weekends":"Any specific questions about the property?",value:j,onChange:$e=>b($e.target.value),rows:2})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:F,children:F?"Submitting...":B==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})]})})]})]})]})]}),e.jsx(vs,{open:Q!==null,onOpenChange:()=>Y(null),children:e.jsxs(ys,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(js,{className:"sr-only",children:e.jsx(bs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Y(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(_r,{className:"h-5 w-5"})}),Q!==null&&ie[Q]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:ie[Q].photo_url,alt:`Photo ${Q+1}`,className:"w-full max-h-[80vh] object-contain"}),ie.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:oe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(Vo,{className:"h-6 w-6"})}),e.jsx("button",{onClick:ge,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(ya,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[Q+1," / ",ie.length]})]})]})]})}),e.jsx(vs,{open:ne,onOpenChange:de,children:e.jsxs(ys,{className:"max-w-4xl p-0 bg-black overflow-hidden",children:[e.jsx(js,{className:"sr-only",children:e.jsx(bs,{children:"Video Tour"})}),e.jsx("button",{onClick:()=>de(!1),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(_r,{className:"h-5 w-5"})}),((Ee=r==null?void 0:r.video)==null?void 0:Ee.playback_url)&&e.jsx("div",{className:"aspect-video w-full",children:e.jsx("iframe",{src:r.video.playback_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function u$t(){var i;const{slug:s}=Xi(),{data:t,isLoading:r,error:n}=Net(s);if(k.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),k.useEffect(()=>{t!=null&&t.id&&fo(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(Vs,{className:"h-28 w-28 rounded-full"}),e.jsx(Vs,{className:"h-6 w-48"}),e.jsx(Vs,{className:"h-4 w-36"})]}),e.jsx(Vs,{className:"h-12 w-full"}),e.jsx(Vs,{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(il,{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(h3e,{card:t})]})}function Unt({slugOverride:s}={}){var Ke;const{slug:t}=Xi(),r=s||t,[n]=Lc(),a=n.get("t"),[i,l]=k.useState(!0),[o,c]=k.useState(null),[d,h]=k.useState(null),m=k.useRef(null),x=k.useRef(null),[g,v]=k.useState(null),[j,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[P,D]=k.useState(0),[B,z]=k.useState(!1),[F,$]=k.useState(""),[X,K]=k.useState(""),[Q,Y]=k.useState(""),[ne,de]=k.useState(""),[ce,ae]=k.useState(""),[ie,me]=k.useState(""),[oe,ge]=k.useState(""),[be,Oe]=k.useState(""),[Me,Pe]=k.useState(""),[Ee,$e]=k.useState(""),[Se,ze]=k.useState(""),[Te,ye]=k.useState("");k.useEffect(()=>{ct()},[r,a]);const ct=async()=>{if(!r)return;l(!0);const{data:Ce,error:nt}=await H.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(nt||!Ce){z(!0),l(!1);return}h(Ce),x.current=Ce;const{data:$t}=await H.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ce.user_id).single();if($t){let lt;if($t.brokerage_id){const{data:Ft}=await H.from("brokerages").select("name").eq("id",$t.brokerage_id).single();lt=(Ft==null?void 0:Ft.name)||void 0}let it=$t.avatar_url||null;if(!it){const{data:Ft}=H.storage.from("avatars").getPublicUrl(`${Ce.user_id}/avatar.jpg`);Ft!=null&&Ft.publicUrl&&(it=`${Ft.publicUrl}?t=${Date.now()}`)}const Nt={...$t,avatar_url:it,brokerage_name:lt};c(Nt),m.current=Nt}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ce.id);const{data:lt,error:it}=await H.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ce.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:lt,resolveErr:it}),!it&&(lt!=null&<.contact_id)){b(lt.contact_id);const Nt=lt.contact;Nt&&(v(Nt),$(Nt.first_name||""),K(Nt.last_name||""),Y(Nt.email||""),de(Nt.phone||""),ae(Nt.address||""),me(Nt.city||""),ge(Nt.state||""),Oe(Nt.zip||""),Pe(Nt.birthday||""),$e(Nt.home_anniversary||""))}}catch(lt){console.error("Failed to resolve token:",lt)}l(!1)},ve=async()=>{var Ce,nt;if(!F.trim()){ue.error("Please enter your first name");return}if(!r){ue.error("Invalid page. Please refresh.");return}A(!0);try{let $t=(Ce=x.current)==null?void 0:Ce.id,lt=(nt=x.current)==null?void 0:nt.user_id;if(!$t||!lt){const{data:Nt}=await H.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!Nt){ue.error("This page is no longer active. Please contact the agent directly."),A(!1);return}$t=Nt.id,lt=Nt.user_id}const{error:it}=await H.from("contact_intake_submissions").insert({intake_page_id:$t,agent_user_id:lt,existing_contact_id:j,first_name:F.trim(),last_name:X.trim()||null,email:Q.trim()||null,phone:ne.trim()||null,address:ce.trim()||null,city:ie.trim()||null,state:oe.trim()||null,zip:be.trim()||null,birthday:Me||null,home_anniversary:Ee||null,real_estate_interest:Se||null,message:Te.trim()||null});if(console.log("[ConnectPage] Insert result:",{error:it}),it)throw it;a&&await H.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Nt=[F.trim(),X.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:lt,contactName:Nt,contactEmail:Q.trim()||null,contactPhone:ne.trim()||null,slug:r})})}catch(Nt){console.warn("Connect page notification failed (non-blocking):",Nt)}S(!0)}catch($t){console.error($t),ue.error("Something went wrong. Please try again.")}finally{A(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-slate-400"})});if(B)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(N)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(il,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Cr.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(Cr.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(Mn,{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(hi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const rt=!!a&&!!g,Re=3,Qe=[{title:rt?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"First Name *"}),e.jsx("input",{type:"text",value:F,onChange:Ce=>$(Ce.target.value),placeholder:"Jane",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Last Name"}),e.jsx("input",{type:"text",value:X,onChange:Ce=>K(Ce.target.value),placeholder:"Smith",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Email"}),e.jsx("input",{type:"email",value:Q,onChange:Ce=>Y(Ce.target.value),placeholder:"jane@email.com",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Phone"}),e.jsx("input",{type:"tel",value:ne,onChange:Ce=>de(Ce.target.value),placeholder:"(555) 123-4567",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Street Address"}),e.jsx("input",{type:"text",value:ce,onChange:Ce=>ae(Ce.target.value),placeholder:"123 Main St",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"City"}),e.jsx("input",{type:"text",value:ie,onChange:Ce=>me(Ce.target.value),placeholder:"Austin",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"State"}),e.jsx("input",{type:"text",value:oe,onChange:Ce=>ge(Ce.target.value),placeholder:"TX",maxLength:2,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Zip"}),e.jsx("input",{type:"text",value:be,onChange:Ce=>Oe(Ce.target.value),placeholder:"78701",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Birthday"}),e.jsx("input",{type:"date",value:Me,onChange:Ce=>Pe(Ce.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Home Anniversary"}),e.jsx("input",{type:"date",value:Ee,onChange:Ce=>$e(Ce.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})]})},{title:"One Last Thing",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:[{value:"buying",label:"🏠 Buying",desc:"Looking for a home"},{value:"selling",label:"📋 Selling",desc:"Thinking of selling"},{value:"both",label:"🔄 Both",desc:"Buy & sell"},{value:"not_now",label:"😊 Not right now",desc:"Just staying connected"}].map(Ce=>e.jsxs("button",{type:"button",onClick:()=>ze(Se===Ce.value?"":Ce.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Se===Ce.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:Ce.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ce.desc})]},Ce.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Te,onChange:Ce=>ye(Ce.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all resize-none"})]})]})}];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50",children:[e.jsxs(il,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-8 sm:py-12",children:[e.jsxs(Cr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"text-center mb-8",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto mb-4 ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 mx-auto mb-4 flex items-center justify-center ring-4 ring-white shadow-lg",children:e.jsx("span",{className:"text-3xl font-bold text-white",children:((Ke=o==null?void 0:o.name)==null?void 0:Ke.charAt(0))||"?"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:o==null?void 0:o.name}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-slate-500 mt-0.5",children:o.title}),(o==null?void 0:o.brokerage_name)&&e.jsx("p",{className:"text-sm text-slate-400",children:o.brokerage_name}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[(o==null?void 0:o.phone)&&e.jsx("a",{href:`tel:${o.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Call agent",children:e.jsx(Nn,{className:"h-4.5 w-4.5"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Email agent",children:e.jsx(Qs,{className:"h-4.5 w-4.5"})})]})]}),e.jsx(Cr.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"text-center text-slate-600 mb-8 px-4 leading-relaxed",children:(d==null?void 0:d.welcome_message)||"I'd love to stay connected! Fill in your info below."}),e.jsx("div",{className:"flex gap-2 mb-8 px-2",children:Array.from({length:Re}).map((Ce,nt)=>e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-all duration-500 ${nt<=P?"bg-blue-500":"bg-slate-200"}`},nt))}),e.jsxs(Cr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 p-6 sm:p-8",children:[e.jsx(i5e,{mode:"wait",children:e.jsxs(Cr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(jr,{className:"h-5 w-5 text-blue-500"}),e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:Qe[P].title})]}),Qe[P].fields]},P)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[P>0?e.jsx("button",{type:"button",onClick:()=>D(Ce=>Ce-1),className:"px-5 py-2.5 text-sm font-medium text-slate-600 hover:text-slate-800 transition-colors",children:"Back"}):e.jsx("div",{}),P{if(P===0&&!F.trim()){ue.error("Please enter your first name");return}D(Ce=>Ce+1)},className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm",children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>ve(),disabled:T,className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50 flex items-center gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),P>0&&PD(Ce=>Ce+1),className:"text-xs text-slate-400 hover:text-slate-500 transition-colors",children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs text-slate-400",children:[e.jsx(hi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const MP=()=>({trackEngagement:k.useCallback(async(t,r,n,a="view")=>{try{const{data:{user:i}}=await H.auth.getUser();if(!i)return;await H.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 HD({banners:s,autoPlayInterval:t=5e3,className:r}){const[n,a]=k.useState(0),[i,l]=k.useState(!1),{trackEngagement:o}=MP(),c=k.useCallback(g=>{o("newsletter",g.id,g.title,"click_link")},[o]),d=k.useCallback(()=>{a(g=>(g+1)%s.length)},[s.length]),h=k.useCallback(()=>{a(g=>(g-1+s.length)%s.length)},[s.length]),m=k.useCallback(g=>{a(g)},[]);if(k.useEffect(()=>{if(s.length<=1||i)return;const g=setInterval(d,t);return()=>clearInterval(g)},[s.length,i,t,d]),!s||s.length===0)return null;const x=s[n];return e.jsxs("div",{className:Bt("relative w-full overflow-hidden rounded-xl",r),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:x.image_url,alt:x.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",className:Bt("absolute left-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",i&&"opacity-100"),onClick:h,children:e.jsx(Vo,{className:"h-6 w-6"})}),e.jsx(G,{variant:"ghost",size:"icon",className:Bt("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(ya,{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((g,v)=>e.jsx("button",{onClick:()=>m(v),className:Bt("w-2 h-2 rounded-full transition-all duration-300",v===n?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${v+1}`},v))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:x.title}),x.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:x.description})]}),x.link_url&&e.jsx("a",{href:x.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(x),children:e.jsx(G,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:x.link_text||"Learn More"})})]})]})}function h$t(s){return"EST"}function lF(s){const r=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),n=h$t();return`${r} ${n}`}function SM(s){const t=new Date,r=new Date(s),n=EA(r,-15),a=EA(r,30);return t>a?"ended":$y(t,{start:r,end:a})?"live":$y(t,{start:n,end:r})?"starting_soon":"upcoming"}function C5e(s){const t=SM(s);return t==="starting_soon"||t==="live"}const zFe=C5e,m$t=({events:s,registrations:t,onNavigateToEvents:r})=>{const[n,a]=k.useState(new Date);k.useEffect(()=>{const g=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(g)},[]);const i=s.filter(g=>C5e(g.event_date));if(i.length===0)return null;const l=i[0],o=SM(l.event_date),c=t.find(g=>g.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,h=!!c,m=o==="live",x=m?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${x.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${x.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${x.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${x.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${x.text} font-bold text-sm uppercase tracking-wider`,children:m?e.jsxs(e.Fragment,{children:[e.jsx(r_,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{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 ${lF(new Date(l.event_date))}`:`Starts at ${lF(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:h?e.jsxs(G,{onClick:()=>window.open(d,"_blank"),className:`${x.button} text-white gap-2`,children:[e.jsx(Yr,{className:"h-4 w-4"}),m?"Join Now":"Join When Live"]}):e.jsxs(G,{variant:"outline",onClick:r,className:`${x.outlineButton} gap-2`,children:[e.jsx(fr,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function f$t(){const{user:s,isBrokerageManager:t}=As(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(!0),h=t?"brokerage_manager":"agent";k.useEffect(()=>{if(!(s!=null&&s.id)){d(!1);return}m()},[s==null?void 0:s.id,h]);const m=async()=>{if(s!=null&&s.id)try{const{data:A,error:P}=await H.from("onboarding_checklist_items").select("*").eq("target_role",h).eq("is_active",!0).order("sort_order");if(P)throw P;const{data:D,error:B}=await H.from("onboarding_checklist_progress").select("item_id, completed_at").eq("user_id",s.id);if(B)throw B;const{data:z,error:F}=await H.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle();if(F)throw F;n(A||[]),i(D||[]),o(!!z),A&&A.length>0&&await x(A,D||[])}catch(A){console.error("Error fetching checklist data:",A)}finally{d(!1)}},x=async(A,P)=>{var $e,Se;if(!(s!=null&&s.id))return;const D=P.map(ze=>ze.item_id),B=A.filter(ze=>!D.includes(ze.id));if(B.length===0)return;const[z,F,$,X,K,Q,Y,ne,de,ce,ae,ie,me,oe,ge]=await Promise.all([H.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle(),H.from("resource_shares").select("id",{count:"exact",head:!0}).eq("sender_id",s.id),H.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),H.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),H.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","template"),H.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","academy_video"),H.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","toolbox"),H.from("activity_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id),H.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),H.from("agent_videos").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),H.from("contact_touch_logs").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),H.from("scorecard_transactions").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),H.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",s.id),H.from("innercircle_contacts").select("id").eq("owner_user_id",s.id),H.from("deal_pipeline").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id)]),be={},Oe=($e=z.data)==null?void 0:$e.brokerage_id;be.share_resource=(F.count||0)>0,be.post_community=($.count||0)>0,be.register_event=(X.count||0)>0,be.view_template=(K.count||0)>0,be.watch_academy=(Q.count||0)>0,be.use_toolbox=(Y.count||0)>0,be.launch_app=(ne.count||0)>0,be.add_contact=(de.count||0)>0,be.create_video=(ce.count||0)>0,be.complete_touch=(ae.count||0)>0,be.add_transaction=(ie.count||0)>0,be.add_listing=(me.count||0)>0,be.add_deal=(ge.count||0)>0;const Me=((Se=oe.data)==null?void 0:Se.map(ze=>ze.id))||[],Pe=[];Oe?Pe.push(H.from("profiles").select("id").eq("brokerage_id",Oe).neq("id",s.id).then(ze=>{var Te;be.add_agent=(((Te=ze.data)==null?void 0:Te.length)||0)>0})):be.add_agent=!1,Me.length>0?(Pe.push(H.from("contact_plan_cycles").select("id",{count:"exact",head:!0}).in("contact_id",Me).then(ze=>{be.add_plan=(ze.count||0)>0})),Pe.push(H.from("contact_popby_settings").select("id",{count:"exact",head:!0}).in("contact_id",Me).then(ze=>{be.schedule_popby=(ze.count||0)>0}))):(be.add_plan=!1,be.schedule_popby=!1),await Promise.all(Pe);const Ee=B.filter(ze=>be[ze.action_type]);if(Ee.length>0){const ze=Ee.map(ye=>({user_id:s.id,item_id:ye.id})),{error:Te}=await H.from("onboarding_checklist_progress").upsert(ze,{onConflict:"user_id,item_id",ignoreDuplicates:!0});if(!Te){const ye=Ee.map(ct=>({item_id:ct.id,completed_at:new Date().toISOString()}));i(ct=>[...ct,...ye])}}},g=async A=>{if(s!=null&&s.id)try{const{error:P}=await H.from("onboarding_checklist_progress").insert({user_id:s.id,item_id:A});if(P)throw P;i(D=>[...D,{item_id:A,completed_at:new Date().toISOString()}])}catch(P){console.error("Error marking item complete:",P)}},v=async()=>{if(s!=null&&s.id)try{const{error:A}=await H.from("onboarding_checklist_dismissed").insert({user_id:s.id});if(A)throw A;o(!0)}catch(A){console.error("Error dismissing checklist:",A)}},j=a.length,b=r.length,N=b>0&&j>=b,S=b>0?j/b*100:0;return{items:r,progress:a,isDismissed:l,loading:c,completedCount:j,totalCount:b,isComplete:N,progressPercentage:S,isItemComplete:A=>a.some(P=>P.item_id===A),markComplete:g,dismiss:v,refetch:m}}const p$t={add_agent:e.jsx(fr,{className:"h-4 w-4"}),share_resource:e.jsx(Pc,{className:"h-4 w-4"}),post_community:e.jsx(bi,{className:"h-4 w-4"}),register_event:e.jsx(rn,{className:"h-4 w-4"}),view_template:e.jsx(Pb,{className:"h-4 w-4"}),watch_academy:e.jsx(Od,{className:"h-4 w-4"}),use_toolbox:e.jsx(i0,{className:"h-4 w-4"}),launch_app:e.jsx(VR,{className:"h-4 w-4"}),add_deal:e.jsx(Uv,{className:"h-4 w-4"}),add_listing:e.jsx(Cn,{className:"h-4 w-4"})},x$t={add_deal:"/mission-control/pipeline",add_listing:"/mission-control/listings/new",post_community:"/community",add_contact:"/mission-control/contacts"};function g$t(){const{items:s,isDismissed:t,loading:r,completedCount:n,totalCount:a,isComplete:i,progressPercentage:l,isItemComplete:o,markComplete:c,dismiss:d}=f$t(),h=vr(),[m,x]=k.useState(!0);return r||t||a===0||i?null:e.jsxs(Ne,{className:"mb-6 border-primary/20 bg-gradient-to-r from-primary/5 to-transparent",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Gv,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Get Started with LevelUp"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Complete these steps to make the most of your membership"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>x(!m),className:"h-8 w-8 p-0",children:m?e.jsx(xp,{className:"h-4 w-4"}):e.jsx(so,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(_r,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Progress"}),e.jsxs("span",{className:"font-medium",children:[n," of ",a," complete"]})]}),e.jsx(ri,{value:l,className:"h-2"})]})]}),m&&e.jsx(De,{className:"pt-0",children:e.jsx("div",{className:"space-y-3",children:s.map(g=>{const v=o(g.id);return e.jsxs("div",{className:Bt("flex items-start gap-3 p-3 rounded-lg transition-colors",v?"bg-muted/50":"bg-background hover:bg-muted/30 cursor-pointer"),onClick:()=>{if(v)return;const j=x$t[g.action_type];j?h(j):c(g.id)},children:[e.jsx("div",{className:"mt-0.5",children:v?e.jsx(Mn,{className:"h-5 w-5 text-primary"}):e.jsx(Bd,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:p$t[g.action_type]||e.jsx(Bd,{className:"h-4 w-4"})}),e.jsx("span",{className:Bt("font-medium",v&&"line-through text-muted-foreground"),children:g.title})]}),g.description&&e.jsx("p",{className:Bt("text-sm text-muted-foreground mt-1",v&&"line-through"),children:g.description})]})]},g.id)})})})]})}const qx=()=>gt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await H.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),$m=s=>{const t=na(),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=H.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})},y$t=s=>gt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:r}=await H.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}),qnt=()=>{const s=na();return gt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:r}=await H.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})},exe=()=>{const s=es(),t=na();return Lt({mutationFn:async r=>{const{tagIds:n,...a}=r,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,owner_user_id:t},{data:l,error:o}=await H.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(n&&n.length>0){const{error:c}=await H.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"]}),nn({title:"Contact created successfully"})},onError:r=>{nn({title:"Error creating contact",description:r.message,variant:"destructive"})}})},T5e=()=>{const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{tagIds:n,tags:a,...i}=r,l={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null},{data:o,error:c}=await H.from("innercircle_contacts").update(l).eq("id",t).select().single();if(c)throw c;if(n!==void 0&&(await H.from("innercircle_contact_tags").delete().eq("contact_id",t),n.length>0)){const{error:d}=await H.from("innercircle_contact_tags").insert(n.map(h=>({contact_id:t,relationship_type_id:h})));if(d)throw d}return o},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),nn({title:"Contact updated successfully"})},onError:t=>{nn({title:"Error updating contact",description:t.message,variant:"destructive"})}})},Vnt=()=>{const s=es();return Lt({mutationFn:async({contactId:t,spouseContactId:r})=>{if(r){const{error:n}=await H.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",t);if(n)throw n;const{error:a}=await H.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",r);if(a)throw a}else{const{data:n}=await H.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=n==null?void 0:n.spouse_contact_id,{error:i}=await H.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await H.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"]}),nn({title:"Spouse link updated"})},onError:t=>{nn({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},E5e=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("innercircle_contacts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),nn({title:"Contact deleted successfully"})},onError:t=>{nn({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},tz=()=>gt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await H.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),v$t=s=>gt({queryKey:["action-scripts",s],queryFn:async()=>{let t=H.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await t;if(n)throw n;return r}}),b$t=()=>gt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await H.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),_$t=()=>{const s=es(),t=na();return Lt({mutationFn:async({name:r,description:n})=>{const{data:a,error:i}=await H.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"]}),nn({title:"Plan created successfully"})},onError:r=>{nn({title:"Error creating plan",description:r.message,variant:"destructive"})}})},w$t=()=>{const s=es(),t=na();return Lt({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:a,error:i}=await H.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 H.from("touchpoint_plans").insert({name:n,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(h=>({plan_id:l.id,month_number:h.month_number,action_type_id:h.action_type_id,default_script_id:h.default_script_id,notes:h.notes})),{error:d}=await H.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),nn({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{nn({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},j$t=()=>{const s=es();return Lt({mutationFn:async({id:t,name:r,description:n})=>{const{data:a,error:i}=await H.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"]}),nn({title:"Plan updated successfully"})}})},N$t=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("touchpoint_plans").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),nn({title:"Plan deleted successfully"})}})},k$t=()=>{const s=es();return Lt({mutationFn:async({planId:t,items:r})=>{if(await H.from("touchpoint_plan_items").delete().eq("plan_id",t),r.length>0){const{error:n}=await H.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"]}),nn({title:"Plan schedule updated"})}})},S$t=()=>{const s=es();return Lt({mutationFn:async({actionTypeId:t,title:r,scriptBody:n,emailSubject:a,tone:i})=>{const{data:{user:l}}=await H.auth.getUser(),{data:o,error:c}=await H.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"]}),nn({title:"Script created successfully"})},onError:t=>{nn({title:"Error creating script",description:t.message,variant:"destructive"})}})},C$t=()=>{const s=na();return gt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:r}=await H.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return t},enabled:!!s})},T$t=()=>{const s=es(),t=na();return Lt({mutationFn:async({planId:r,relationshipTypeId:n,active:a})=>{const{data:i}=await H.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(i){const{error:l}=await H.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await H.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"]}),nn({title:"Plan enrollment updated"})}})},sz=(s=7)=>{const t=na();return gt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-s);const{data:n,error:a}=await H.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})},Hnt=()=>{const s=na();return gt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:r}=await H.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})},E$t=(s=90)=>{const{data:t}=$m(),{data:r}=Hnt();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=es(),t=na();return Lt({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await H.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"]}),nn({title:"Action completed!"});try{const[l,o]=await Promise.all([H.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),H.from("action_types").select("name").eq("id",n.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";c&&H.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{}}})},Gnt="agentos_weekly_touch_goal",$Fe=20,the=()=>{if(typeof window>"u")return $Fe;const s=localStorage.getItem(Gnt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return $Fe},Wnt=s=>{localStorage.setItem(Gnt,s.toString())},A5e=()=>{const{data:s}=sz(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=the();return{actionsThisWeek:n,weeklyGoal:i,streak:a,progress:Math.min(n/i*100,100)}},A$t=()=>{const s=na();return gt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:r}=await H.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})},M$t=()=>{const s=es();return na(),Lt({mutationFn:async()=>{const{data:t}=await H.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:r}=await H.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(!r)return;const{data:n}=await H.from("contact_plan_cycles").select("contact_id, plan_id"),a=new Set((n==null?void 0:n.map(l=>`${l.contact_id}-${l.plan_id}`))||[]),i=[];for(const l of r)for(const o of l.tags||[]){const c=t.find(d=>d.relationship_type_id===o.relationship_type_id);c&&!a.has(`${l.id}-${c.plan_id}`)&&i.push({contact_id:l.id,plan_id:c.plan_id,relationship_type_id:o.relationship_type_id})}if(i.length>0){const{error:l}=await H.from("contact_plan_cycles").insert(i);if(l)throw l}return i.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&nn({title:`${t} contact(s) enrolled in plans`})}})},Knt=()=>{const s=na(),{data:t}=A$t(),{data:r}=sz(30);return gt({queryKey:["today-actions",s,t==null?void 0:t.length,r==null?void 0:r.length],queryFn:async()=>{var v;if(!t||t.length===0)return[];const{data:n}=await H.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((n==null?void 0:n.map(j=>j.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((r==null?void 0:r.filter(j=>new Date(j.completed_at)>=o).map(j=>`${j.contact_id}-${j.action_type_id}`))||[]);for(const j of t){if(!((v=j.plan)!=null&&v.items)||j.plan.items.length===0||!j.contact||a.has(j.contact_id))continue;const b=new Date(j.cycle_start_date),S=Math.floor((i.getTime()-b.getTime())/(30.44*24*60*60*1e3))%12+1,T=j.plan.items.find(A=>A.month_number===S);if(T&&T.action_type){const A=`${j.contact_id}-${T.action_type_id}`;if(!c.has(A)){const{data:P}=await H.from("relationship_types").select("name").eq("id",j.relationship_type_id).single();l.push({contact:j.contact,actionType:T.action_type,script:T.default_script||void 0,planName:j.plan.name,relationshipTypeName:(P==null?void 0:P.name)||"",monthNumber:S})}}}const d=5,h=i.getDate(),m=l.sort((j,b)=>j.contact.first_name.localeCompare(b.contact.first_name)),x=(h-1)%Math.max(1,m.length);return[...m.slice(x),...m.slice(0,x)].slice(0,d)},enabled:!!s&&!!t})};function I$t(){const s=vr(),{data:t,isLoading:r}=Knt(),{data:n}=$m(),a=A5e(),[i,l]=k.useState(the()),[o,c]=k.useState(""),[d,h]=k.useState(!1);k.useEffect(()=>{l(the())},[]);const m=()=>{const D=parseInt(o,10);if(isNaN(D)||D<1){nn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(D),Wnt(D),h(!1),nn({title:"Goal updated",description:`Weekly touch goal set to ${D}`})},x=()=>{c(i.toString()),h(!0)},g=Tf(new Date),v=Hl(g,7),j=D=>{if(!D)return null;const B=D.split(/[-/T]/);if(B.length<3)return null;const z=parseInt(B[1],10)-1,F=parseInt(B[2],10);return isNaN(z)||isNaN(F)?null:new Date(g.getFullYear(),z,F)},b=(n==null?void 0:n.map(D=>{const B=j(D.birthday),z=j(D.home_anniversary),F=[];return B&&B>=g&&B<=v&&F.push({contact:D,type:"birthday",date:B,isToday:$l(B,g)}),z&&z>=g&&z<=v&&F.push({contact:D,type:"anniversary",date:z,isToday:$l(z,g)}),F}).flat().sort((D,B)=>D.date.getTime()-B.date.getTime()).slice(0,3))||[],N=(n==null?void 0:n.filter(D=>{const B=j(D.birthday),z=j(D.home_anniversary);return B&&$l(B,g)||z&&$l(z,g)}).length)||0,S=(t==null?void 0:t.length)||0,T=N+S,A=(a==null?void 0:a.actionsThisWeek)||0,P=(a==null?void 0:a.streak)||0;return r?e.jsx(Ne,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(De,{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(Ne,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:P>0&&e.jsxs(Ge,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(xc,{className:"h-3 w-3"}),P," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[T," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control")},children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:D=>{D.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(ja,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:D=>{D.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(Uv,{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(zd,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(vs,{open:d,onOpenChange:h,children:[e.jsx(Ni,{asChild:!0,children:e.jsx("button",{onClick:x,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(lo,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(ys,{className:"sm:max-w-[360px]",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Set Weekly Goal"}),e.jsx(Fr,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(ke,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:D=>c(D.target.value),placeholder:"20",onKeyDown:D=>{D.key==="Enter"&&m()}})]}),e.jsx(G,{onClick:m,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(ri,{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(Eh,{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,B)=>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:z=>{z.stopPropagation(),s(`/mission-control/contacts/${D.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.type==="birthday"?e.jsx(Eh,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(Cn,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[D.contact.first_name," ",D.contact.last_name]}),D.isToday&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.isToday?D.type==="birthday"?"🎂":"🏠":Ss(D.date,"EEE, MMM d")}),e.jsx(ya,{className:"h-3 w-3"})]})]},`${D.contact.id}-${D.type}-${B}`))})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>s("/mission-control"),children:["Open Agent OS",e.jsx(Ga,{className:"h-4 w-4"})]})]})]})}function P$t(s){return gt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(r)throw r;return t},enabled:!!s})}function L$t(s,t){return gt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let r=H.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 D$t(s,t=4){return gt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:r,error:n}=await H.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 R$t(s){const t=es();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.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 O$t(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("brokerage_content").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function F$t(s){const t=es();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.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 B$t(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("brokerage_content_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function z$t(s){const t=es();return Lt({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 H.from("brokerage_content_categories").upsert(r,{onConflict:"brokerage_id,name"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const $$t={video:Ho,pdf:ln,link:rl,event:rn,graphic:pl},U$t={video:"bg-red-500/10 text-red-600 dark:text-red-400",pdf:"bg-blue-500/10 text-blue-600 dark:text-blue-400",link:"bg-green-500/10 text-green-600 dark:text-green-400",event:"bg-purple-500/10 text-purple-600 dark:text-purple-400",graphic:"bg-amber-500/10 text-amber-600 dark:text-amber-400"};function q$t(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function V$t(s){if(!s)return!1;try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function H$t({item:s}){const t=vr(),r=$$t[s.content_type]||rl,n=U$t[s.content_type]||"",[a,i]=k.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?q$t(s.url):null);k.useEffect(()=>{l||!s.url||s.content_type!=="video"||!V$t(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(Ne,{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(De,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Ge,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${n}`,children:[e.jsx(r,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Ss(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function G$t(){const{brokerageId:s}=As(),t=vr(),{data:r=[],isLoading:n}=D$t(s,4);return!s||n||r.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{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(H$t,{item:a},a.id))})]})}const Ynt=()=>gt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await H.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),Znt=s=>{const{user:t,brokerageId:r}=As();return gt({queryKey:["listings",s,r],queryFn:async()=>{let n=H.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 H.from("profiles").select("id").eq("brokerage_id",r);if(o&&o.length>0){const c=o.map(m=>m.id);let d=H.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:h}=await d;if(h){const m=new Set(l.map(g=>g.id)),x=h.filter(g=>!m.has(g.id));l=[...l,...x]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},Xnt=()=>{const{user:s}=As();return gt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})},Qnt=s=>{const{user:t}=As();return gt({queryKey:["listing",s],queryFn:async()=>{const{data:r,error:n}=await H.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 H.from("listing_views").insert({listing_id:s,viewer_id:t.id}),r},enabled:!!s})},W$t=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:a}=await H.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"]})}})},K$t=()=>{const s=es();return Lt({mutationFn:async({agentId:t,...r})=>{const{data:n,error:a}=await H.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"]})}})},Y$t=()=>{const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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]})}})},Jnt=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("listings").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Z$t=()=>{const s=es();return Lt({mutationFn:async({listingId:t,photoUrl:r,isPrimary:n=!1})=>{const{data:a,error:i}=await H.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"]})}})},X$t=()=>{const s=es();return Lt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await H.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"]})}})},Q$t=()=>{const s=es();return Lt({mutationFn:async({photos:t})=>{var i;const r=t.map(l=>H.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"]})}})},J$t=()=>{const s=es();return Lt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await H.from("listing_photos").update({is_primary:!1}).eq("listing_id",r);if(n)throw n;const{error:a}=await H.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"]})}})},eUt=()=>{const{user:s}=As();return gt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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})},eat=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await H.from("listing_saves").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await H.from("listing_saves").delete().eq("id",n.id),{saved:!1}):(await H.from("listing_saves").insert({listing_id:r,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},tat=s=>{const{user:t}=As();return gt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await H.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},tUt=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await H.from("listing_follows").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await H.from("listing_follows").delete().eq("id",n.id),{following:!1}):(await H.from("listing_follows").insert({listing_id:r,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},sUt=s=>{const{user:t}=As();return gt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await H.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},rUt=()=>{const{user:s}=As();return Lt({mutationFn:async({listingId:t,shareType:r})=>{if(!s)throw new Error("Not authenticated");const{error:n}=await H.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:r});if(n)throw n}})},nUt=()=>{const{user:s}=As();return gt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,r]=await Promise.all([H.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),H.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})},aUt=()=>{const s=es(),{user:t}=As();return Lt({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 H.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"]})}})},iUt=()=>gt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await H.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 H.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}}}),oUt=()=>{const{user:s,brokerageId:t}=As();return gt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:r}=await H.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 H.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})},sat=({className:s,variant:t="default"})=>e.jsx(Ge,{variant:"outline",className:Bt("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"}),lUt={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"},cUt={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function dUt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function uUt(){const s=vr(),{data:t,isLoading:r}=Ynt(),{data:n,isLoading:a}=Znt({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(n==null?void 0:n.filter(h=>h.is_approved&&h.is_public))||[],l=i.filter(h=>h.is_featured),o=i.filter(h=>!h.is_featured),c=[...l,...o].slice(0,6),d=r||a;return!d&&!t?null:d?e.jsx(Ne,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(De,{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(sat,{})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx(G,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(h=>{var x,g;const m=((x=h.photos)==null?void 0:x.find(v=>v.is_primary))||((g=h.photos)==null?void 0:g[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${h.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[m!=null&&m.photo_url?e.jsx("img",{src:m.photo_url,alt:`${h.city}, ${h.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/50"})}),h.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Ge,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Qn,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Ge,{className:`text-[10px] px-1.5 py-0.5 ${lUt[h.status]}`,children:cUt[h.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:dUt(h.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[h.city,", ",h.state]}),(h.bedrooms||h.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[h.bedrooms&&`${h.bedrooms} bed`,h.bedrooms&&h.bathrooms&&" · ",h.bathrooms&&`${h.bathrooms} bath`]})]})]},h.id)})})]})}function rat(s=10,t){return gt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:r}=await H.from("user_roles").select("user_id").eq("role","admin"),n=new Set((r==null?void 0:r.map(x=>x.user_id))||[]);let a=null;if(t){const{data:x}=await H.from("profiles").select("id").eq("brokerage_id",t);a=new Set((x==null?void 0:x.map(g=>g.id))||[])}const{data:i,error:l}=await H.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+n.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(x=>!n.has(x.user_id));a&&(o=o.filter(x=>a.has(x.user_id)));const c=o.slice(0,s),d=c.map(x=>x.user_id),{data:h}=await H.from("profiles").select("id, name").in("id",d),m=new Map((h==null?void 0:h.map(x=>[x.id,{name:x.name}]))||[]);return c.map(x=>({user_id:x.user_id,total_points:x.total_points,total_events_attended:x.total_events_attended,current_streak:x.current_streak,profile:m.get(x.user_id)||null}))}})}function nat(s){return gt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return t},enabled:!!s})}function aat(s){return gt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function iat(s,t){return gt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:r}=await H.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!r)return null;const{data:n}=await H.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 H.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 H.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(h=>h.id))||[]);o=o.filter(h=>d.has(h.user_id))}return o.length+1},enabled:!!s})}function hUt(){const{user:s,brokerageId:t,isAdmin:r}=As();vr();const n=!!t,[a,i]=k.useState("brokerage"),l=()=>{if(r)return null;if(n)return a==="global"?null:t},{data:o,isLoading:c}=rat(5,l()),{data:d}=nat(s==null?void 0:s.id),{data:h}=iat(s==null?void 0:s.id,l()),{data:m}=aat(s==null?void 0:s.id),x=r||n,g=()=>r?"Agent Leaderboard":n?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Zi,{className:"h-4 w-4 text-yellow-500"}),g()]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...Array(x?5:3)].map((j,b)=>e.jsx(Vs,{className:"h-10 w-full"},b))})})]});const v=j=>j===0?e.jsx(Zi,{className:"h-4 w-4 text-yellow-500 mx-auto"}):j===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):j===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:j+1});if(x){const j=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Zi,{className:"h-4 w-4 text-yellow-500"}),g()]}),!r&&n&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(G,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(G,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(De,{children:[!r&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",h||"-"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-primary",children:d.total_points})," pts"]}),e.jsxs("span",{children:[e.jsx("strong",{children:d.total_events_attended})," events"]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[j.map((b,N)=>{var S,T,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${b.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":N===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:v(N)}),e.jsx(vn,{className:"h-6 w-6",children:e.jsx(bn,{className:"text-xs",children:((T=(S=b.profile)==null?void 0:S.name)==null?void 0:T.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=b.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:b.total_points})]},b.user_id)}),j.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Kn,{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(li,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ya,{className:"h-4 w-4"})]})]})]})}return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Zi,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(De,{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(xc,{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(Xl,{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(j=>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:j.badge_name},j.id)),m.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",m.length-4," more"]})]})]}),e.jsxs(Kn,{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(li,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ya,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Qn,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Kn,{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(li,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(ya,{className:"h-4 w-4"})]})]})})]})}const IP=()=>gt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await H.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),M5e=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{data:n}=await H.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 H.from("lead_sources").insert({name:r,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ue.success("Lead source added")},onError:r=>{ue.error("Failed to add lead source"),console.error(r)}})},mUt=()=>{const s=es();return Lt({mutationFn:async({id:t,name:r})=>{const{error:n}=await H.from("lead_sources").update({name:r}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ue.success("Lead source updated")},onError:t=>{ue.error(t.message||"Failed to update lead source")}})},fUt=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("lead_sources").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ue.success("Lead source removed")},onError:t=>{ue.error(t.message||"Failed to remove lead source")}})},I5e=(s,t)=>{const{user:r,isAdmin:n}=As(),a=n&&t?t:r==null?void 0:r.id;return gt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=H.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})},P5e=s=>{const{user:t,isAdmin:r}=As(),n=r&&s?s:t==null?void 0:t.id;return gt({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:a,error:i}=await H.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})},sxe=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.from("scorecard_transactions").insert({...r,owner_user_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction added")},onError:r=>{ue.error("Failed to add transaction"),console.error(r)}})},pUt=()=>{const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("scorecard_transactions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction updated")},onError:t=>{ue.error("Failed to update transaction"),console.error(t)}})},xUt=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("scorecard_transactions").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction deleted")},onError:t=>{ue.error("Failed to delete transaction"),console.error(t)}})},oat=(s,t)=>{const{user:r,isAdmin:n}=As(),a=n&&t?t:r==null?void 0:r.id;return gt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await H.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},gUt=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.from("scorecard_goals").upsert({...r,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["scorecard-goals",n.year]}),ue.success("Goals saved")},onError:r=>{ue.error("Failed to save goals"),console.error(r)}})},rxe=()=>{const{user:s}=As();return gt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t},enabled:!!(s!=null&&s.id)})},yUt=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{data:n,error:a}=await H.from("scorecard_settings").upsert({...r,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ue.success("Settings saved")},onError:r=>{ue.error("Failed to save settings"),console.error(r)}})},lat=(s,t)=>{const{data:r,isLoading:n}=I5e(s,t),{data:a,isLoading:i}=P5e(t),{data:l}=rxe(),o=(l==null?void 0:l.show_commission)??!0,c=d=>{if(!d||d.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const h=d.filter(P=>P.transaction_type==="buyer").length,m=d.filter(P=>P.transaction_type==="seller").length,x=d.reduce((P,D)=>P+Number(D.sale_price),0),g=d.reduce((P,D)=>P+(Number(D.commission_amount)||0),0),v=d.reduce((P,D)=>{const B=Number(D.commission_amount)||0;if(!B)return P;let z=B;return D.brokerage_split_pct&&(z-=B*(D.brokerage_split_pct/100)),D.team_split_pct&&(z-=B*(D.team_split_pct/100)),D.franchise_fee_pct&&(z-=B*(D.franchise_fee_pct/100)),D.referral_fee_pct&&(z-=B*(D.referral_fee_pct/100)),D.transaction_fee&&(z-=D.transaction_fee),P+Math.max(0,z)},0),j={};d.forEach(P=>{var B;const D=((B=P.lead_source)==null?void 0:B.name)||"Unknown";j[D]=(j[D]||0)+1});const b=Object.entries(j).map(([P,D])=>({name:P,count:D})).sort((P,D)=>D.count-P.count),N=b[0]||null,S={};d.forEach(P=>{const D=Ul(P.close_date).toLocaleString("default",{month:"short"});S[D]=(S[D]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(P=>({month:P,count:S[P]||0}));return{totalTransactions:d.length,buyerCount:h,sellerCount:m,totalVolume:x,averagePrice:d.length>0?x/d.length:0,totalCommission:o?g:0,totalNetToAgent:o?v:0,topLeadSource:N,transactionsByMonth:A,leadSourceBreakdown:b}};return{yearStats:c(r),lifetimeStats:c(a),isLoading:n||i,showCommission:o}},vUt=()=>{const{isAdmin:s}=As();return gt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:r}=await H.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 H.from("profiles").select("id, name, email").in("id",n);if(i)throw i;return a},enabled:s})},ej={recency:40,touchpoints:30,transactions:20},UFe={warm:70,cooling:40};function bUt(s){return s===null?0:s<=14?ej.recency:s<=30?ej.recency*.85:s<=60?ej.recency*.65:s<=90?ej.recency*.4:s<=180?ej.recency*.2:ej.recency*.05}function _Ut(s){const t=Math.min(s/12,1);return Math.round(ej.touchpoints*t)}function wUt(s){return s?ej.transactions:0}function jUt(){return 0}function NUt(s){return s>=UFe.warm?"warm":s>=UFe.cooling?"cooling":"at-risk"}function nxe(){const{data:s,isLoading:t}=$m(),{data:r}=Hnt(),{data:n}=sz(365),{data:a}=P5e(),i=k.useMemo(()=>{if(!s)return[];const o=new Date,c=q4(o,12),d={};n==null||n.forEach(m=>{new Date(m.completed_at)>=c&&(d[m.contact_id]=(d[m.contact_id]||0)+1)});const h=new Set((a==null?void 0:a.filter(m=>m.contact_id).map(m=>m.contact_id))||[]);return s.map(m=>{const x=(r==null?void 0:r[m.id])||null,g=x?Kg(o,new Date(x)):null,v=d[m.id]||0,j=h.has(m.id),b=bUt(g),N=_Ut(v),S=wUt(j),T=jUt(),A=Math.round(b+N+S+T),P={score:A,status:NUt(A),breakdown:{recency:Math.round(b),touchpoints:Math.round(N),transactions:Math.round(S),referrals:Math.round(T)},lastTouchDate:x,daysSinceTouch:g,touchCountLast12Months:v,hasTransaction:j};return{...m,relationshipScore:P}})},[s,r,n,a]),l=k.useMemo(()=>{const o=i.filter(x=>x.relationshipScore.status==="warm").length,c=i.filter(x=>x.relationshipScore.status==="cooling").length,d=i.filter(x=>x.relationshipScore.status==="at-risk").length,h=i.length,m=h>0?Math.round(i.reduce((x,g)=>x+g.relationshipScore.score,0)/h):0;return{warm:o,cooling:c,atRisk:d,total:h,averageScore:m}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function cat(){const s=vr(),{stats:t,contactsWithScores:r,isLoading:n}=nxe();if(n)return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Vs,{className:"h-5 w-40"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Vs,{className:"h-20 w-full"}),e.jsx(Vs,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(G,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=r.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(_o,{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(De,{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(ri,{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(ri,{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(ri,{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(a_,{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(ya,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(ya,{className:"h-4 w-4 ml-1"})]})]})]})}const kUt=()=>{var de;const{user:s,isAdmin:t}=As(),r=vr(),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState([]),[d,h]=k.useState([]),[m,x]=k.useState([]),[g,v]=k.useState([]),[j,b]=k.useState(new Set),[N,S]=k.useState([]),[T,A]=k.useState([]),[P,D]=k.useState([]),[B,z]=k.useState(null),[F,$]=k.useState(!0);k.useEffect(()=>{X()},[s]);const X=async()=>{var ce,ae,ie,me,oe;try{const[ge,be,Oe,Me,Pe,Ee,$e,Se,ze,Te,ye]=await Promise.all([H.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),H.from("app_tiles").select("*").order("name"),H.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),H.from("events").select("*").order("event_date",{ascending:!0}),H.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),H.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),H.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),H.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),H.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),H.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),H.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ce=ye.data)!=null&&ce.name&&z(ye.data.name);const ct=((ae=ge.data)==null?void 0:ae.map(Ce=>Ce.tag))||[],ve=new Set(((ie=Oe.data)==null?void 0:ie.map(Ce=>Ce.app_id))||[]);b(ve);const Re=(((me=be.data)==null?void 0:me.filter(Ce=>!Ce.required_tags||Ce.required_tags.length===0?!0:Ce.required_tags.some(nt=>ct.includes(nt))))||[]).sort((Ce,nt)=>Ce.name==="LevelUp Members Portal"?-1:nt.name==="LevelUp Members Portal"?1:0);a(Re.slice(0,6));const Qe=((oe=Me.data)==null?void 0:oe.filter(Ce=>SM(Ce.event_date)!=="ended"))||[];l(Qe.slice(0,4)),S(Pe.data||[]),c(Ee.data||[]),h($e.data||[]),x(Se.data||[]),v(ze.data||[]);const Ke=Te.data||[];A(Ke.filter(Ce=>Ce.placement==="top")),D(Ke.filter(Ce=>Ce.placement==="between"))}catch(ge){console.error("Error loading dashboard:",ge),ue.error("Failed to load dashboard data")}finally{$(!1)}},K=async ce=>{var ie;const ae=window.open("about:blank","_blank");try{await H.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ce.app_id,app_name:ce.name,user_agent:navigator.userAgent});const{data:me,error:oe}=await H.functions.invoke("sso-launch",{body:{app_id:ce.app_id}});if(oe)throw oe;me!=null&&me.redirect_url?ae&&!ae.closed?(ae.location.href=me.redirect_url,(ie=ae.focus)==null||ie.call(ae)):window.location.assign(me.redirect_url):(ae==null||ae.close(),ue.error("Launch link unavailable"))}catch(me){ae==null||ae.close(),console.error("Error launching app:",me),ue.error("Failed to launch app")}},Q=ce=>N==null?void 0:N.some(ae=>ae.event_id===ce),Y=ce=>{const ae=N==null?void 0:N.find(ie=>ie.event_id===ce);return ae==null?void 0:ae.zoom_join_url};if(F)return e.jsx(_s,{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 ne=ce=>P.filter(ae=>ae.section_after===ce);return e.jsxs(_s,{title:"Dashboard",children:[e.jsx(m$t,{events:i,registrations:N,onNavigateToEvents:()=>r("/events")}),T.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(HD,{banners:T})}),e.jsx(g$t,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(B||((de=s==null?void 0:s.user_metadata)==null?void 0:de.name)||"there").split(" ")[0],"!"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-8",children:[e.jsx(I$t,{}),e.jsx(cat,{}),e.jsx(hUt,{})]}),e.jsx(G$t,{}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Upcoming Events"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(rn,{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(ce=>{const ae=Q(ce.id),ie=Y(ce.id)||ce.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 ${zFe(ce.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>r("/events"),children:[zFe(ce.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(r_,{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(ce.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(ce.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:ce.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(ce.event_date))," at ",lF(new Date(ce.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:ae?e.jsxs(G,{size:"sm",variant:"default",className:"gap-1",onClick:me=>{me.stopPropagation(),window.open(ie,"_blank")},children:[e.jsx(Yr,{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(ya,{className:"h-4 w-4"})]})})]},ce.id)})})]}),ne("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(HD,{banners:ne("events")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Academy Videos"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),m.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(mf,{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(ce=>e.jsxs("div",{onClick:()=>r(`/academy/${ce.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:[ce.thumbnail_url?e.jsx("img",{src:ce.thumbnail_url,alt:ce.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(mf,{className:"h-8 w-8 text-muted-foreground/50"})}),ce.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:ce.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:ce.title})})]},ce.id))})]}),ne("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(HD,{banners:ne("academy")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Resource Kits"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(im,{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(ce=>e.jsxs("div",{onClick:()=>r(`/toolbox/${ce.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:ce.featured_image_url?e.jsx("img",{src:ce.featured_image_url,alt:ce.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(im,{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:ce.name})})]},ce.id))})]}),ne("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(HD,{banners:ne("toolbox")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"New Templates"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Qb,{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(ce=>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:ce.preview_image_url?e.jsx("img",{src:ce.preview_image_url,alt:ce.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(Qb,{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:ce.name})})]},ce.id))})]}),ne("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(HD,{banners:ne("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(uUt,{})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),n.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Bg,{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(ce=>{const ae=j.has(ce.id);return e.jsxs("div",{onClick:()=>K(ce),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:ce.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:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ce.description})]}),ae&&e.jsx(Bg,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ce.id)})})]}),e.jsxs("section",{className:"mt-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Additional Services"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ga,{className:"h-4 w-4"})]})]}),g.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(jr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:g.map(ce=>e.jsxs("div",{onClick:()=>window.open(ce.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:ce.preview_image_url?e.jsx("img",{src:ce.preview_image_url,alt:ce.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(jr,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ce.name}),ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ce.description})]})]},ce.id))})]})]})};var dat="AlertDialog",[SUt]=yd(dat,[SJe]),P_=SJe(),uat=s=>{const{__scopeAlertDialog:t,...r}=s,n=P_(t);return e.jsx(xpe,{...n,...r,modal:!0})};uat.displayName=dat;var CUt="AlertDialogTrigger",hat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=P_(r);return e.jsx(e3e,{...a,...n,ref:t})});hat.displayName=CUt;var TUt="AlertDialogPortal",mat=s=>{const{__scopeAlertDialog:t,...r}=s,n=P_(t);return e.jsx(gpe,{...n,...r})};mat.displayName=TUt;var EUt="AlertDialogOverlay",fat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=P_(r);return e.jsx(SP,{...a,...n,ref:t})});fat.displayName=EUt;var CM="AlertDialogContent",[AUt,MUt]=SUt(CM),IUt=VYe("AlertDialogContent"),pat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,children:n,...a}=s,i=P_(r),l=k.useRef(null),o=Qa(t,l),c=k.useRef(null);return e.jsx(AAt,{contentName:CM,titleName:xat,docsSlug:"alert-dialog",children:e.jsx(AUt,{scope:r,cancelRef:c,children:e.jsxs(CP,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:Or(a.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=c.current)==null||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(IUt,{children:n}),e.jsx(LUt,{contentRef:l})]})})})});pat.displayName=CM;var xat="AlertDialogTitle",gat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=P_(r);return e.jsx(UB,{...a,...n,ref:t})});gat.displayName=xat;var yat="AlertDialogDescription",vat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=P_(r);return e.jsx(qB,{...a,...n,ref:t})});vat.displayName=yat;var PUt="AlertDialogAction",bat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=P_(r);return e.jsx(VB,{...a,...n,ref:t})});bat.displayName=PUt;var _at="AlertDialogCancel",wat=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,{cancelRef:a}=MUt(_at,r),i=P_(r),l=Qa(t,a);return e.jsx(VB,{...i,...n,ref:l})});wat.displayName=_at;var LUt=({contentRef:s})=>{const t=`\`${CM}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${CM}\` by passing a \`${yat}\` 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 \`${CM}\`. 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},DUt=uat,RUt=hat,OUt=mat,jat=fat,Nat=pat,kat=bat,Sat=wat,Cat=gat,Tat=vat;const Yo=DUt,Lm=RUt,FUt=OUt,Eat=k.forwardRef(({className:s,...t},r)=>e.jsx(jat,{className:Bt("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}));Eat.displayName=jat.displayName;const Fo=k.forwardRef(({className:s,...t},r)=>e.jsxs(FUt,{children:[e.jsx(Eat,{}),e.jsx(Nat,{ref:r,className:Bt("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})]}));Fo.displayName=Nat.displayName;const Bo=({className:s,...t})=>e.jsx("div",{className:Bt("flex flex-col space-y-2 text-center sm:text-left",s),...t});Bo.displayName="AlertDialogHeader";const zo=({className:s,...t})=>e.jsx("div",{className:Bt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});zo.displayName="AlertDialogFooter";const $o=k.forwardRef(({className:s,...t},r)=>e.jsx(Cat,{ref:r,className:Bt("text-lg font-semibold",s),...t}));$o.displayName=Cat.displayName;const Uo=k.forwardRef(({className:s,...t},r)=>e.jsx(Tat,{ref:r,className:Bt("text-sm text-muted-foreground",s),...t}));Uo.displayName=Tat.displayName;const Eo=k.forwardRef(({className:s,...t},r)=>e.jsx(kat,{ref:r,className:Bt(uI(),s),...t}));Eo.displayName=kat.displayName;const qo=k.forwardRef(({className:s,...t},r)=>e.jsx(Sat,{ref:r,className:Bt(uI({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));qo.displayName=Sat.displayName;const BUt=[{key:"contacts",label:"Contacts",icon:Nn,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:A3,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:im,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:sn,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Cn,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Vj,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ja,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:gx,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Th,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:n0,description:"Create and manage smart presentations"}];function zUt(){var B;const{user:s}=As(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState({email:"",name:"",password:""}),[g,v]=k.useState("create"),[j,b]=k.useState(!1),[N,S]=k.useState(null);k.useEffect(()=>{s&&T()},[s]);const T=async()=>{if(s){a(!0);try{const{data:z,error:F}=await H.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(F)throw F;if(z&&z.length>0){const $=z.map(Q=>Q.assistant_id),{data:X}=await H.from("profiles").select("id, name, email").in("id",$),K=z.map(Q=>{const Y=X==null?void 0:X.find(ne=>ne.id===Q.assistant_id);return{...Q,permissions:Q.permissions,assistant_profile:Y?{name:Y.name||"",email:Y.email||""}:void 0}});r(K)}else r([])}catch(z){console.error("Error loading assistants:",z)}finally{a(!1)}}},A=async()=>{if(s){if(g==="link"){if(!m.email.trim()){ue.error("Please enter the assistant's email");return}b(!0);try{const{data:{session:z}}=await H.auth.getSession();if(!z)throw new Error("Not authenticated");const{data:F,error:$}=await H.from("profiles").select("id, name, email").eq("email",m.email.trim().toLowerCase()).single();if($||!F){ue.error("No account found with that email. Try creating a new assistant instead.");return}const{data:X}=await H.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",F.id);if(X&&X.length>0){ue.error("This assistant is already assigned to you");return}const K=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:F.id,role:"assistant",action:"add",agentId:s.id})}),Q=await K.json();if(!K.ok)throw new Error(Q.error||"Failed to assign assistant role");const{error:Y}=await H.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:F.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(Y)throw Y;ue.success(`${F.name||F.email} linked as your assistant`),l(!1),x({email:"",name:"",password:""}),T()}catch(z){console.error("Error linking assistant:",z),ue.error(z.message||"Failed to link assistant")}finally{b(!1)}return}if(!m.email.trim()||!m.name.trim()||!m.password.trim()){ue.error("Please fill in all fields");return}if(m.password.length<6){ue.error("Password must be at least 6 characters");return}b(!0);try{const{data:{session:z}}=await H.auth.getSession();if(!z)throw new Error("Not authenticated");const F=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({email:m.email.trim(),password:m.password,name:m.name.trim(),purpose:"assistant"})}),$=await F.json();if(!F.ok)throw new Error($.error||"Failed to create assistant account");const X=$.userId||$.id;if(!X)throw new Error("No user ID returned");const K=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:X,role:"assistant",action:"add",agentId:s.id})}),Q=await K.json();if(!K.ok)throw new Error(Q.error||"Failed to assign assistant role");const{error:Y}=await H.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:X,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(Y)throw Y;ue.success(`Assistant account created for ${m.name.trim()}`),l(!1),x({email:"",name:"",password:""}),T()}catch(z){console.error("Error adding assistant:",z),ue.error(z.message||"Failed to add assistant")}finally{b(!1)}}},P=async()=>{if(!(!d||!s))try{const{data:{session:z}}=await H.auth.getSession();if(!z)throw new Error("Not authenticated");const{error:F}=await H.from("agent_assistant_assignments").delete().eq("id",d.id);if(F)throw F;const{data:$}=await H.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!$||$.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ue.success("Assistant removed"),c(!1),h(null),T()}catch(z){console.error("Error removing assistant:",z),ue.error(z.message||"Failed to remove assistant")}},D=async(z,F,$)=>{S(z);try{const X=t.find(Y=>Y.id===z);if(!X)return;const K={...X.permissions,[F]:$},{error:Q}=await H.from("agent_assistant_assignments").update({permissions:K}).eq("id",z);if(Q)throw Q;r(Y=>Y.map(ne=>ne.id===z?{...ne,permissions:K}:ne))}catch(X){console.error("Error updating permissions:",X),ue.error("Failed to update permissions")}finally{S(null)}};return n?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(De,{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(Ne,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Nr,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(G,{size:"sm",onClick:()=>{v("create"),l(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(De,{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(z=>{var F,$,X,K;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vn,{className:"h-10 w-10",children:e.jsx(bn,{children:(($=(F=z.assistant_profile)==null?void 0:F.name)==null?void 0:$.split(" ").map(Q=>Q[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((X=z.assistant_profile)==null?void 0:X.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((K=z.assistant_profile)==null?void 0:K.email)||""})]}),e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[e.jsx(Zu,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{h(z),c(!0)},children:e.jsx(yr,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Permissions"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:BUt.map(Q=>{const Y=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(Y,{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(br,{checked:z.permissions[Q.key]||!1,onCheckedChange:ne=>D(z.id,Q.key,ne),disabled:N===z.id})]},Q.key)})})]})]},z.id)})})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add Assistant"}),e.jsx(Fr,{children:g==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(G,{variant:g==="create"?"default":"outline",size:"sm",onClick:()=>v("create"),children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(G,{variant:g==="link"?"default":"outline",size:"sm",onClick:()=>v("link"),children:[e.jsx(xo,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[g==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-name",children:"Name"}),e.jsx(ke,{id:"assistant-name",value:m.name,onChange:z=>x({...m,name:z.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-email",children:"Email"}),e.jsx(ke,{id:"assistant-email",type:"email",value:m.email,onChange:z=>x({...m,email:z.target.value}),placeholder:"assistant@email.com"})]}),g==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(ke,{id:"assistant-password",type:"password",value:m.password,onChange:z=>x({...m,password:z.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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(G,{onClick:A,disabled:j,children:[j&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),g==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Yo,{open:o,onOpenChange:c,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Remove Assistant?"}),e.jsxs(Uo,{children:["This will remove ",(B=d==null?void 0:d.assistant_profile)==null?void 0:B.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:P,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Wh(s){this.content=s}Wh.prototype={constructor:Wh,find:function(s){for(var t=0;t>1}};Wh.from=function(s){if(s instanceof Wh)return s;var t=[];if(s)for(var r in s)t.push(r,s[r]);return new Wh(t)};function Aat(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){let l=a.text,o=i.text,c=0;for(;l[c]==o[c];c++)r++;return c&&c0&&x>0&&d[m-1]==h[x-1];)m--,x--,r--,n--;return m&&x&&m=56320&&s<57344}function Pat(s){return s>=55296&&s<56320}let an=class of{constructor(t,r){if(this.content=t,this.size=r||0,r==null)for(let n=0;nt&&n(c,a+o,i||null,l)!==!1&&c.content.size){let h=o+1;c.nodesBetween(Math.max(0,t-h),Math.min(c.content.size,r-h),n,a+h)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,r,n,a){let i="",l=!0;return this.nodesBetween(t,r,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,r-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&n&&(l?l=!1:i+=n),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let r=this.lastChild,n=t.firstChild,a=this.content.slice(),i=0;for(r.isText&&r.sameMarkup(n)&&(a[a.length-1]=r.withText(r.text+n.text),i=1);it)for(let i=0,l=0;lt&&((lr)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,r-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,r-l-1))),n.push(o),a+=o.nodeSize),l=c}return new of(n,a)}cutByIndex(t,r){return t==r?of.empty:t==0&&r==this.content.length?this:new of(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 of(a,i)}addToStart(t){return new of([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new of(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?iU(r+1,i):iU(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 of.empty;if(!Array.isArray(r))throw new RangeError("Invalid input for Fragment.fromJSON");return of.fromArray(r.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return of.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}};Zl.none=[];class rhe extends Error{}class Un{constructor(t,r,n){this.content=t,this.openStart=r,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,r){let n=Dat(this.content,t+this.openStart,r,this.openStart+1,this.openEnd+1);return n&&new Un(n,this.openStart,this.openEnd)}removeBetween(t,r){return new Un(Lat(this.content,t+this.openStart,r+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,r){if(!r)return Un.empty;let n=r.openStart||0,a=r.openEnd||0;if(typeof n!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Un(an.fromJSON(t,r.content),n,a)}static maxOpen(t,r=!0){let n=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.lastChild)a++;return new Un(t,n,a)}}Un.empty=new Un(an.empty,0,0);function Lat(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(Lat(i.content,t-a-1,r-a-1)))}function Dat(s,t,r,n,a,i){let{index:l,offset:o}=s.findIndex(t),c=s.maybeChild(l);if(o==t||c.isText)return i&&n<=0&&a<=0&&!i.canReplace(l,l,r)?null:s.cut(0,t).append(r).append(s.cut(t));let d=Dat(c.content,t-o-1,r,l==0?n-1:0,l==s.childCount-1?a-1:0,c);return d&&s.replaceChild(l,c.copy(d))}function $Ut(s,t,r){if(r.openStart>s.depth)throw new rhe("Inserted content deeper than insertion position");if(s.depth-r.openStart!=t.depth-r.openEnd)throw new rhe("Inconsistent open depths");return Rat(s,t,r,0)}function Rat(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 e8(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&&(Z3(s.nodeAfter,n),i++));for(let o=i;oa&&eNe(s,t,a+1),l=n.depth>a&&eNe(r,n,a+1),o=[];return e8(null,s,a,o),i&&l&&t.index(a)==r.index(a)?(Oat(i,l),Z3(X3(i,Fat(s,t,r,n,a+1)),o)):(i&&Z3(X3(i,nhe(s,t,a+1)),o),e8(t,r,a,o),l&&Z3(X3(l,nhe(r,n,a+1)),o)),e8(n,null,a,o),new an(o)}function nhe(s,t,r){let n=[];if(e8(null,s,r,n),s.depth>r){let a=eNe(s,t,r+1);Z3(X3(a,nhe(s,t,r+1)),n)}return e8(t,null,r,n),new an(n)}function UUt(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(an.from(a));return{start:a.resolveNoCache(s.openStart+r),end:a.resolveNoCache(a.content.size-s.openEnd-r)}}class cF{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 ahe(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 cF(r,n,i)}static resolveCached(t,r){let n=qFe.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()+")"),Bat(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=an.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=an.fromJSON(t,r.content),i=t.nodeType(r.type).create(r.attrs,a,n);return i.type.checkAttrs(i.attrs),i}};l2.prototype.text=void 0;class ihe extends l2{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):Bat(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 ihe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new ihe(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 Bat(s,t){for(let r=s.length-1;r>=0;r--)t=s[r].type.name+"("+t+")";return t}class w5{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,r){let n=new GUt(t,r);if(n.next==null)return w5.empty;let a=zat(n);n.next&&n.err("Unexpected trailing text");let i=JUt(QUt(a));return eqt(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(` `)}}w5.empty=new w5(!0);class GUt{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 zat(s){let t=[];do t.push(WUt(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function WUt(s){let t=[];do t.push(KUt(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function KUt(s){let t=XUt(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=YUt(s,t);else break;return t}function VFe(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function YUt(s,t){let r=VFe(s),n=r;return s.eat(",")&&(s.next!="}"?n=VFe(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:r,max:n,expr:t}}function ZUt(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 XUt(s){if(s.eat("(")){let t=zat(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=ZUt(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 QUt(s){let t=[[]];return a(i(s,0),r()),t;function r(){return t.push([])-1}function n(l,o,c){let d={term:c,to:o};return t[l].push(d),d}function a(l,o){l.forEach(c=>c.to=o)}function i(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(i(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=i(l.exprs[c],o);if(c==l.exprs.length-1)return d;a(d,o=r())}else if(l.type=="star"){let c=r();return n(o,c),a(i(l.expr,c),c),[n(c)]}else if(l.type=="plus"){let c=r();return a(i(l.expr,o),c),a(i(l.expr,c),c),[n(c)]}else{if(l.type=="opt")return[n(o)].concat(i(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{s[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let h=0;h{d||a.push([o,d=[]]),d.indexOf(h)==-1&&d.push(h)})})});let i=t[n.join(",")]=new w5(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:qat(this.attrs,t)}create(t=null,r,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new l2(this,this.computeAttrs(t),an.from(r),Zl.setFrom(n))}createChecked(t=null,r,n){return r=an.from(r),this.checkContent(r),new l2(this,this.computeAttrs(t),r,Zl.setFrom(n))}createAndFill(t=null,r,n){if(t=this.computeAttrs(t),r=an.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(an.empty,!0);return i?new l2(this,t,r.append(i),Zl.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 Gat(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 tqt(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 sqt{constructor(t,r,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?tqt(t,r,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class axe{constructor(t,r,n,a){this.name=t,this.rank=r,this.schema=n,this.spec=a,this.attrs=Hat(t,a.attrs),this.excluded=null;let i=Uat(this.attrs);this.instance=i?new Zl(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Zl(this,qat(this.attrs,t))}static compile(t,r){let n=Object.create(null),a=0;return t.forEach((i,l)=>n[i]=new axe(i,a++,r,l)),n}removeFromSet(t){for(var r=0;r-1}}class Wat{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=Wh.from(t.nodes),r.marks=Wh.from(t.marks||{}),this.nodes=GFe.compile(this.spec.nodes,this),this.marks=axe.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]=w5.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?WFe(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==""?[]:WFe(this,l.split(" "))}this.nodeFromJSON=a=>l2.fromJSON(this,a),this.markFromJSON=a=>Zl.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 GFe){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 ihe(n,n.defaultAttrs,t,Zl.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 WFe(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 rqt(s){return s.tag!=null}function nqt(s){return s.style!=null}let t8=class sNe{constructor(t,r){this.schema=t,this.rules=r,this.tags=[],this.styles=[];let n=this.matchedStyles=[];r.forEach(a=>{if(rqt(a))this.tags.push(a);else if(nqt(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 YFe(this,r,!1);return n.addAll(t,Zl.none,r.from,r.to),n.finish()}parseSlice(t,r={}){let n=new YFe(this,r,!0);return n.addAll(t,Zl.none,r.from,r.to),Un.maxOpen(n.finish())}matchTag(t,r,n){for(let a=n?this.tags.indexOf(n)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=r))){if(l.getAttrs){let c=l.getAttrs(r);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let r=[];function n(a){let i=a.priority==null?50:a.priority,l=0;for(;l{n(l=ZFe(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=ZFe(l)),l.node||l.ignore||l.mark||(l.node=a)})}return r}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new sNe(t,sNe.schemaRules(t)))}};const Kat={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},aqt={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Yat={ol:!0,ul:!0},dF=1,rNe=2,s8=4;function KFe(s,t,r){return t!=null?(t?dF:0)|(t==="full"?rNe:0):s&&s.whitespace=="pre"?dF|rNe:r&~s8}class oU{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=Zl.none,this.match=i||(l&s8?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let r=this.type.contentMatch.fillBefore(an.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&dF)){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=an.from(this.content);return!t&&this.match&&(r=r.append(this.match.fillBefore(an.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&&!Kat.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class YFe{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=KFe(null,r.preserveWhitespace,0)|(n?s8:0);a?i=new oU(a.type,a.attrs,Zl.none,!0,r.topMatch||a.type.contentMatch,l):n?i=new oU(null,null,Zl.none,!0,null,l):i=new oU(t.schema.topNodeType,null,Zl.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&rNe?"full":this.localPreserveWS||(a.options&dF)>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):XFe(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new oU(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|=dF)}return!1}get currentPos(){this.closeExtra();let t=0;for(let r=this.open;r>=0;r--){let n=this.nodes[r].content;for(let a=n.length-1;a>=0;a--)t+=n[a].nodeSize;r&&t++}return t}findAtPoint(t,r){if(this.find)for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let r=t.split("/"),n=this.options.context,a=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=r[o];if(d==""){if(o==r.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let h=c>0||c==0&&a?this.nodes[c].type:n&&c>=i?n.node(c-i).type:null;if(!h||h.name!=d&&!h.isInGroup(d))return!1;c--}}return!0};return l(r.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let r=t.depth;r>=0;r--){let n=t.node(r).contentMatchAt(t.indexAfter(r)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let r in this.parser.schema.nodes){let n=this.parser.schema.nodes[r];if(n.isTextblock&&n.defaultAttrs)return n}}}function iqt(s){for(let t=s.firstChild,r=null;t;t=t.nextSibling){let n=t.nodeType==1?t.nodeName.toLowerCase():null;n&&Yat.hasOwnProperty(n)&&r?(r.appendChild(t),t=r):n=="li"?r=t:n&&(r=null)}}function oqt(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function ZFe(s){let t={};for(let r in s)t[r]=s[r];return t}function XFe(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&&kde(lU(n),a(t,r),null,t.attrs)}static renderSpec(t,r,n=null,a){return typeof r=="string"?{dom:t.createTextNode(r)}:kde(t,r,n,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new Y5(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let r=QFe(t.nodes);return r.text||(r.text=n=>n.text),r}static marksFromSchema(t){return QFe(t.marks)}}function QFe(s){let t={};for(let r in s){let n=s[r].spec.toDOM;n&&(t[r]=n)}return t}function lU(s){return s.document||window.document}const JFe=new WeakMap;function lqt(s){let t=JFe.get(s);return t===void 0&&JFe.set(s,t=cqt(s)),t}function cqt(s){let t=null;function r(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")t||(t=[]),t.push(n);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(r=a.slice(0,l),a=a.slice(l+1));let o,c=r?s.createElementNS(r,a):s.createElement(a),d=t[1],h=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){h=2;for(let m in d)if(d[m]!=null){let x=m.indexOf(" ");x>0?c.setAttributeNS(m.slice(0,x),m.slice(x+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=h;mh)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof x=="string")c.appendChild(s.createTextNode(x));else{let{dom:g,contentDOM:v}=kde(s,x,r,n);if(c.appendChild(g),v){if(o)throw new RangeError("Multiple content holes");o=v}}}return{dom:c,contentDOM:o}}const Zat=65535,Xat=Math.pow(2,16);function dqt(s,t){return s+t*Xat}function eBe(s){return s&Zat}function uqt(s){return(s-(s&Zat))/Xat}const Qat=1,Jat=2,Sde=4,eit=8;class nNe{constructor(t,r,n){this.pos=t,this.delInfo=r,this.recover=n}get deleted(){return(this.delInfo&eit)>0}get deletedBefore(){return(this.delInfo&(Qat|Sde))>0}get deletedAfter(){return(this.delInfo&(Jat|Sde))>0}get deletedAcross(){return(this.delInfo&Sde)>0}}class dx{constructor(t,r=!1){if(this.ranges=t,this.inverted=r,!t.length&&dx.empty)return dx.empty}recover(t){let r=0,n=eBe(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],h=this.ranges[o+l],m=c+d;if(t<=m){let x=d?t==c?-1:t==m?1:r:r,g=c+a+(x<0?0:h);if(n)return g;let v=t==(r<0?c:m)?null:dqt(o/3,t-c),j=t==c?Jat:t==m?Qat:Sde;return(r<0?t!=c:t!=m)&&(j|=eit),new nNe(g,j,v)}a+=h-d}return n?t+a:new nNe(t+a,0,null)}touches(t,r){let n=0,a=eBe(r),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],h=c+d;if(t<=h&&o==a*3)return!0;n+=this.ranges[o+l]-d}return!1}forEach(t){let r=this.inverted?2:1,n=this.inverted?1:2;for(let a=0,i=0;a=0;r--){let a=t.getMirror(r);this.appendMap(t._maps[r].invert(),a!=null&&a>r?n-a-1:void 0)}}invert(){let t=new uF;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 ju.fromReplace(t,this.from,this.to,i)}invert(){return new Mv(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 Mj(r.pos,n.pos,this.mark)}merge(t){return t instanceof Mj&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Mj(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 Mj(r.from,r.to,t.markFromJSON(r.mark))}}Um.jsonID("addMark",Mj);class Mv extends Um{constructor(t,r,n){super(),this.from=t,this.to=r,this.mark=n}apply(t){let r=t.slice(this.from,this.to),n=new Un(L5e(r.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),r.openStart,r.openEnd);return ju.fromReplace(t,this.from,this.to,n)}invert(){return new Mj(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 Mv(r.pos,n.pos,this.mark)}merge(t){return t instanceof Mv&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Mv(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 Mv(r.from,r.to,t.markFromJSON(r.mark))}}Um.jsonID("removeMark",Mv);class Ij extends Um{constructor(t,r){super(),this.pos=t,this.mark=r}apply(t){let r=t.nodeAt(this.pos);if(!r)return ju.fail("No node at mark step's position");let n=r.type.create(r.attrs,null,this.mark.addToSet(r.marks));return ju.fromReplace(t,this.pos,this.pos+1,new Un(an.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 Ih(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 Ih(r.from,r.to,r.gapFrom,r.gapTo,Un.fromJSON(t,r.slice),r.insert,!!r.structure)}}Um.jsonID("replaceAround",Ih);function aNe(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 hqt(s,t,r,n){let a=[],i=[],l,o;s.doc.nodesBetween(t,r,(c,d,h)=>{if(!c.isInline)return;let m=c.marks;if(!n.isInSet(m)&&h.type.allowsMarkType(n.type)){let x=Math.max(d,t),g=Math.min(d+c.nodeSize,r),v=n.addToSet(m);for(let j=0;js.step(c)),i.forEach(c=>s.step(c))}function mqt(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 axe){let d=l.marks,h;for(;h=n.isInSet(d);)(c||(c=[])).push(h),d=h.removeFromSet(d)}else n?n.isInSet(l.marks)&&(c=[n]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,r);for(let h=0;hs.step(new Mv(l.from,l.to,l.style)))}function D5e(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 fqt(s,t,r){return(t==0||s.canReplace(t,s.childCount))&&(r==s.childCount||s.canReplace(0,r))}function PP(s){let r=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let n=s.depth,a=0,i=0;;--n){let l=s.$from.node(n),o=s.$from.index(n)+a,c=s.$to.indexAfter(n)-i;if(nr;v--)j||n.index(v)>0?(j=!0,h=an.from(n.node(v).copy(h)),m++):c--;let x=an.empty,g=0;for(let v=i,j=!1;v>r;v--)j||a.after(v+1)=0;l--){if(n.size){let o=r[l].type.contentMatch.matchFragment(n);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=an.from(r[l].type.create(r[l].attrs,n))}let a=t.start,i=t.end;s.step(new Ih(a,i,a,i,new Un(n,0,0),r.length,!0))}function vqt(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)&&bqt(s.doc,s.mapping.slice(i).map(o),n)){let d=null;if(n.schema.linebreakReplacement){let g=n.whitespace=="pre",v=!!n.contentMatch.matchType(n.schema.linebreakReplacement);g&&!v?d=!1:!g&&v&&(d=!0)}d===!1&&sit(s,l,o,i),D5e(s,s.mapping.slice(i).map(o,1),n,void 0,d===null);let h=s.mapping.slice(i),m=h.map(o,1),x=h.map(o+l.nodeSize,1);return s.step(new Ih(m,x,m+1,x-1,new Un(an.from(n.create(c,null,l.marks)),0,0),1,!0)),d===!0&&tit(s,l,o,i),!1}})}function tit(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 sit(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 bqt(s,t,r){let n=s.resolve(t),a=n.index();return n.parent.canReplaceWith(a,a+1,r)}function _qt(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 Ih(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Un(an.from(l),0,0),1,!0))}function i_(s,t,r=1,n){let a=s.resolve(t),i=a.depth-r,l=n&&n[n.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,h=r-2;d>i;d--,h--){let m=a.node(d),x=a.index(d);if(m.type.spec.isolating)return!1;let g=m.content.cutByIndex(x,m.childCount),v=n&&n[h+1];v&&(g=g.replaceChild(0,v.type.create(v.attrs)));let j=n&&n[h]||m;if(!m.canReplace(x+1,m.childCount)||!j.type.validContent(g))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 wqt(s,t,r=1,n){let a=s.doc.resolve(t),i=an.empty,l=an.empty;for(let o=a.depth,c=a.depth-r,d=r-1;o>c;o--,d--){i=an.from(a.node(o).copy(i));let h=n&&n[d];l=an.from(h?h.type.create(h.attrs,l):a.node(o).copy(l))}s.step(new bu(t,t,new Un(i.append(l),r,r),!0))}function Z2(s,t){let r=s.resolve(t),n=r.index();return rit(r.nodeBefore,r.nodeAfter)&&r.parent.canReplace(n,n+1)}function jqt(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&&rit(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 Nqt(s,t,r){let n=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-r),l=i.node().type;if(a&&l.inlineContent){let h=l.whitespace=="pre",m=!!l.contentMatch.matchType(a);h&&!m?n=!1:!h&&m&&(n=!0)}let o=s.steps.length;if(n===!1){let h=s.doc.resolve(t+r);sit(s,h.node(),h.before(),o)}l.inlineContent&&D5e(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 bu(d,c.map(t+r,-1),Un.empty,!0)),n===!0){let h=s.doc.resolve(d);tit(s,h.node(),h.before(),s.steps.length)}return s}function kqt(s,t,r){let n=s.resolve(t);if(n.parent.canReplaceWith(n.index(),n.index(),r))return t;if(n.parentOffset==0)for(let a=n.depth-1;a>=0;a--){let i=n.index(a);if(n.node(a).canReplaceWith(i,i,r))return n.before(a+1);if(i>0)return null}if(n.parentOffset==n.parent.content.size)for(let a=n.depth-1;a>=0;a--){let i=n.indexAfter(a);if(n.node(a).canReplaceWith(i,i,r))return n.after(a+1);if(i=0;l--){let o=l==n.depth?0:n.pos<=(n.start(l+1)+n.end(l+1))/2?-1:1,c=n.index(l)+(o>0?1:0),d=n.node(l),h=!1;if(i==1)h=d.canReplace(c,c,a);else{let m=d.contentMatchAt(c).findWrapping(a.firstChild.type);h=m&&d.canReplaceWith(c,c,m[0])}if(h)return o==0?n.pos:o<0?n.before(l+1):n.after(l+1)}return null}function oxe(s,t,r=t,n=Un.empty){if(t==r&&!n.size)return null;let a=s.resolve(t),i=s.resolve(r);return ait(a,i,n)?new bu(t,r,n):new Sqt(a,i,n).fit()}function ait(s,t,r){return!r.openStart&&!r.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),r.content)}class Sqt{constructor(t,r,n){this.$from=t,this.$to=r,this.unplaced=n,this.frontier=[],this.placed=an.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=an.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),r=this.placed.size-this.depth-this.$from.depth,n=this.$from,a=this.close(t<0?this.$to:n.doc.resolve(t));if(!a)return null;let i=this.placed,l=n.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new Un(i,l,o);return t>-1?new Ih(n.pos,t,this.$to.pos,this.$to.end(),c,r):c.size||n.pos!=this.$to.pos?new bu(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=Q1e(this.unplaced.content,n-1).firstChild,a=i.content):a=this.unplaced.content;let l=a.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],h,m=null;if(r==1&&(l?d.matchType(l.type)||(m=d.fillBefore(an.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:o,parent:i,inject:m};if(r==2&&l&&(h=d.findWrapping(l.type)))return{sliceDepth:n,frontierDepth:o,parent:i,wrap:h};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Q1e(t,r);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Un(t,r+1,Math.max(n,a.size+r>=t.size-n?r+1:0)),!0)}dropNode(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Q1e(t,r);if(a.childCount<=1&&r>0){let i=t.size-r<=r+a.size;this.unplaced=new Un(jR(t,r-1,1),r-1,i?r-1:n)}else this.unplaced=new Un(jR(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 j=0;j1||c==0||j.content.size)&&(m=b,h.push(iit(j.mark(x.allowedMarks(j.marks)),d==1?c:0,d==o.childCount?g:-1)))}let v=d==o.childCount;v||(g=-1),this.placed=NR(this.placed,r,an.from(h)),this.frontier[r].match=m,v&&g<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let j=0,b=o;j1&&a==this.$to.end(--n);)++a;return a}findCloseLevel(t){e:for(let r=Math.min(this.depth,t.depth);r>=0;r--){let{match:n,type:a}=this.frontier[r],i=r=0;o--){let{match:c,type:d}=this.frontier[o],h=J1e(t,o,d,c,!0);if(!h||h.childCount)continue e}return{depth:r,fit:l,move:i?t.doc.resolve(t.after(r+1)):t}}}}close(t){let r=this.findCloseLevel(t);if(!r)return null;for(;this.depth>r.depth;)this.closeFrontierNode();r.fit.childCount&&(this.placed=NR(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=NR(this.placed,this.depth,an.from(t.create(r,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let r=this.frontier.pop().match.fillBefore(an.empty,!0);r.childCount&&(this.placed=NR(this.placed,this.frontier.length,r))}}function jR(s,t,r){return t==0?s.cutByIndex(r,s.childCount):s.replaceChild(0,s.firstChild.copy(jR(s.firstChild.content,t-1,r)))}function NR(s,t,r){return t==0?s.append(r):s.replaceChild(s.childCount-1,s.lastChild.copy(NR(s.lastChild.content,t-1,r)))}function Q1e(s,t){for(let r=0;r1&&(n=n.replaceChild(0,iit(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(an.empty,!0)))),s.copy(n)}function J1e(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&&!Cqt(r,i.content,l)?o:null}function Cqt(s,t,r){for(let n=r;n0;x--,g--){let v=a.node(x).type.spec;if(v.defining||v.definingAsContext||v.isolating)break;l.indexOf(x)>-1?o=x:a.before(x)==g&&l.splice(1,0,-x)}let c=l.indexOf(o),d=[],h=n.openStart;for(let x=n.content,g=0;;g++){let v=x.firstChild;if(d.push(v),g==n.openStart)break;x=v.content}for(let x=h-1;x>=0;x--){let g=d[x],v=Tqt(g.type);if(v&&!g.sameMarkup(a.node(Math.abs(o)-1)))h=x;else if(v||!g.type.isTextblock)break}for(let x=n.openStart;x>=0;x--){let g=(x+h+1)%(n.openStart+1),v=d[g];if(v)for(let j=0;j=0&&(s.replace(t,r,n),!(s.steps.length>m));x--){let g=l[x];g<0||(t=a.before(g),r=i.after(g))}}function oit(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(an.empty,!0))}return s}function Aqt(s,t,r,n){if(!n.isInline&&t==r&&s.doc.resolve(t).parent.content.size){let a=kqt(s.doc,t,n.type);a!=null&&(t=r=a)}s.replaceRange(t,r,new Un(an.from(n),0,0))}function Mqt(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=lit(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 lit(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 TM extends Um{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 ju.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 ju.fromReplace(t,this.pos,this.pos+1,new Un(an.from(a),0,r.isLeaf?0:1))}getMap(){return dx.empty}invert(t){return new TM(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 TM(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 TM(r.pos,r.attr,r.value)}}Um.jsonID("attr",TM);class hF extends Um{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 ju.ok(n)}getMap(){return dx.empty}invert(t){return new hF(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 hF(r.attr,r.value)}}Um.jsonID("docAttr",hF);let _I=class extends Error{};_I=function s(t){let r=Error.call(this,t);return r.__proto__=s.prototype,r};_I.prototype=Object.create(Error.prototype);_I.prototype.constructor=_I;_I.prototype.name="TransformError";class O5e{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new uF}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let r=this.maybeStep(t);if(r.failed)throw new _I(r.failed);return this}maybeStep(t){let r=t.apply(this.doc);return r.failed||this.addStep(t,r.doc),r}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,r=-1e9;for(let n=0;n{t=Math.min(t,o),r=Math.max(r,c)})}return t==1e9?null:{from:t,to:r}}addStep(t,r){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=r}replace(t,r=t,n=Un.empty){let a=oxe(this.doc,t,r,n);return a&&this.step(a),this}replaceWith(t,r,n){return this.replace(t,r,new Un(an.from(n),0,0))}delete(t,r){return this.replace(t,r,Un.empty)}insert(t,r){return this.replaceWith(t,t,r)}replaceRange(t,r,n){return Eqt(this,t,r,n),this}replaceRangeWith(t,r,n){return Aqt(this,t,r,n),this}deleteRange(t,r){return Mqt(this,t,r),this}lift(t,r){return pqt(this,t,r),this}join(t,r=1){return Nqt(this,t,r),this}wrap(t,r){return yqt(this,t,r),this}setBlockType(t,r=t,n,a=null){return vqt(this,t,r,n,a),this}setNodeMarkup(t,r,n=null,a){return _qt(this,t,r,n,a),this}setNodeAttribute(t,r,n){return this.step(new TM(t,r,n)),this}setDocAttribute(t,r){return this.step(new hF(t,r)),this}addNodeMark(t,r){return this.step(new Ij(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 Zl)r.isInSet(n.marks)&&this.step(new j5(t,r));else{let a=n.marks,i,l=[];for(;i=r.isInSet(a);)l.push(new j5(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 wqt(this,t,r,n),this}addMark(t,r,n){return hqt(this,t,r,n),this}removeMark(t,r,n){return mqt(this,t,r,n),this}clearIncompatible(t,r,n){return D5e(this,t,r,n),this}}const ebe=Object.create(null);class vi{constructor(t,r,n){this.$anchor=t,this.$head=r,this.ranges=n||[new cit(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?uA(t.node(0),t.node(i),t.before(i+1),t.index(i),r,n):uA(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 jx(t.node(0))}static atStart(t){return uA(t,t,0,0,1)||new jx(t)}static atEnd(t){return uA(t,t,t.content.size,t.childCount,-1)||new jx(t)}static fromJSON(t,r){if(!r||!r.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=ebe[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 ebe)throw new RangeError("Duplicate use of selection JSON ID "+t);return ebe[t]=r,r.prototype.jsonID=t,r}getBookmark(){return Ya.between(this.$anchor,this.$head).getBookmark()}}vi.prototype.visible=!0;class cit{constructor(t,r){this.$from=t,this.$to=r}}let sBe=!1;function rBe(s){!sBe&&!s.parent.inlineContent&&(sBe=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Ya extends vi{constructor(t,r=t){rBe(t),rBe(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 vi.near(n);let a=t.resolve(r.map(this.anchor));return new Ya(a.parent.inlineContent?a:n,n)}replace(t,r=Un.empty){if(super.replace(t,r),r==Un.empty){let n=this.$from.marksAcross(this.$to);n&&t.ensureMarks(n)}}eq(t){return t instanceof Ya&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new lxe(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 Ya(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=vi.findFrom(r,n,!0)||vi.findFrom(r,-n,!0);if(i)r=i.$head;else return vi.near(r,n)}return t.parent.inlineContent||(a==0?t=r:(t=(vi.findFrom(t,-n,!0)||vi.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&&Za.isSelectable(o))return Za.create(s,r-(a<0?o.nodeSize:0))}else{let c=uA(s,o,r+a,a<0?o.childCount:0,a,i);if(c)return c}r+=o.nodeSize*a}return null}function nBe(s,t,r){let n=s.steps.length-1;if(n{l==null&&(l=h)}),s.setSelection(vi.near(s.doc.resolve(l),r))}const aBe=1,cU=2,iBe=4;class Pqt extends O5e{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|=cU,this}ensureMarks(t){return Zl.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&cU)>0}addStep(t,r){super.addStep(t,r),this.updated=this.updated&~cU,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)||Zl.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(vi.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|=iBe,this}get scrolledIntoView(){return(this.updated&iBe)>0}}function oBe(s,t){return!t||!s?s:s.bind(t)}class kR{constructor(t,r,n){this.name=t,this.init=oBe(r.init,n),this.apply=oBe(r.apply,n)}}const Lqt=[new kR("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new kR("selection",{init(s,t){return s.selection||vi.atStart(t.doc)},apply(s){return s.selection}}),new kR("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,r,n){return n.selection.$cursor?s.storedMarks:null}}),new kR("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class tbe{constructor(t,r){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Lqt.slice(),r&&r.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new kR(n.key,n.spec.state,n))})}}class PA{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 tbe(t.schema,t.plugins),i=new PA(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=l2.fromJSON(t.schema,r.doc);else if(l.name=="selection")i.selection=vi.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 dit(s,t,r){for(let n in s){let a=s[n];a instanceof Function?a=a.bind(t):n=="handleDOMEvents"&&(a=dit(a,t,{})),r[n]=a}return r}class sh{constructor(t){this.spec=t,this.props={},t.props&&dit(t.props,this,this.props),this.key=t.key?t.key.key:uit("plugin")}getState(t){return t[this.key]}}const sbe=Object.create(null);function uit(s){return s in sbe?s+"$"+ ++sbe[s]:(sbe[s]=0,s+"$")}class qm{constructor(t="key"){this.key=uit(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const Qh=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},wI=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let iNe=null;const kb=function(s,t,r){let n=iNe||(iNe=document.createRange());return n.setEnd(s,r??s.nodeValue.length),n.setStart(s,t||0),n},Dqt=function(){iNe=null},N5=function(s,t,r,n){return r&&(lBe(s,t,r,n,-1)||lBe(s,t,r,n,1))},Rqt=/^(img|br|input|textarea|hr)$/i;function lBe(s,t,r,n,a){for(var i;;){if(s==r&&t==n)return!0;if(t==(a<0?0:Mg(s))){let l=s.parentNode;if(!l||l.nodeType!=1||rz(s)||Rqt.test(s.nodeName)||s.contentEditable=="false")return!1;t=Qh(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?Mg(s):0}else return!1}}function Mg(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Oqt(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=Mg(s)}else if(s.parentNode&&!rz(s))t=Qh(s),s=s.parentNode;else return null}}function Fqt(s,t){for(;;){if(s.nodeType==3&&t2),kg=jI||(i1?/Mac/.test(i1.platform):!1),fit=i1?/Win/.test(i1.platform):!1,Hb=/Android \d/.test(X2),nz=!!cBe&&"webkitFontSmoothing"in cBe.documentElement.style,Uqt=nz?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function qqt(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 ub(s,t){return typeof s=="number"?s:s[t]}function Vqt(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 dBe(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=wI(l);continue}let o=l,c=o==i.body,d=c?qqt(i):Vqt(o),h=0,m=0;if(t.topd.bottom-ub(n,"bottom")&&(m=t.bottom-t.top>d.bottom-d.top?t.top+ub(a,"top")-d.top:t.bottom-d.bottom+ub(a,"bottom")),t.leftd.right-ub(n,"right")&&(h=t.right-d.right+ub(a,"right")),h||m)if(c)i.defaultView.scrollBy(h,m);else{let g=o.scrollLeft,v=o.scrollTop;m&&(o.scrollTop+=m),h&&(o.scrollLeft+=h);let j=o.scrollLeft-g,b=o.scrollTop-v;t={left:t.left-j,top:t.top-b,right:t.right-j,bottom:t.bottom-b}}let x=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(x))break;l=x=="absolute"?l.offsetParent:wI(l)}}function Hqt(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:pit(s.dom)}}function pit(s){let t=[],r=s.ownerDocument;for(let n=s;n&&(t.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=r);n=wI(n));return t}function Gqt({refDOM:s,refTop:t,stack:r}){let n=s?s.getBoundingClientRect().top:0;xit(r,n==0?0:n-t)}function xit(s,t){for(let r=0;r=o){l=Math.max(v.bottom,l),o=Math.min(v.top,o);let j=v.left>t.left?v.left-t.left:v.right=(v.left+v.right)/2?1:0));continue}}else v.top>t.top&&!c&&v.left<=t.left&&v.right>=t.left&&(c=h,d={left:Math.max(v.left,Math.min(v.right,t.left)),top:v.top});!r&&(t.left>=v.right&&t.top>=v.top||t.left>=v.left&&t.top>=v.bottom)&&(i=m+1)}}return!r&&c&&(r=c,a=d,n=0),r&&r.nodeType==3?Kqt(r,a):!r||n&&r.nodeType==1?{node:s,offset:i}:git(r,a)}function Kqt(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 B5e(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function Yqt(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 Xqt(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 yit(s,t,r){let n=s.childNodes.length;if(n&&r.topt.top&&a++}let d;nz&&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=Xqt(s,n,a,t))}o==null&&(o=Zqt(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function uBe(s){return s.top=0&&a==n.nodeValue.length?(c--,h=1):r<0?c--:d++,GD(Ww(kb(n,c,d),h),h<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(r<0||a==Mg(n))){let c=n.childNodes[a-1];if(c.nodeType==1)return rbe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(r<0||a==Mg(n))){let c=n.childNodes[a-1],d=c.nodeType==3?kb(c,Mg(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return GD(Ww(d,1),!1)}if(i==null&&a=0)}function GD(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 rbe(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 bit(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 eVt(s,t,r){let n=t.selection,a=r=="up"?n.$from:n.$to;return bit(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=vit(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=kb(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;dh.top+1&&(r=="up"?l.top-h.top>(h.bottom-l.top)*2:h.bottom-l.bottom>(l.bottom-h.top)*2))return!1}}return!0})}const tVt=/[\u0590-\u08ac]/;function sVt(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?!tVt.test(n.parent.textContent)||!o.modify?r=="left"||r=="backward"?i:l:bit(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:h,anchorOffset:m}=s.domSelectionRange(),x=o.caretBidiLevel;o.modify("move",r,"character");let g=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:v,focusOffset:j}=s.domSelectionRange(),b=v&&!g.contains(v.nodeType==1?v:v.parentNode)||c==v&&d==j;try{o.collapse(h,m),c&&(c!=h||d!=m)&&o.extend&&o.extend(c,d)}catch{}return x!=null&&(o.caretBidiLevel=x),b}):n.pos==n.start()||n.pos==n.end()}let hBe=null,mBe=null,fBe=!1;function rVt(s,t,r){return hBe==t&&mBe==r?fBe:(hBe=t,mBe=r,fBe=r=="up"||r=="down"?eVt(s,t,r):sVt(s,t,r))}const Hg=0,pBe=1,W4=2,o1=3;class az{constructor(t,r,n,a){this.parent=t,this.children=r,this.dom=n,this.contentDOM=a,this.dirty=Hg,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,r,n){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let r=0;rQh(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 wit){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 _it&&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?Qh(i.dom)+1:0}}else{let i,l=!0;for(;i=n=h&&r<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,r,h);t=l;for(let m=o;m>0;m--){let x=this.children[m-1];if(x.size&&x.dom.parentNode==this.contentDOM&&!x.emptyChildAt(1)){a=Qh(x.dom)+1;break}t-=x.size}a==-1&&(a=0)}if(a>-1&&(d>r||o==this.children.length-1)){r=d;for(let h=o+1;hv&&lr){let v=o;o=c,c=v}let g=document.createRange();g.setEnd(c.node,c.offset),g.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(g)}}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?W4:pBe,t==o&&r==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=o1:i.markDirty(t-o,r-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?W4:o1}n=l}this.dirty=W4}markParentsDirty(){let t=1;for(let r=this.parent;r;r=r.parent,t++){let n=t==1?W4:pBe;r.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!r.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=r,this.widget=r,i=this}matchesWidget(t){return this.dirty==Hg&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let r=this.widget.spec.stopEvent;return r?r(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class nVt extends az{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 k5 extends az{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=Y5.renderSpec(document,r.type.spec.toDOM(r,n),null,r.attrs)),new k5(t,r,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&o1||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=o1&&this.mark.eq(t)}markDirty(t,r){if(super.markDirty(t,r),this.dirty!=Hg){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(i=uNe(i,0,t,n));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},n,a),h=d&&d.dom,m=d&&d.contentDOM;if(r.isText){if(!h)h=document.createTextNode(r.text);else if(h.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else h||({dom:h,contentDOM:m}=Y5.renderSpec(document,r.type.spec.toDOM(r),null,r.attrs));!m&&!r.isText&&h.nodeName!="BR"&&(h.hasAttribute("contenteditable")||(h.contentEditable="false"),r.type.spec.draggable&&(h.draggable=!0));let x=h;return h=kit(h,n,r),d?c=new aVt(t,r,n,a,h,m||null,x,d,i,l+1):r.isText?new dxe(t,r,n,a,h,x,i):new d2(t,r,n,a,h,m||null,x,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let n=this.children[r];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;break}}t.contentElement||(t.getContent=()=>an.empty)}return t}matchesNode(t,r,n){return this.dirty==Hg&&t.eq(this.node)&&ohe(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 oVt(this,l&&l.node,t);dVt(this.node,this.innerDeco,(d,h,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,n,t,h):d.type.side>=0&&!m&&c.syncToMarks(h==this.node.childCount?Zl.none:this.node.child(h).marks,n,t,h),c.placeWidget(d,t,a)},(d,h,m,x)=>{c.syncToMarks(d.marks,n,t,x);let g;c.findNodeMatch(d,h,m,x)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,h,m,g,t)||c.updateNextNode(d,h,m,t,x,a)||c.addNode(d,h,m,t,a),a+=d.nodeSize}),c.syncToMarks([],n,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==W4)&&(l&&this.protectLocalComposition(t,l),jit(this.contentDOM,this.children,t),jI&&uVt(this.dom))}localCompositionInfo(t,r){let{from:n,to:a}=t.state.selection;if(!(t.state.selection instanceof Ya)||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=hVt(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 nVt(this,i,r,a);t.input.compositionNodes.push(l),this.children=uNe(this.children,n,n+a.length,t,l)}update(t,r,n,a){return this.dirty==o1||!t.sameMarkup(this.node)?!1:(this.updateInner(t,r,n,a),!0)}updateInner(t,r,n,a){this.updateOuterDeco(r),this.node=t,this.innerDeco=n,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=Hg}updateOuterDeco(t){if(ohe(t,this.outerDeco))return;let r=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=Nit(this.dom,this.nodeDOM,dNe(this.outerDeco,this.node,r),dNe(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 xBe(s,t,r,n,a){kit(n,t,s);let i=new d2(void 0,s,t,r,n,n,n,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class dxe extends d2{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==o1||this.dirty!=Hg&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(r),(this.dirty!=Hg||t.text!=this.node.text)&&t.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=t.text,a.trackWrites==this.nodeDOM&&(a.trackWrites=null)),this.node=t,this.dirty=Hg,!0)}inParent(){let t=this.parent.contentDOM;for(let r=this.nodeDOM;r;r=r.parentNode)if(r==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,r,n){return t==this.nodeDOM?this.posAtStart+Math.min(r,this.node.text.length):super.localPosFromDOM(t,r,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,r,n){let a=this.node.cut(t,r),i=document.createTextNode(a.text);return new dxe(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=o1)}get domAtom(){return!1}isText(t){return this.node.text==t}}class wit extends az{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==Hg&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class aVt extends d2{constructor(t,r,n,a,i,l,o,c,d,h){super(t,r,n,a,i,l,o,d,h),this.spec=c}update(t,r,n,a){if(this.dirty==o1)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 jit(s,t,r){let n=s.firstChild,a=!1;for(let i=0;i>1,o=Math.min(l,t.length);for(;i-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let h=k5.create(this.top,t[l],r,n);this.top.children.splice(this.index,0,h),this.top=h,this.changed=!0}this.index=0,l++}}findNodeMatch(t,r,n,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,r,n))i=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(n){let d=r.children[n-1];if(d instanceof k5)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 cVt(s,t){return s.type.side-t.type.side}function dVt(s,t,r,n){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let v=i+x.nodeSize;if(x.isText){let b=v;l!b.inline):o.slice();n(x,j,t.forChild(i,x),g),i=v}}function uVt(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 hVt(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 uNe(s,t,r,n,a){let i=[];for(let l=0,o=0;l=r||h<=t?i.push(c):(dr&&i.push(c.slice(r-d,c.size,n)))}return i}function z5e(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(cxe(r)){for(c=l;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&Za.isSelectable(m)&&a.parent&&!(m.isInline&&Bqt(r.focusNode,r.focusOffset,a.dom))){let x=a.posBefore;d=new Za(l==x?o:n.resolve(x))}}else{if(r instanceof s.dom.ownerDocument.defaultView.Selection&&r.rangeCount>1){let m=l,x=l;for(let g=0;g{(r.anchorNode!=n||r.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!Sit(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function fVt(s){let t=s.domSelection();if(!t)return;let r=s.cursorWrapper.dom,n=r.nodeName=="IMG";n?t.collapse(r.parentNode,Qh(r)+1):t.collapse(r,0),!n&&!s.state.selection.visible&&yp&&c2<=11&&(r.disabled=!0,r.disabled=!1)}function Cit(s,t){if(t instanceof Za){let r=s.docView.descAt(t.from);r!=s.lastSelectedViewDesc&&(_Be(s),r&&r.selectNode(),s.lastSelectedViewDesc=r)}else _Be(s)}function _Be(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function $5e(s,t,r,n){return s.someProp("createSelectionBetween",a=>a(s,t,r))||Ya.between(t,r,n)}function wBe(s){return s.editable&&!s.hasFocus()?!1:Tit(s)}function Tit(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 pVt(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),r=s.domSelectionRange();return N5(t.node,t.offset,r.anchorNode,r.anchorOffset)}function hNe(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&&vi.findFrom(i,t)}function tj(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function jBe(s,t,r){let n=s.state.selection;if(n instanceof Ya)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 tj(s,new Ya(n.$anchor,l))}else if(n.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=hNe(s.state,t);return a&&a instanceof Za?tj(s,a):!1}else if(!(kg&&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?Za.isSelectable(i)?tj(s,new Za(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):nz?tj(s,new Ya(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(n instanceof Za&&n.node.isInline)return tj(s,new Ya(t>0?n.$to:n.$from));{let a=hNe(s.state,t);return a?tj(s,a):!1}}}function lhe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function n8(s,t){let r=s.pmViewDesc;return r&&r.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function $E(s,t){return t<0?xVt(s):gVt(s)}function xVt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a,i,l=!1;for(Vg&&r.nodeType==1&&n0){if(r.nodeType!=1)break;{let o=r.childNodes[n-1];if(n8(o,-1))a=r,i=--n;else if(o.nodeType==3)r=o,n=r.nodeValue.length;else break}}else{if(Eit(r))break;{let o=r.previousSibling;for(;o&&n8(o,-1);)a=r.parentNode,i=Qh(o),o=o.previousSibling;if(o)r=o,n=lhe(r);else{if(r=r.parentNode,r==s.dom)break;n=0}}}l?mNe(s,r,n):a&&mNe(s,a,i)}function gVt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a=lhe(r),i,l;for(;;)if(n{s.state==a&&o_(s)},50)}function NBe(s,t){let r=s.state.doc.resolve(t);if(!(kh||fit)&&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 kBe(s,t,r){let n=s.state.selection;if(n instanceof Ya&&!n.empty||r.indexOf("s")>-1||kg&&r.indexOf("m")>-1)return!1;let{$from:a,$to:i}=n;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=hNe(s.state,t);if(l&&l instanceof Za)return tj(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=n instanceof jx?vi.near(l,t):vi.findFrom(l,t);return o?tj(s,o):!1}return!1}function SBe(s,t){if(!(s.state.selection instanceof Ya))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 CBe(s,t,r){s.domObserver.stop(),t.contentEditable=r,s.domObserver.start()}function bVt(s){if(!Bm||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;CBe(s,n,"true"),setTimeout(()=>CBe(s,n,"false"),20)}return!1}function _Vt(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function wVt(s,t){let r=t.keyCode,n=_Vt(t);if(r==8||kg&&r==72&&n=="c")return SBe(s,-1)||$E(s,-1);if(r==46&&!t.shiftKey||kg&&r==68&&n=="c")return SBe(s,1)||$E(s,1);if(r==13||r==27)return!0;if(r==37||kg&&r==66&&n=="c"){let a=r==37?NBe(s,s.state.selection.from)=="ltr"?-1:1:-1;return jBe(s,a,n)||$E(s,a)}else if(r==39||kg&&r==70&&n=="c"){let a=r==39?NBe(s,s.state.selection.from)=="ltr"?1:-1:1;return jBe(s,a,n)||$E(s,a)}else{if(r==38||kg&&r==80&&n=="c")return kBe(s,-1,n)||$E(s,-1);if(r==40||kg&&r==78&&n=="c")return bVt(s)||kBe(s,1,n)||$E(s,1);if(n==(kg?"m":"c")&&(r==66||r==73||r==89||r==90))return!0}return!1}function U5e(s,t){s.someProp("transformCopied",g=>{t=g(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 g=n.firstChild;r.push(g.type.name,g.attrs!=g.type.defaultAttrs?g.attrs:null),n=g.content}let l=s.someProp("clipboardSerializer")||Y5.fromSchema(s.state.schema),o=Dit(),c=o.createElement("div");c.appendChild(l.serializeFragment(n,{document:o}));let d=c.firstChild,h,m=0;for(;d&&d.nodeType==1&&(h=Lit[d.nodeName.toLowerCase()]);){for(let g=h.length-1;g>=0;g--){let v=o.createElement(h[g]);for(;c.firstChild;)v.appendChild(c.firstChild);c.appendChild(v),m++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${m?` -${m}`:""} ${JSON.stringify(r)}`);let x=s.someProp("clipboardTextSerializer",g=>g(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:x,slice:t}}function Ait(s,t,r,n,a){let i=a.parent.type.spec.code,l,o;if(!r&&!t)return null;let c=!!t&&(n||i||!r);if(c){if(s.someProp("transformPastedText",x=>{t=x(t,i||n,s)}),i)return o=new Un(an.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",x=>{o=x(o,s,!0)}),o;let m=s.someProp("clipboardTextParser",x=>x(t,a,n,s));if(m)o=m;else{let x=a.marks(),{schema:g}=s.state,v=Y5.fromSchema(g);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(j=>{let b=l.appendChild(document.createElement("p"));j&&b.appendChild(v.serializeNode(g.text(j,x)))})}}else s.someProp("transformPastedHTML",m=>{r=m(r,s)}),l=SVt(r),nz&&CVt(l);let d=l&&l.querySelector("[data-pm-slice]"),h=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(h&&h[3])for(let m=+h[3];m>0;m--){let x=l.firstChild;for(;x&&x.nodeType!=1;)x=x.nextSibling;if(!x)break;l=x}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||t8.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||h),context:a,ruleFromNode(x){return x.nodeName=="BR"&&!x.nextSibling&&x.parentNode&&!jVt.test(x.parentNode.nodeName)?{ignore:!0}:null}})),h)o=TVt(TBe(o,+h[1],+h[2]),h[4]);else if(o=Un.maxOpen(NVt(o.content,a),!0),o.openStart||o.openEnd){let m=0,x=0;for(let g=o.content.firstChild;m{o=m(o,s,c)}),o}const jVt=/^(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 NVt(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&&Iit(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Pit(l[l.length-1],i.length));let h=Mit(o,c);l.push(h),a=a.matchType(h.type),i=c}}),l)return an.from(l)}return s}function Mit(s,t,r=0){for(let n=t.length-1;n>=r;n--)s=t[n].create(null,an.from(s));return s}function Iit(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(an.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function TBe(s,t,r){return tr})),abe.createHTML(s)):s}function SVt(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let r=Dit().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),a;if((a=n&&Lit[n[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),r.innerHTML=kVt(s),a)for(let i=0;i=0;o-=2){let c=r.nodes[n[o]];if(!c||c.hasRequiredAttrs())break;a=an.from(c.create(n[o+1],a)),i++,l++}return new Un(a,i,l)}const Ef={},Af={},EVt={touchstart:!0,touchmove:!0};class AVt{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 MVt(s){for(let t in Ef){let r=Ef[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>{PVt(s,n)&&!q5e(s,n)&&(s.editable||!(n.type in Af))&&r(s,n)},EVt[t]?{passive:!0}:void 0)}Bm&&s.dom.addEventListener("input",()=>null),pNe(s)}function Gb(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function IVt(s){s.input.mouseDown&&s.input.mouseDown.done(),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 pNe(s){s.someProp("handleDOMEvents",t=>{for(let r in t)s.input.eventHandlers[r]||s.dom.addEventListener(r,s.input.eventHandlers[r]=n=>q5e(s,n))})}function q5e(s,t){return s.someProp("handleDOMEvents",r=>{let n=r[t.type];return n?n(s,t)||t.defaultPrevented:!1})}function PVt(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let r=t.target;r!=s.dom;r=r.parentNode)if(!r||r.nodeType==11||r.pmViewDesc&&r.pmViewDesc.stopEvent(t))return!1;return!0}function LVt(s,t){!q5e(s,t)&&Ef[t.type]&&(s.editable||!(t.type in Af))&&Ef[t.type](s,t)}Af.keydown=(s,t)=>{let r=t;if(s.input.shiftKey=r.keyCode==16||r.shiftKey,!Bit(s)&&(s.input.lastKeyCode=r.keyCode,s.input.lastKeyCodeTime=Date.now(),!(Hb&&kh&&r.keyCode==13)))if(r.keyCode!=229&&s.domObserver.forceFlush(),jI&&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,D4(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,r))||wVt(s,r)?r.preventDefault():Gb(s,"key")};Af.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};Af.keypress=(s,t)=>{let r=t;if(Bit(s)||!r.charCode||r.ctrlKey&&!r.altKey||kg&&r.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,r))){r.preventDefault();return}let n=s.state.selection;if(!(n instanceof Ya)||!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 iz(s){return{left:s.clientX,top:s.clientY}}function DVt(s,t){let r=t.x-s.clientX,n=t.y-s.clientY;return r*r+n*n<100}function V5e(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 oz(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 RVt(s,t){if(t==-1)return!1;let r=s.state.doc.resolve(t),n=r.nodeAfter;return n&&n.isAtom&&Za.isSelectable(n)?(oz(s,new Za(r)),!0):!1}function OVt(s,t){if(t==-1)return!1;let r=s.state.selection,n,a;r instanceof Za&&(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(Za.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?(oz(s,Za.create(s.state.doc,a)),!0):!1}function FVt(s,t,r,n,a){return V5e(s,"handleClickOn",t,r,n)||s.someProp("handleClick",i=>i(s,t,n))||(a?OVt(s,r):RVt(s,r))}function BVt(s,t,r,n){return V5e(s,"handleDoubleClickOn",t,r,n)||s.someProp("handleDoubleClick",a=>a(s,t,n))}function zVt(s,t,r,n){return V5e(s,"handleTripleClickOn",t,r,n)||s.someProp("handleTripleClick",a=>a(s,t,n))||$Vt(s,r,n)}function $Vt(s,t,r){if(r.button!=0)return!1;let n=Rit(s,t,!0),a=s.state.doc;return n?(oz(s,n),n instanceof Ya&&a.eq(s.state.doc)&&(s.input.mouseDown=new qVt(s,n)),!0):!1}function Rit(s,t,r){let n=s.state.doc;if(t==-1)return n.inlineContent?Ya.create(n,0,n.content.size):null;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)return Ya.create(n,o+1,o+1+l.content.size);if(r&&Za.isSelectable(l))return Za.create(n,o)}return null}function H5e(s){return che(s)}const Oit=kg?"metaKey":"ctrlKey";Ef.mousedown=(s,t)=>{let r=t;s.input.shiftKey=r.shiftKey;let n=H5e(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&DVt(r,s.input.lastClick)&&!r[Oit]&&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},s.input.mouseDown&&s.input.mouseDown.done();let l=s.posAtCoords(iz(r));l&&(i=="singleClick"?s.input.mouseDown=new UVt(s,l,r,!!n):(i=="doubleClick"?BVt:zVt)(s,l.pos,l.inside,r)?r.preventDefault():Gb(s,"pointer"))};class Fit{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){t.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class UVt extends Fit{constructor(t,r,n,a){super(t),this.pos=r,this.event=n,this.flushed=a,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!n[Oit],this.allowDefault=n.shiftKey;let i,l;if(r.inside>-1)i=t.state.doc.nodeAt(r.inside),l=r.inside;else{let h=t.state.doc.resolve(r.pos);i=h.parent,l=h.depth?h.before():0}const o=a?null:n.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Za&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Vg&&!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()),Gb(t,"pointer")}done(){super.done(),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(()=>{this.view.isDestroyed||o_(this.view)})}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(iz(t))),this.updateAllowDefault(t),this.allowDefault||!r?Gb(this.view,"pointer"):FVt(this.view,r.pos,r.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||Bm&&this.mightDrag&&!this.mightDrag.node.isAtom||kh&&!this.view.state.selection.visible&&Math.min(Math.abs(r.pos-this.view.state.selection.from),Math.abs(r.pos-this.view.state.selection.to))<=2)?(oz(this.view,vi.near(this.view.state.doc.resolve(r.pos))),t.preventDefault()):Gb(this.view,"pointer")}move(t){this.updateAllowDefault(t),Gb(this.view,"pointer"),super.move(t)}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class qVt extends Fit{constructor(t,r){super(t),this.startSelection=r,this.startDoc=t.state.doc}move(t){if(t.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}t.preventDefault(),Gb(this.view,"pointer");let r=this.view.posAtCoords(iz(t)),n=r&&Rit(this.view,r.inside,!1);if(!n)return;let{doc:a}=this.view.state,i=this.startSelection,[l,o]=n.from{s.input.lastTouch=Date.now(),H5e(s),Gb(s,"pointer")};Ef.touchmove=s=>{s.input.lastTouch=Date.now(),Gb(s,"pointer")};Ef.contextmenu=s=>H5e(s);function Bit(s,t){return s.composing?!0:Bm&&Math.abs(Date.now()-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const VVt=Hb?5e3:-1;Af.compositionstart=Af.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,r=t.selection.$to;if(t.selection instanceof Ya&&(t.storedMarks||!r.textOffset&&r.parentOffset&&r.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||kh&&fit&&HVt(s)))s.markCursor=s.state.storedMarks||r.marks(),che(s,!0),s.markCursor=null;else if(che(s,!t.selection.empty),Vg&&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}zit(s,VVt)};function HVt(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"}Af.compositionend=(s,t)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now(),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++,zit(s,20))};function zit(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>che(s),t))}function $it(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function GVt(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let r=Oqt(t.focusNode,t.focusOffset),n=Fqt(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 che(s,t=!1){if(!(Hb&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),$it(s),t||s.docView&&s.docView.dirty){let r=z5e(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 WVt(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 mF=yp&&c2<15||jI&&Uqt<604;Ef.copy=Af.cut=(s,t)=>{let r=t,n=s.state.selection,a=r.type=="cut";if(n.empty)return;let i=mF?null:r.clipboardData,l=n.content(),{dom:o,text:c}=U5e(s,l);i?(r.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):WVt(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function KVt(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function YVt(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?fF(s,n.value,null,a,t):fF(s,n.textContent,n.innerHTML,a,t)},50)}function fF(s,t,r,n,a){let i=Ait(s,t,r,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Un.empty)))return!0;if(!i)return!1;let l=KVt(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 Uit(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," "):""}Af.paste=(s,t)=>{let r=t;if(s.composing&&!Hb)return;let n=mF?null:r.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&fF(s,Uit(n),n.getData("text/html"),a,r)?r.preventDefault():YVt(s,r)};class qit{constructor(t,r,n){this.slice=t,this.move=r,this.node=n}}const ZVt=kg?"altKey":"ctrlKey";function Vit(s,t){let r;return s.someProp("dragCopies",n=>{r=r||n(t)}),r!=null?!r:!t[ZVt]}Ef.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(iz(r)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Za?a.to-1:a.to))){if(n&&n.mightDrag)l=Za.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=Za.create(s.state.doc,m.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:h}=U5e(s,o);(!r.dataTransfer.files.length||!kh||mit>120)&&r.dataTransfer.clearData(),r.dataTransfer.setData(mF?"Text":"text/html",c.innerHTML),r.dataTransfer.effectAllowed="copyMove",mF||r.dataTransfer.setData("text/plain",d),s.dragging=new qit(h,Vit(s,r),l)};Ef.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};Af.dragover=Af.dragenter=(s,t)=>t.preventDefault();Af.drop=(s,t)=>{try{XVt(s,t,s.dragging)}finally{s.dragging=null}};function XVt(s,t,r){if(!t.dataTransfer)return;let n=s.posAtCoords(iz(t));if(!n)return;let a=s.state.doc.resolve(n.pos),i=r&&r.slice;i?s.someProp("transformPasted",g=>{i=g(i,s,!1)}):i=Ait(s,Uit(t.dataTransfer),mF?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(r&&Vit(s,t));if(s.someProp("handleDrop",g=>g(s,t,i||Un.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?nit(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:g}=r;g?g.replace(c):c.deleteSelection()}let d=c.mapping.map(o),h=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,m=c.doc;if(h?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(m))return;let x=c.doc.resolve(d);if(h&&Za.isSelectable(i.content.firstChild)&&x.nodeAfter&&x.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Za(x));else{let g=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((v,j,b,N)=>g=N),c.setSelection($5e(s,x,c.doc.resolve(g)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}Ef.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())&&o_(s)},20))};Ef.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)};Ef.beforeinput=(s,t)=>{if(kh&&Hb&&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,D4(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 Af)Ef[s]=Af[s];function pF(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 dhe{constructor(t,r){this.toDOM=t,this.spec=r||Q3,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 bf(i-n,i-n,this)}valid(){return!0}eq(t){return this==t||t instanceof dhe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&pF(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class u2{constructor(t,r){this.attrs=t,this.spec=r||Q3}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 bf(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==Cm||t.maps.length==0?this:this.mapInner(t,r,0,0,n||Q3)}mapInner(t,r,n,a,i){let l;for(let o=0;o{let d=c+n,h;if(h=Git(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 u2){let d=Math.max(i,c.from)-i,h=Math.min(l,c.to)-i;da.map(t,r,Q3));return mj.from(n)}forChild(t,r){if(r.isLeaf)return Md.empty;let n=[];for(let a=0;ar instanceof Md)?t:t.reduce((r,n)=>r.concat(n instanceof Md?n:n.members),[]))}}forEachSet(t){for(let r=0;r{let b=j-v-(g-x);for(let N=0;NS+h-m)continue;let T=o[N]+h-m;g>=T?o[N+1]=x<=T?-2:-1:x>=h&&b&&(o[N]+=b,o[N+1]+=b)}m+=b}),h=r.maps[d].map(h,-1)}let c=!1;for(let d=0;d=n.content.size){c=!0;continue}let x=r.map(s[d+1]+i,-1),g=x-a,{index:v,offset:j}=n.content.findIndex(m),b=n.maybeChild(v);if(b&&j==m&&j+b.nodeSize==g){let N=o[d+2].mapInner(r,b,h+1,s[d]+i+1,l);N!=Cm?(o[d]=m,o[d+1]=g,o[d+2]=N):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=JVt(o,s,t,r,a,i,l),h=uhe(d,n,0,l);t=h.local;for(let m=0;mr&&l.to{let d=Git(s,o,c+r);if(d){i=!0;let h=uhe(d,o,r+c+1,n);h!=Cm&&a.push(c,c+o.nodeSize,h)}});let l=Hit(i?Wit(s):s,-r).sort(J3);for(let o=0;o0;)t++;s.splice(t,0,r)}function ibe(s){let t=[];return s.someProp("decorations",r=>{let n=r(s.state);n&&n!=Cm&&t.push(n)}),s.cursorWrapper&&t.push(Md.create(s.state.doc,[s.cursorWrapper.deco])),mj.from(t)}const eHt={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},tHt=yp&&c2<=11;class sHt{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 rHt{constructor(t,r){this.view=t,this.handleDOMChange=r,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new sHt,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():Bm&&t.composing&&n.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),tHt&&(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,eHt)),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(wBe(this.view)){if(this.suppressingSelectionUpdates)return o_(this.view);if(yp&&c2<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&N5(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=wI(i))r.add(i);for(let i=t.anchorNode;i;i=wI(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)&&wBe(t)&&!this.ignoreSelectionChange(n),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let h=0;hh.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||kh&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&r.some(h=>h.type=="childList"&&h.removedNodes.length))){for(let h of c)if(h.nodeName=="BR"&&h.parentNode){let m=h.nextSibling;for(;m&&m.nodeType==1;){if(m.contentEditable=="false"){h.parentNode.removeChild(h);break}m=m.firstChild}}}else if(Vg&&c.length){let h=c.filter(m=>m.nodeName=="BR");if(h.length==2){let[m,x]=h;m.parentNode&&m.parentNode.parentNode==x.parentNode?x.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let x of h){let g=x.parentNode;g&&g.nodeName=="LI"&&(!m||iHt(t,m)!=g)&&x.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),nHt(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,oHt(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(n)||o_(t),this.currentSelection.set(n))}registerMutation(t,r){if(r.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let h=0;ha;b--){let N=n.childNodes[b-1],S=N.pmViewDesc;if(N.nodeName=="BR"&&!S){i=b;break}if(!S||S.size)break}let m=s.state.doc,x=s.someProp("domParser")||t8.fromSchema(s.state.schema),g=m.resolve(l),v=null,j=x.parse(n,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:a,to:i,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:cHt,context:g});if(d&&d[0].pos!=null){let b=d[0].pos,N=d[1]&&d[1].pos;N==null&&(N=b),v={anchor:b+l,head:N+l}}return{doc:j,sel:v,from:l,to:o}}function cHt(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(Bm&&/^(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||Bm&&/^(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 dHt=/^(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 uHt(s,t,r,n,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let B=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,z=z5e(s,B);if(z&&!s.state.selection.eq(z)){if(kh&&Hb&&s.input.lastKeyCode===13&&Date.now()-100$(s,D4(13,"Enter"))))return;let F=s.state.tr.setSelection(z);B=="pointer"?F.setMeta("pointer",!0):B=="key"&&F.scrollIntoView(),i&&F.setMeta("composition",i),s.dispatch(F)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(r);t=l.before(o+1),r=s.state.doc.resolve(r).after(o+1);let c=s.state.selection,d=lHt(s,t,r),h=s.state.doc,m=h.slice(d.from,d.to),x,g;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Hb)&&a.some(B=>B.nodeType==1&&!dHt.test(B.nodeName))&&(!v||v.endA>=v.endB)&&s.someProp("handleKeyDown",B=>B(s,D4(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!v)if(n&&c instanceof Ya&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))v={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let B=LBe(s,s.state.doc,d.sel);if(B&&!B.eq(s.state.selection)){let z=s.state.tr.setSelection(B);i&&z.setMeta("composition",i),s.dispatch(z)}}return}s.state.selection.froms.state.selection.from&&v.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?v.start=s.state.selection.from:v.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(v.endB+=s.state.selection.to-v.endA,v.endA=s.state.selection.to)),yp&&c2<=11&&v.endB==v.start+1&&v.endA==v.start&&v.start>d.from&&d.doc.textBetween(v.start-d.from-1,v.start-d.from+1)=="  "&&(v.start--,v.endA--,v.endB--);let j=d.doc.resolveNoCache(v.start-d.from),b=d.doc.resolveNoCache(v.endB-d.from),N=h.resolve(v.start),S=j.sameParent(b)&&j.parent.inlineContent&&N.end()>=v.endA;if((jI&&s.input.lastIOSEnter>Date.now()-225&&(!S||a.some(B=>B.nodeName=="DIV"||B.nodeName=="P"))||!S&&j.posB(s,D4(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>v.start&&mHt(h,v.start,v.endA,j,b)&&s.someProp("handleKeyDown",B=>B(s,D4(8,"Backspace")))){Hb&&kh&&s.domObserver.suppressSelectionUpdates();return}kh&&v.endB==v.start&&(s.input.lastChromeDelete=Date.now()),Hb&&!S&&j.start()!=b.start()&&b.parentOffset==0&&j.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==v.endA&&(v.endB-=2,b=d.doc.resolveNoCache(v.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(B){return B(s,D4(13,"Enter"))})},20));let T=v.start,A=v.endA,P=B=>{let z=B||s.state.tr.replace(T,A,d.doc.slice(v.start-d.from,v.endB-d.from));if(d.sel){let F=LBe(s,z.doc,d.sel);F&&!(kh&&s.composing&&F.empty&&(v.start!=v.endB||s.input.lastChromeDeleteo_(s),20));let B=P(s.state.tr.delete(T,A)),z=h.resolve(v.start).marksAcross(h.resolve(v.endA));z&&B.ensureMarks(z),s.dispatch(B)}else if(v.endA==v.endB&&(D=hHt(j.parent.content.cut(j.parentOffset,b.parentOffset),N.parent.content.cut(N.parentOffset,v.endA-N.start())))){let B=P(s.state.tr);D.type=="add"?B.addMark(T,A,D.mark):B.removeMark(T,A,D.mark),s.dispatch(B)}else if(j.parent.child(j.index()).isText&&j.index()==b.index()-(b.textOffset?0:1)){let B=j.parent.textBetween(j.parentOffset,b.parentOffset),z=()=>P(s.state.tr.insertText(B,T,A));s.someProp("handleTextInput",F=>F(s,T,A,B,z))||s.dispatch(z())}else s.dispatch(P());else s.dispatch(P())}function LBe(s,t,r){return Math.max(r.anchor,r.head)>t.content.size?null:$5e(s,t.resolve(r.anchor),t.resolve(r.head))}function hHt(s,t){let r=s.firstChild.marks,n=t.firstChild.marks,a=r,i=n,l,o,c;for(let h=0;hh.mark(o.addToSet(h.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=h=>h.mark(o.removeFromSet(h.marks));else return null;let d=[];for(let h=0;hr||obe(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 fHt(s,t,r,n,a){let i=s.findDiffStart(t,r),l=r+s.size,o=r+t.size;if(i==null)return null;let{a:c,b:d}=s.findDiffEnd(t,l,o);if(a=="end"){let h=Math.max(0,i-Math.min(c,d));n-=c+h-i}if(c=c?i-n:0;i-=h,d=i+(d-c),c=i}else if(d=d?i-n:0;i-=h,c=i+(c-d),d=i}return{start:i,endA:c,endB:d}}class Kit{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 AVt,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=r,this.state=r.state,this.directPlugins=r.plugins||[],this.directPlugins.forEach(BBe),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=OBe(this),RBe(this),this.nodeViews=FBe(this),this.docView=xBe(this.state.doc,DBe(this),ibe(this),this.dom,this),this.domObserver=new rHt(this,(n,a,i,l)=>uHt(this,n,a,i,l)),this.domObserver.start(),MVt(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&&pNe(this);let r=this._props;this._props=t,t.plugins&&(t.plugins.forEach(BBe),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&&($it(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 g=FBe(this);xHt(g,this.nodeViews)&&(this.nodeViews=g,i=!0)}(o||r.handleDOMEvents!=this._props.handleDOMEvents)&&pNe(this),this.editable=OBe(this),RBe(this);let c=ibe(this),d=DBe(this),h=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=i||!this.docView.matchesNode(t.doc,d,c);(m||!t.selection.eq(a.selection))&&(l=!0);let x=h=="preserve"&&l&&this.dom.style.overflowAnchor==null&&Hqt(this);if(l){this.domObserver.stop();let g=m&&(yp||kh)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&pHt(a.selection,t.selection);if(m){let j=kh?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=GVt(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=xBe(t.doc,d,c,this.dom,this)),j&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(g=!0)}let v=this.input.mouseDown;g||!(v&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&pVt(this)&&v.delaySelUpdate())?o_(this,g):(Cit(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((n=this.dragging)===null||n===void 0)&&n.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),h=="reset"?this.dom.scrollTop=0:h=="to selection"?this.scrollToSelection():x&&Gqt(x)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",r=>r(this)))if(this.state.selection instanceof Za){let r=this.docView.domAfterPos(this.state.selection.from);r.nodeType==1&&dBe(this,r.getBoundingClientRect(),t)}else dBe(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 Qqt(this,t)}coordsAtPos(t,r=1){return vit(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 rVt(this,r||this.state,t)}pasteHTML(t,r){return fF(this,"",t,!1,r||new ClipboardEvent("paste"))}pasteText(t,r){return fF(this,t,null,!0,r||new ClipboardEvent("paste"))}serializeForClipboard(t){return U5e(this,t)}destroy(){this.docView&&(IVt(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ibe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Dqt())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return LVt(this,t)}domSelectionRange(){let t=this.domSelection();return t?Bm&&this.root.nodeType===11&&zqt(this.dom.ownerDocument)==this.dom&&aHt(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Kit.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function DBe(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"),[bf.node(0,s.state.doc.content.size,t)]}function RBe(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:bf.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function OBe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function pHt(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 FBe(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 xHt(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 BBe(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 E2={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:"'"},hhe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},gHt=typeof navigator<"u"&&/Mac/.test(navigator.platform),yHt=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Jh=0;Jh<10;Jh++)E2[48+Jh]=E2[96+Jh]=String(Jh);for(var Jh=1;Jh<=24;Jh++)E2[Jh+111]="F"+Jh;for(var Jh=65;Jh<=90;Jh++)E2[Jh]=String.fromCharCode(Jh+32),hhe[Jh]=String.fromCharCode(Jh);for(var lbe in E2)hhe.hasOwnProperty(lbe)||(hhe[lbe]=E2[lbe]);function vHt(s){var t=gHt&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||yHt&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",r=!t&&s.key||(s.shiftKey?hhe:E2)[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 bHt=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),_Ht=typeof navigator<"u"&&/Win/.test(navigator.platform);function wHt(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 Yit(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("backward",s):r.parentOffset>0)?null:r}const Zit=(s,t,r)=>{let n=Yit(s,r);if(!n)return!1;let a=Z5e(n);if(!a){let l=n.blockRange(),o=l&&PP(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(aot(s,a,t,-1))return!0;if(n.parent.content.size==0&&(NI(i,"end")||Za.isSelectable(i)))for(let l=n.depth;;l--){let o=oxe(s.doc,n.before(l),n.after(l),Un.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==n.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},kHt=(s,t,r)=>{let n=Yit(s,r);if(!n)return!1;let a=Z5e(n);return a?Xit(s,a,t):!1},SHt=(s,t,r)=>{let n=Jit(s,r);if(!n)return!1;let a=X5e(n);return a?Xit(s,a,t):!1};function Xit(s,t,r){let n=t.nodeBefore,a=n,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let h=a.lastChild;if(!h)return!1;a=h}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let h=o.firstChild;if(!h)return!1;o=h}let d=oxe(s.doc,i,c,Un.empty);if(!d||d.from!=i||d instanceof bu&&d.slice.size>=c-i)return!1;if(r){let h=s.tr.step(d);h.setSelection(Ya.create(h.doc,i)),r(h.scrollIntoView())}return!0}function NI(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 Qit=(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=Z5e(n)}let l=i&&i.nodeBefore;return!l||!Za.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Za.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function Z5e(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 Jit(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("forward",s):r.parentOffset{let n=Jit(s,r);if(!n)return!1;let a=X5e(n);if(!a)return!1;let i=a.nodeAfter;if(aot(s,a,t,1))return!0;if(n.parent.content.size==0&&(NI(i,"start")||Za.isSelectable(i))){let l=oxe(s.doc,n.before(),n.after(),Un.empty);if(l&&l.slice.size{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("forward",s):n.parentOffset=0;t--){let r=s.node(t);if(s.index(t)+1{let r=s.selection,n=r instanceof Za,a;if(n){if(r.node.isTextblock||!Z2(s.doc,r.from))return!1;a=r.from}else if(a=ixe(s.doc,r.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);n&&i.setSelection(Za.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},THt=(s,t)=>{let r=s.selection,n;if(r instanceof Za){if(r.node.isTextblock||!Z2(s.doc,r.to))return!1;n=r.to}else if(n=ixe(s.doc,r.to,1),n==null)return!1;return t&&t(s.tr.join(n).scrollIntoView()),!0},EHt=(s,t)=>{let{$from:r,$to:n}=s.selection,a=r.blockRange(n),i=a&&PP(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},sot=(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 Q5e(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=Q5e(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(vi.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},rot=(s,t)=>{let r=s.selection,{$from:n,$to:a}=r;if(r instanceof jx||n.parent.inlineContent||a.parent.inlineContent)return!1;let i=Q5e(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(i_(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let n=r.blockRange(),a=n&&PP(n);return a==null?!1:(t&&t(s.tr.lift(n,a).scrollIntoView()),!0)};function MHt(s){return(t,r)=>{let{$from:n,$to:a}=t.selection;if(t.selection instanceof Za&&t.selection.node.isBlock)return!n.parentOffset||!i_(t.doc,n.pos)?!1:(r&&r(t.tr.split(n.pos).scrollIntoView()),!0);if(!n.depth)return!1;let i=[],l,o,c=!1,d=!1;for(let g=n.depth;;g--)if(n.node(g).isBlock){c=n.end(g)==n.pos+(n.depth-g),d=n.start(g)==n.pos-(n.depth-g),o=Q5e(n.node(g-1).contentMatchAt(n.indexAfter(g-1))),i.unshift(c&&o?{type:o}:null),l=g;break}else{if(g==1)return!1;i.unshift(null)}let h=t.tr;(t.selection instanceof Ya||t.selection instanceof jx)&&h.deleteSelection();let m=h.mapping.map(n.pos),x=i_(h.doc,m,i.length,i);if(x||(i[0]=o?{type:o}:null,x=i_(h.doc,m,i.length,i)),!x)return!1;if(h.split(m,i.length,i),!c&&d&&n.node(l).type!=o){let g=h.mapping.map(n.before(l)),v=h.doc.resolve(g);o&&n.node(l-1).canReplaceWith(v.index(),v.index()+1,o)&&h.setNodeMarkup(h.mapping.map(n.before(l)),o)}return r&&r(h.scrollIntoView()),!0}}const IHt=MHt(),PHt=(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(Za.create(s.doc,a))),!0)};function LHt(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||Z2(s.doc,t.pos))?!1:(r&&r(s.tr.join(t.pos).scrollIntoView()),!0)}function aot(s,t,r,n){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&LHt(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 g=t.pos+i.nodeSize,v=an.empty;for(let N=l.length-1;N>=0;N--)v=an.from(l[N].create(null,v));v=an.from(a.copy(v));let j=s.tr.step(new Ih(t.pos-1,g,t.pos,g,new Un(v,1,0),l.length,!0)),b=j.doc.resolve(g+2*l.length);b.nodeAfter&&b.nodeAfter.type==a.type&&Z2(j.doc,b.pos)&&j.join(b.pos),r(j.scrollIntoView())}return!0}let h=i.type.spec.isolating||n>0&&c?null:vi.findFrom(t,1),m=h&&h.$from.blockRange(h.$to),x=m&&PP(m);if(x!=null&&x>=t.depth)return r&&r(s.tr.lift(m,x).scrollIntoView()),!0;if(d&&NI(i,"start",!0)&&NI(a,"end")){let g=a,v=[];for(;v.push(g),!g.isTextblock;)g=g.lastChild;let j=i,b=1;for(;!j.isTextblock;j=j.firstChild)b++;if(g.canReplace(g.childCount,g.childCount,j.content)){if(r){let N=an.empty;for(let T=v.length-1;T>=0;T--)N=an.from(v[T].copy(N));let S=s.tr.step(new Ih(t.pos-v.length,t.pos+i.nodeSize,t.pos+b,t.pos+i.nodeSize-b,new Un(N,v.length,0),0,!0));r(S.scrollIntoView())}return!0}}return!1}function iot(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(Ya.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const DHt=iot(-1),RHt=iot(1);function OHt(s,t=null){return function(r,n){let{$from:a,$to:i}=r.selection,l=a.blockRange(i),o=l&&R5e(l,s,t);return o?(n&&n(r.tr.wrap(l,o).scrollIntoView()),!0):!1}}function zBe(s,t=null){return function(r,n){let a=!1;for(let i=0;i{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(s,t)))if(c.type==s)a=!0;else{let h=r.doc.resolve(d),m=h.index();a=h.parent.canReplaceWith(m,m+1,s)}})}if(!a)return!1;if(n){let i=r.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(r)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new ahe(c,c,t.depth),t.endIndex=0;h--)i=an.from(r[h].type.create(r[h].attrs,i));s.step(new Ih(t.start-(n?2:0),t.end,t.start,t.end,new Un(i,0,0),r.length,!0));let l=0;for(let h=0;hl.childCount>0&&l.firstChild.type==s);return i?r?n.node(i.depth-1).type==s?UHt(t,r,s,i):qHt(t,r,i):!0:!1}}function UHt(s,t,r,n){let a=s.tr,i=n.end,l=n.$to.end(n.depth);ij;v--)g-=a.child(v).nodeSize,n.delete(g-1,g+1);let i=n.doc.resolve(r.start),l=i.nodeAfter;if(n.mapping.map(r.end)!=r.start+i.nodeAfter.nodeSize)return!1;let o=r.startIndex==0,c=r.endIndex==a.childCount,d=i.node(-1),h=i.index(-1);if(!d.canReplace(h+(o?0:1),h+1,l.content.append(c?an.empty:an.from(a))))return!1;let m=i.pos,x=m+l.nodeSize;return n.step(new Ih(m-(o?1:0),x+(c?1:0),m+1,x-1,new Un((o?an.empty:an.from(a.copy(an.empty))).append(c?an.empty:an.from(a.copy(an.empty))),o?0:1,c?0:1),o?0:1)),t(n.scrollIntoView()),!0}function VHt(s){return function(t,r){let{$from:n,$to:a}=t.selection,i=n.blockRange(a,d=>d.childCount>0&&d.firstChild.type==s);if(!i)return!1;let l=i.startIndex;if(l==0)return!1;let o=i.parent,c=o.child(l-1);if(c.type!=s)return!1;if(r){let d=c.lastChild&&c.lastChild.type==o.type,h=an.from(d?s.create():null),m=new Un(an.from(s.create(null,an.from(o.type.create(null,h)))),d?3:1,0),x=i.start,g=i.end;r(t.tr.step(new Ih(x-(d?3:1),g,x,g,m,1,!0)).scrollIntoView())}return!0}}function uxe(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 hxe{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:r,state:n}=this,{view:a}=r,{tr:i}=n,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...h)=>{const m=c(...h)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),m}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,h=()=>(!c&&r&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(x=>x===!0)),m={...Object.fromEntries(Object.entries(n).map(([x,g])=>[x,(...j)=>{const b=this.buildProps(d,r),N=g(...j)(b);return o.push(N),m}])),run:h};return m}createCan(t){const{rawCommands:r,state:n}=this,a=!1,i=t||n.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...h)=>d(...h)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:uxe({state:i,transaction:t}),dispatch:r?()=>{}:void 0,chain:()=>this.createChain(t,r),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...h)=>d(...h)(o)]))}};return o}}let HHt=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 ba(s,t,r){return s.config[t]===void 0&&s.parent?ba(s.parent,t,r):typeof s.config[t]=="function"?s.config[t].bind({...r,parent:s.parent?ba(s.parent,t,r):null}):s.config[t]}function mxe(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 oot(s){const t=[],{nodeExtensions:r,markExtensions:n}=mxe(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=ba(l,"addGlobalAttributes",o);if(!c)return;c().forEach(h=>{h.types.forEach(m=>{Object.entries(h.attributes).forEach(([x,g])=>{t.push({type:m,name:x,attribute:{...i,...g}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=ba(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([h,m])=>{const x={...i,...m};typeof(x==null?void 0:x.default)=="function"&&(x.default=x.default()),x!=null&&x.isRequired&&(x==null?void 0:x.default)===void 0&&delete x.default,t.push({type:l.name,name:h,attribute:x})})}),t}function Dh(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 Zc(...s){return s.filter(t=>!!t).reduce((t,r)=>{const n={...t};return Object.entries(r).forEach(([a,i])=>{if(!n[a]){n[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=n[a]?n[a].split(" "):[],d=o.filter(h=>!c.includes(h));n[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(h=>h.trim()).filter(Boolean):[],c=n[a]?n[a].split(";").map(h=>h.trim()).filter(Boolean):[],d=new Map;c.forEach(h=>{const[m,x]=h.split(":").map(g=>g.trim());d.set(m,x)}),o.forEach(h=>{const[m,x]=h.split(":").map(g=>g.trim());d.set(m,x)}),n[a]=Array.from(d.entries()).map(([h,m])=>`${h}: ${m}`).join("; ")}else n[a]=i}),n},{})}function xNe(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)=>Zc(r,n),{})}function lot(s){return typeof s=="function"}function to(s,t=void 0,...r){return lot(s)?t?s.bind(t)(...r):s(...r):s}function GHt(s={}){return Object.keys(s).length===0&&s.constructor===Object}function WHt(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function $Be(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):WHt(r.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...n,...a}}}}function UBe(s){return Object.fromEntries(Object.entries(s).filter(([t,r])=>t==="attrs"&&GHt(r)?!1:r!=null))}function KHt(s,t){var r;const n=oot(s),{nodeExtensions:a,markExtensions:i}=mxe(s),l=(r=a.find(d=>ba(d,"topNode")))===null||r===void 0?void 0:r.name,o=Object.fromEntries(a.map(d=>{const h=n.filter(N=>N.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},x=s.reduce((N,S)=>{const T=ba(S,"extendNodeSchema",m);return{...N,...T?T(d):{}}},{}),g=UBe({...x,content:to(ba(d,"content",m)),marks:to(ba(d,"marks",m)),group:to(ba(d,"group",m)),inline:to(ba(d,"inline",m)),atom:to(ba(d,"atom",m)),selectable:to(ba(d,"selectable",m)),draggable:to(ba(d,"draggable",m)),code:to(ba(d,"code",m)),whitespace:to(ba(d,"whitespace",m)),linebreakReplacement:to(ba(d,"linebreakReplacement",m)),defining:to(ba(d,"defining",m)),isolating:to(ba(d,"isolating",m)),attrs:Object.fromEntries(h.map(N=>{var S;return[N.name,{default:(S=N==null?void 0:N.attribute)===null||S===void 0?void 0:S.default}]}))}),v=to(ba(d,"parseHTML",m));v&&(g.parseDOM=v.map(N=>$Be(N,h)));const j=ba(d,"renderHTML",m);j&&(g.toDOM=N=>j({node:N,HTMLAttributes:xNe(N,h)}));const b=ba(d,"renderText",m);return b&&(g.toText=b),[d.name,g]})),c=Object.fromEntries(i.map(d=>{const h=n.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},x=s.reduce((b,N)=>{const S=ba(N,"extendMarkSchema",m);return{...b,...S?S(d):{}}},{}),g=UBe({...x,inclusive:to(ba(d,"inclusive",m)),excludes:to(ba(d,"excludes",m)),group:to(ba(d,"group",m)),spanning:to(ba(d,"spanning",m)),code:to(ba(d,"code",m)),attrs:Object.fromEntries(h.map(b=>{var N;return[b.name,{default:(N=b==null?void 0:b.attribute)===null||N===void 0?void 0:N.default}]}))}),v=to(ba(d,"parseHTML",m));v&&(g.parseDOM=v.map(b=>$Be(b,h)));const j=ba(d,"renderHTML",m);return j&&(g.toDOM=b=>j({mark:b,HTMLAttributes:xNe(b,h)})),[d.name,g]}));return new Wat({topNode:l,nodes:o,marks:c})}function dbe(s,t){return t.nodes[s]||t.marks[s]||null}function qBe(s,t){return Array.isArray(t)?t.some(r=>(typeof r=="string"?r:r.name)===s.name):t}function eTe(s,t){const r=Y5.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(r),a.innerHTML}const YHt=(s,t=500)=>{let r="";const n=s.parentOffset;return s.parent.nodesBetween(Math.max(0,n-t),n,(a,i,l,o)=>{var c,d;const h=((d=(c=a.type.spec).toText)===null||d===void 0?void 0:d.call(c,{node:a,pos:i,parent:l,index:o}))||a.textContent||"%leaf%";r+=a.isAtom&&!a.isText?h:h.slice(0,Math.max(0,n-i))}),r};function tTe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class fxe{constructor(t){this.find=t.find,this.handler=t.handler}}const ZHt=(s,t)=>{if(tTe(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 dU(s){var t;const{editor:r,from:n,to:a,text:i,rules:l,plugin:o}=s,{view:c}=r;if(c.composing)return!1;const d=c.state.doc.resolve(n);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(x=>x.type.spec.code))return!1;let h=!1;const m=YHt(d)+i;return l.forEach(x=>{if(h)return;const g=ZHt(m,x.find);if(!g)return;const v=c.state.tr,j=uxe({state:c.state,transaction:v}),b={from:n-(g[0].length-i.length),to:a},{commands:N,chain:S,can:T}=new hxe({editor:r,state:j});x.handler({state:j,range:b,match:g,commands:N,chain:S,can:T})===null||!v.steps.length||(v.setMeta(o,{transform:v,from:n,to:a,text:i}),c.dispatch(v),h=!0)}),h}function XHt(s){const{editor:t,rules:r}=s,n=new sh({state:{init(){return null},apply(a,i,l){const o=a.getMeta(n);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:h}=c;typeof h=="string"?h=h:h=eTe(an.from(h),l.schema);const{from:m}=c,x=m+h.length;dU({editor:t,from:m,to:x,text:h,rules:r,plugin:n})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return dU({editor:t,from:i,to:l,text:o,rules:r,plugin:n})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&dU({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?dU({editor:t,from:l.pos,to:l.pos,text:` `,rules:r,plugin:n}):!1}},isInputRules:!0});return n}function QHt(s){return Object.prototype.toString.call(s).slice(8,-1)}function uU(s){return QHt(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function pxe(s,t){const r={...s};return uU(s)&&uU(t)&&Object.keys(t).forEach(n=>{uU(t[n])&&uU(s[n])?r[n]=pxe(s[n],t[n]):r[n]=t[n]}),r}class m0{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=to(ba(this,"addOptions",{name:this.name}))),this.storage=to(ba(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new m0(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>pxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new m0(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=to(ba(r,"addOptions",{name:r.name})),r.storage=to(ba(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 JHt(s){return typeof s=="number"}class eGt{constructor(t){this.find=t.find,this.handler=t.handler}}const tGt=(s,t,r)=>{if(tTe(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 sGt(s){const{editor:t,state:r,from:n,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:h}=new hxe({editor:t,state:r}),m=[];return r.doc.nodesBetween(n,a,(g,v)=>{if(!g.isTextblock||g.type.spec.code)return;const j=Math.max(n,v),b=Math.min(a,v+g.content.size),N=g.textBetween(j-v,b-v,void 0,"");tGt(N,i.find,l).forEach(T=>{if(T.index===void 0)return;const A=j+T.index+1,P=A+T[0].length,D={from:r.tr.mapping.map(A),to:r.tr.mapping.map(P)},B=i.handler({state:r,range:D,match:T,commands:c,chain:d,can:h,pasteEvent:l,dropEvent:o});m.push(B)})}),m.every(g=>g!==null)}let hU=null;const rGt=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 nGt(s){const{editor:t,rules:r}=s;let n=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:h,from:m,to:x,rule:g,pasteEvt:v})=>{const j=h.tr,b=uxe({state:h,transaction:j});if(!(!sGt({editor:t,state:b,from:Math.max(m-1,0),to:x.b-1,rule:g,pasteEvent:v,dropEvent:o})||!j.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,j}};return r.map(h=>new sh({view(m){const x=v=>{var j;n=!((j=m.dom.parentElement)===null||j===void 0)&&j.contains(v.target)?m.dom.parentElement:null,n&&(hU=t)},g=()=>{hU&&(hU=null)};return window.addEventListener("dragstart",x),window.addEventListener("dragend",g),{destroy(){window.removeEventListener("dragstart",x),window.removeEventListener("dragend",g)}}},props:{handleDOMEvents:{drop:(m,x)=>{if(i=n===m.dom.parentElement,o=x,!i){const g=hU;g!=null&&g.isEditable&&setTimeout(()=>{const v=g.state.selection;v&&g.commands.deleteRange({from:v.from,to:v.to})},10)}return!1},paste:(m,x)=>{var g;const v=(g=x.clipboardData)===null||g===void 0?void 0:g.getData("text/html");return l=x,a=!!(v!=null&&v.includes("data-pm-slice")),!1}}},appendTransaction:(m,x,g)=>{const v=m[0],j=v.getMeta("uiEvent")==="paste"&&!a,b=v.getMeta("uiEvent")==="drop"&&!i,N=v.getMeta("applyPasteRules"),S=!!N;if(!j&&!b&&!S)return;if(S){let{text:P}=N;typeof P=="string"?P=P:P=eTe(an.from(P),g.schema);const{from:D}=N,B=D+P.length,z=rGt(P);return c({rule:h,state:g,from:D,to:{b:B},pasteEvt:z})}const T=x.doc.content.findDiffStart(g.doc.content),A=x.doc.content.findDiffEnd(g.doc.content);if(!(!JHt(T)||!A||T===A.b))return c({rule:h,state:g,from:T,to:A,pasteEvt:l})}}))}function aGt(s){const t=s.filter((r,n)=>s.indexOf(r)!==n);return Array.from(new Set(t))}class LA{constructor(t,r){this.splittableMarks=[],this.editor=r,this.extensions=LA.resolve(t),this.schema=KHt(this.extensions,r),this.setupExtensions()}static resolve(t){const r=LA.sort(LA.flatten(t)),n=aGt(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=ba(r,"addExtensions",n);return a?[r,...this.flatten(a())]:r}).flat(10)}static sort(t){return t.sort((n,a)=>{const i=ba(n,"priority")||100,l=ba(a,"priority")||100;return i>l?-1:i{const n={name:r.name,options:r.options,storage:r.storage,editor:this.editor,type:dbe(r.name,this.schema)},a=ba(r,"addCommands",n);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,r=LA.sort([...this.extensions].reverse()),n=[],a=[],i=r.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:dbe(l.name,this.schema)},c=[],d=ba(l,"addKeyboardShortcuts",o);let h={};if(l.type==="mark"&&ba(l,"exitable",o)&&(h.ArrowRight=()=>m0.handleExit({editor:t,mark:l})),d){const j=Object.fromEntries(Object.entries(d()).map(([b,N])=>[b,()=>N({editor:t})]));h={...h,...j}}const m=NHt(h);c.push(m);const x=ba(l,"addInputRules",o);qBe(l,t.options.enableInputRules)&&x&&n.push(...x());const g=ba(l,"addPasteRules",o);qBe(l,t.options.enablePasteRules)&&g&&a.push(...g());const v=ba(l,"addProseMirrorPlugins",o);if(v){const j=v();c.push(...j)}return c}).flat();return[XHt({editor:t,rules:n}),...nGt({editor:t,rules:a}),...i]}get attributes(){return oot(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:r}=mxe(this.extensions);return Object.fromEntries(r.filter(n=>!!ba(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:Dh(n.name,this.schema)},l=ba(n,"addNodeView",i);if(!l)return[];const o=(c,d,h,m,x)=>{const g=xNe(c,a);return l()({node:c,view:d,getPos:h,decorations:m,innerDecorations:x,editor:t,extension:n,HTMLAttributes:g})};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:dbe(t.name,this.schema)};t.type==="mark"&&(!((r=to(ba(t,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(t.name);const a=ba(t,"onBeforeCreate",n),i=ba(t,"onCreate",n),l=ba(t,"onUpdate",n),o=ba(t,"onSelectionUpdate",n),c=ba(t,"onTransaction",n),d=ba(t,"onFocus",n),h=ba(t,"onBlur",n),m=ba(t,"onDestroy",n);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),h&&this.editor.on("blur",h),m&&this.editor.on("destroy",m)})}}class hm{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=to(ba(this,"addOptions",{name:this.name}))),this.storage=to(ba(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new hm(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>pxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new hm({...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=to(ba(r,"addOptions",{name:r.name})),r.storage=to(ba(r,"addStorage",{name:r.name,options:r.options})),r}}function cot(s,t,r){const{from:n,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=r||{};let o="";return s.nodesBetween(n,a,(c,d,h,m)=>{var x;c.isBlock&&d>n&&(o+=i);const g=l==null?void 0:l[c.type.name];if(g)return h&&(o+=g({node:c,pos:d,parent:h,index:m,range:t})),!1;c.isText&&(o+=(x=c==null?void 0:c.text)===null||x===void 0?void 0:x.slice(Math.max(n,d)-d,a-d))}),o}function dot(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,r])=>[t,r.spec.toText]))}const iGt=hm.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new sh({key:new qm("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:r}=s,{doc:n,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(h=>h.$from.pos)),o=Math.max(...i.map(h=>h.$to.pos)),c=dot(r);return cot(n,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),oGt=()=>({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),lGt=(s=!1)=>({commands:t})=>t.setContent("",s),cGt=()=>({state:s,tr:t,dispatch:r})=>{const{selection:n}=t,{ranges:a}=n;return r&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:h}=t,m=d.resolve(h.map(c)),x=d.resolve(h.map(c+o.nodeSize)),g=m.blockRange(x);if(!g)return;const v=PP(g);if(o.type.isTextblock){const{defaultType:j}=m.parent.contentMatchAt(m.index());t.setNodeMarkup(g.start,j)}(v||v===0)&&t.lift(g,v)})}),!0},dGt=s=>t=>s(t),uGt=()=>({state:s,dispatch:t})=>rot(s,t),hGt=(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 Ya(n.doc.resolve(Math.max(l-1,0)))),!0},mGt=()=>({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},fGt=s=>({tr:t,state:r,dispatch:n})=>{const a=Dh(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},pGt=s=>({tr:t,dispatch:r})=>{const{from:n,to:a}=s;return r&&t.delete(n,a),!0},xGt=()=>({state:s,dispatch:t})=>Y5e(s,t),gGt=()=>({commands:s})=>s.keyboardShortcut("Enter"),yGt=()=>({state:s,dispatch:t})=>AHt(s,t);function mhe(s,t,r={strict:!0}){const n=Object.keys(t);return n.length?n.every(a=>r.strict?t[a]===s[a]:tTe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function uot(s,t,r={}){return s.find(n=>n.type===t&&mhe(Object.fromEntries(Object.keys(r).map(a=>[a,n.attrs[a]])),r))}function VBe(s,t,r={}){return!!uot(s,t,r)}function sTe(s,t,r){var n;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(h=>h.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(h=>h.type===t)||(r=r||((n=a.node.marks[0])===null||n===void 0?void 0:n.attrs),!uot([...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&&VBe([...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=Q2(s,n.schema),{doc:l,selection:o}=r,{$from:c,from:d,to:h}=o;if(a){const m=sTe(c,i,t);if(m&&m.from<=d&&m.to>=h){const x=Ya.create(l,m.from,m.to);r.setSelection(x)}}return!0},bGt=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=()=>{(fhe()||HBe())&&n.dom.focus(),requestAnimationFrame(()=>{r.isDestroyed||(n.focus(),_Gt()&&!fhe()&&!HBe()&&n.dom.focus({preventScroll:!0}))})};if(n.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!hot(r.state.selection))return l(),!0;const o=mot(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},jGt=(s,t)=>r=>s.every((n,a)=>t(n,{...r,index:a})),NGt=(s,t)=>({tr:r,commands:n})=>n.insertContentAt({from:r.selection.from,to:r.selection.to},s,t),fot=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&&fot(n)}return s};function mU(s){const t=`${s}`,r=new window.DOMParser().parseFromString(t,"text/html").body;return fot(r)}function xF(s,t,r){if(s instanceof l2||s instanceof an)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 an.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),xF("",t,r)}if(a){if(r.errorOnInvalidContent){let l=!1,o="";const c=new Wat({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?t8.fromSchema(c).parseSlice(mU(s),r.parseOptions):t8.fromSchema(c).parse(mU(s),r.parseOptions),r.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=t8.fromSchema(t);return r.slice?i.parseSlice(mU(s),r.parseOptions).content:i.parse(mU(s),r.parseOptions)}return xF("",t,r)}function kGt(s,t,r){const n=s.steps.length-1;if(n{l===0&&(l=h)}),s.setSelection(vi.near(s.doc.resolve(l),r))}const SGt=s=>!("type"in s),CGt=(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{xF(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{o=xF(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=r.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(b){return c(b),!1}let{from:h,to:m}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},x=!0,g=!0;if((SGt(o)?o:[o]).forEach(b=>{b.check(),x=x?b.isText&&b.marks.length===0:!1,g=g?b.isBlock:!1}),h===m&&g){const{parent:b}=n.doc.resolve(h);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(h-=1,m+=1)}let j;if(x){if(Array.isArray(t))j=t.map(b=>b.text||"").join("");else if(t instanceof an){let b="";t.forEach(N=>{N.text&&(b+=N.text)}),j=b}else typeof t=="object"&&t&&t.text?j=t.text:j=t;n.insertText(j,h,m)}else j=o,n.replaceWith(h,m,j);r.updateSelection&&kGt(n,n.steps.length-1,-1),r.applyInputRules&&n.setMeta("applyInputRules",{from:h,text:j}),r.applyPasteRules&&n.setMeta("applyPasteRules",{from:h,text:j})}return!0},TGt=()=>({state:s,dispatch:t})=>CHt(s,t),EGt=()=>({state:s,dispatch:t})=>THt(s,t),AGt=()=>({state:s,dispatch:t})=>Zit(s,t),MGt=()=>({state:s,dispatch:t})=>eot(s,t),IGt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=ixe(s.doc,s.selection.$from.pos,-1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},PGt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=ixe(s.doc,s.selection.$from.pos,1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},LGt=()=>({state:s,dispatch:t})=>kHt(s,t),DGt=()=>({state:s,dispatch:t})=>SHt(s,t);function pot(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function RGt(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=RGt(s).split(/-(?!$)/),l=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{r.someProp("handleKeyDown",d=>d(r,o))});return c==null||c.steps.forEach(d=>{const h=d.map(n.mapping);h&&a&&n.maybeStep(h)}),!0};function gF(s,t,r={}){const{from:n,to:a,empty:i}=s.selection,l=t?Dh(t,s.schema):null,o=[];s.doc.nodesBetween(n,a,(m,x)=>{if(m.isText)return;const g=Math.max(n,x),v=Math.min(a,x+m.nodeSize);o.push({node:m,from:g,to:v})});const c=a-n,d=o.filter(m=>l?l.name===m.node.type.name:!0).filter(m=>mhe(m.node.attrs,r,{strict:!1}));return i?!!d.length:d.reduce((m,x)=>m+x.to-x.from,0)>=c}const FGt=(s,t={})=>({state:r,dispatch:n})=>{const a=Dh(s,r.schema);return gF(r,a,t)?EHt(r,n):!1},BGt=()=>({state:s,dispatch:t})=>not(s,t),zGt=s=>({state:t,dispatch:r})=>{const n=Dh(s,t.schema);return $Ht(n)(t,r)},$Gt=()=>({state:s,dispatch:t})=>sot(s,t);function xxe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function GBe(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 UGt=(s,t)=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=xxe(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=Dh(s,n.schema)),o==="mark"&&(l=Q2(s,n.schema)),a&&r.selection.ranges.forEach(c=>{n.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,h)=>{i&&i===d.type&&r.setNodeMarkup(h,void 0,GBe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(m=>{l===m.type&&r.addMark(h,h+d.nodeSize,l.create(GBe(m.attrs,t)))})})}),!0):!1},qGt=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),VGt=()=>({tr:s,dispatch:t})=>{if(t){const r=new jx(s.doc);s.setSelection(r)}return!0},HGt=()=>({state:s,dispatch:t})=>Qit(s,t),GGt=()=>({state:s,dispatch:t})=>tot(s,t),WGt=()=>({state:s,dispatch:t})=>PHt(s,t),KGt=()=>({state:s,dispatch:t})=>RHt(s,t),YGt=()=>({state:s,dispatch:t})=>DHt(s,t);function gNe(s,t,r={},n={}){return xF(s,t,{slice:!1,parseOptions:r,errorOnInvalidContent:n.errorOnInvalidContent})}const ZGt=(s,t=!1,r={},n={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:h}=i;if(r.preserveWhitespace!=="full"){const m=gNe(s,a.schema,r,{errorOnInvalidContent:(c=n.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,h.content.size,m).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:h.content.size},s,{parseOptions:r,errorOnInvalidContent:(d=n.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function xot(s,t){const r=Q2(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 XGt(s,t){const r=new O5e(s);return t.forEach(n=>{n.steps.forEach(a=>{r.step(a)})}),r}function QGt(s){for(let t=0;t{r(a)&&n.push({node:a,pos:i})}),n}function got(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 rTe(s){return t=>got(t.$from,s)}function eWt(s,t){const r={from:0,to:s.content.size};return cot(s,r,t)}function tWt(s,t){const r=Dh(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 yot(s,t){const r=xxe(typeof t=="string"?t:t.name,s.schema);return r==="node"?tWt(s,t):r==="mark"?xot(s,t):{}}function sWt(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 rWt(s){const t=sWt(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 nWt(s){const{mapping:t,steps:r}=s,n=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=r[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),h=t.slice(i).map(c),m=t.invert().map(d,-1),x=t.invert().map(h);n.push({oldRange:{from:m,to:x},newRange:{from:d,to:h}})})}),rWt(n)}function nTe(s,t,r){const n=[];return s===t?r.resolve(s).marks().forEach(a=>{const i=r.resolve(s),l=sTe(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 Cde(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 yNe(s,t,r={}){const{empty:n,ranges:a}=s.selection,i=t?Q2(t,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(m=>i?i.name===m.type.name:!0).find(m=>mhe(m.attrs,r,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:m,$to:x})=>{const g=m.pos,v=x.pos;s.doc.nodesBetween(g,v,(j,b)=>{if(!j.isText&&!j.marks.length)return;const N=Math.max(g,b),S=Math.min(v,b+j.nodeSize),T=S-N;l+=T,o.push(...j.marks.map(A=>({mark:A,from:N,to:S})))})}),l===0)return!1;const c=o.filter(m=>i?i.name===m.mark.type.name:!0).filter(m=>mhe(m.mark.attrs,r,{strict:!1})).reduce((m,x)=>m+x.to-x.from,0),d=o.filter(m=>i?m.mark.type!==i&&m.mark.type.excludes(i):!0).reduce((m,x)=>m+x.to-x.from,0);return(c>0?c+d:c)>=l}function aWt(s,t,r={}){if(!t)return gF(s,null,r)||yNe(s,null,r);const n=xxe(t,s.schema);return n==="node"?gF(s,t,r):n==="mark"?yNe(s,t,r):!1}function WBe(s,t){const{nodeExtensions:r}=mxe(t),n=r.find(l=>l.name===s);if(!n)return!1;const a={name:n.name,options:n.options,storage:n.storage},i=to(ba(n,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function aTe(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&&(aTe(i,{ignoreWhitespace:r,checkChildren:t})||(a=!1))}),a}return!1}function iWt(s){return s instanceof Za}function oWt(s,t,r){var n;const{selection:a}=t;let i=null;if(hot(a)&&(i=a.$cursor),i){const o=(n=s.storedMarks)!==null&&n!==void 0?n:i.marks();return!!r.isInSet(o)||!o.some(c=>c.type.excludes(r))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(r):!1;return s.doc.nodesBetween(o.pos,c.pos,(h,m,x)=>{if(d)return!1;if(h.isInline){const g=!x||x.type.allowsMarkType(r),v=!!r.isInSet(h.marks)||!h.marks.some(j=>j.type.excludes(r));d=g&&v}return!d}),d})}const lWt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{const{selection:i}=r,{empty:l,ranges:o}=i,c=Q2(s,n.schema);if(a)if(l){const d=xot(n,c);r.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const h=d.$from.pos,m=d.$to.pos;n.doc.nodesBetween(h,m,(x,g)=>{const v=Math.max(g,h),j=Math.min(g+x.nodeSize,m);x.marks.find(N=>N.type===c)?x.marks.forEach(N=>{c===N.type&&r.addMark(v,j,c.create({...N.attrs,...t}))}):r.addMark(v,j,c.create(t))})});return oWt(n,r,c)},cWt=(s,t)=>({tr:r})=>(r.setMeta(s,t),!0),dWt=(s,t={})=>({state:r,dispatch:n,chain:a})=>{const i=Dh(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})=>zBe(i,{...l,...t})(r)?!0:o.clearNodes()).command(({state:o})=>zBe(i,{...l,...t})(o,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},uWt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,a=Y4(s,0,n.content.size),i=Za.create(n,a);t.setSelection(i)}return!0},hWt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Ya.atStart(n).from,o=Ya.atEnd(n).to,c=Y4(a,l,o),d=Y4(i,l,o),h=Ya.create(n,c,d);t.setSelection(h)}return!0},mWt=s=>({state:t,dispatch:r})=>{const n=Dh(s,t.schema);return VHt(n)(t,r)};function KBe(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 fWt=({keepMarks:s=!0}={})=>({tr:t,state:r,dispatch:n,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,h=Cde(d,o.node().type.name,o.node().attrs);if(i instanceof Za&&i.node.isBlock)return!o.parentOffset||!i_(l,o.pos)?!1:(n&&(s&&KBe(r,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,x=o.depth===0?void 0:QGt(o.node(-1).contentMatchAt(o.indexAfter(-1)));let g=m&&x?[{type:x,attrs:h}]:void 0,v=i_(t.doc,t.mapping.map(o.pos),1,g);if(!g&&!v&&i_(t.doc,t.mapping.map(o.pos),1,x?[{type:x}]:void 0)&&(v=!0,g=x?[{type:x,attrs:h}]:void 0),n){if(v&&(i instanceof Ya&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,g),x&&!m&&!o.parentOffset&&o.parent.type!==x)){const j=t.mapping.map(o.before()),b=t.doc.resolve(j);o.node(-1).canReplaceWith(b.index(),b.index()+1,x)&&t.setNodeMarkup(t.mapping.map(o.before()),x)}s&&KBe(r,a.extensionManager.splittableMarks),t.scrollIntoView()}return v},pWt=(s,t={})=>({tr:r,state:n,dispatch:a,editor:i})=>{var l;const o=Dh(s,n.schema),{$from:c,$to:d}=n.selection,h=n.selection.node;if(h&&h.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==o)return!1;const x=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let N=an.empty;const S=c.index(-1)?1:c.index(-2)?2:3;for(let z=c.depth-S;z>=c.depth-3;z-=1)N=an.from(c.node(z).copy(N));const T=c.indexAfter(-1){if(B>-1)return!1;z.isTextblock&&z.content.size===0&&(B=F+1)}),B>-1&&r.setSelection(Ya.near(r.doc.resolve(B))),r.scrollIntoView()}return!0}const g=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,v={...Cde(x,m.type.name,m.attrs),...t},j={...Cde(x,c.node().type.name,c.node().attrs),...t};r.delete(c.pos,d.pos);const b=g?[{type:o,attrs:v},{type:g,attrs:j}]:[{type:o,attrs:v}];if(!i_(r.doc,c.pos,2))return!1;if(a){const{selection:N,storedMarks:S}=n,{splittableMarks:T}=i.extensionManager,A=S||N.$to.parentOffset&&N.$from.marks();if(r.split(c.pos,2,b).scrollIntoView(),!A||!a)return!0;const P=A.filter(D=>T.includes(D.type.name));r.ensureMarks(P)}return!0},ube=(s,t)=>{const r=rTe(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)&&Z2(s.doc,r.pos)&&s.join(r.pos),!0},hbe=(s,t)=>{const r=rTe(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)&&Z2(s.doc,n)&&s.join(n),!0},xWt=(s,t,r,n={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:h})=>{const{extensions:m,splittableMarks:x}=a.extensionManager,g=Dh(s,l.schema),v=Dh(t,l.schema),{selection:j,storedMarks:b}=l,{$from:N,$to:S}=j,T=N.blockRange(S),A=b||j.$to.parentOffset&&j.$from.marks();if(!T)return!1;const P=rTe(D=>WBe(D.type.name,m))(j);if(T.depth>=1&&P&&T.depth-P.depth<=1){if(P.node.type===g)return d.liftListItem(v);if(WBe(P.node.type.name,m)&&g.validContent(P.node.content)&&o)return c().command(()=>(i.setNodeMarkup(P.pos,g),!0)).command(()=>ube(i,g)).command(()=>hbe(i,g)).run()}return!r||!A||!o?c().command(()=>h().wrapInList(g,n)?!0:d.clearNodes()).wrapInList(g,n).command(()=>ube(i,g)).command(()=>hbe(i,g)).run():c().command(()=>{const D=h().wrapInList(g,n),B=A.filter(z=>x.includes(z.type.name));return i.ensureMarks(B),D?!0:d.clearNodes()}).wrapInList(g,n).command(()=>ube(i,g)).command(()=>hbe(i,g)).run()},gWt=(s,t={},r={})=>({state:n,commands:a})=>{const{extendEmptyMarkRange:i=!1}=r,l=Q2(s,n.schema);return yNe(n,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},yWt=(s,t,r={})=>({state:n,commands:a})=>{const i=Dh(s,n.schema),l=Dh(t,n.schema),o=gF(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})},vWt=(s,t={})=>({state:r,commands:n})=>{const a=Dh(s,r.schema);return gF(r,a,t)?n.lift(a):n.wrapIn(a,t)},bWt=()=>({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},_Wt=()=>({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},wWt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=r,c=Q2(s,n.schema),{$from:d,empty:h,ranges:m}=o;if(!a)return!0;if(h&&l){let{from:x,to:g}=o;const v=(i=d.marks().find(b=>b.type===c))===null||i===void 0?void 0:i.attrs,j=sTe(d,c,v);j&&(x=j.from,g=j.to),r.removeMark(x,g,c)}else m.forEach(x=>{r.removeMark(x.$from.pos,x.$to.pos,c)});return r.removeStoredMark(c),!0},jWt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=xxe(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=Dh(s,n.schema)),o==="mark"&&(l=Q2(s,n.schema)),a&&r.selection.ranges.forEach(c=>{const d=c.$from.pos,h=c.$to.pos;let m,x,g,v;r.selection.empty?n.doc.nodesBetween(d,h,(j,b)=>{i&&i===j.type&&(g=Math.max(b,d),v=Math.min(b+j.nodeSize,h),m=b,x=j)}):n.doc.nodesBetween(d,h,(j,b)=>{b=d&&b<=h&&(i&&i===j.type&&r.setNodeMarkup(b,void 0,{...j.attrs,...t}),l&&j.marks.length&&j.marks.forEach(N=>{if(l===N.type){const S=Math.max(b,d),T=Math.min(b+j.nodeSize,h);r.addMark(S,T,l.create({...N.attrs,...t}))}}))}),x&&(m!==void 0&&r.setNodeMarkup(m,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(j=>{l===j.type&&r.addMark(g,v,l.create({...j.attrs,...t}))}))}),!0):!1},NWt=(s,t={})=>({state:r,dispatch:n})=>{const a=Dh(s,r.schema);return OHt(a,t)(r,n)},kWt=(s,t={})=>({state:r,dispatch:n})=>{const a=Dh(s,r.schema);return FHt(a,t)(r,n)};var SWt=Object.freeze({__proto__:null,blur:oGt,clearContent:lGt,clearNodes:cGt,command:dGt,createParagraphNear:uGt,cut:hGt,deleteCurrentNode:mGt,deleteNode:fGt,deleteRange:pGt,deleteSelection:xGt,enter:gGt,exitCode:yGt,extendMarkRange:vGt,first:bGt,focus:wGt,forEach:jGt,insertContent:NGt,insertContentAt:CGt,joinBackward:AGt,joinDown:EGt,joinForward:MGt,joinItemBackward:IGt,joinItemForward:PGt,joinTextblockBackward:LGt,joinTextblockForward:DGt,joinUp:TGt,keyboardShortcut:OGt,lift:FGt,liftEmptyBlock:BGt,liftListItem:zGt,newlineInCode:$Gt,resetAttributes:UGt,scrollIntoView:qGt,selectAll:VGt,selectNodeBackward:HGt,selectNodeForward:GGt,selectParentNode:WGt,selectTextblockEnd:KGt,selectTextblockStart:YGt,setContent:ZGt,setMark:lWt,setMeta:cWt,setNode:dWt,setNodeSelection:uWt,setTextSelection:hWt,sinkListItem:mWt,splitBlock:fWt,splitListItem:pWt,toggleList:xWt,toggleMark:gWt,toggleNode:yWt,toggleWrap:vWt,undoInputRule:bWt,unsetAllMarks:_Wt,unsetMark:wWt,updateAttributes:jWt,wrapIn:NWt,wrapInList:kWt});const CWt=hm.create({name:"commands",addCommands(){return{...SWt}}}),TWt=hm.create({name:"drop",addProseMirrorPlugins(){return[new sh({key:new qm("tiptapDrop"),props:{handleDrop:(s,t,r,n)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:r,moved:n})}}})]}}),EWt=hm.create({name:"editable",addProseMirrorPlugins(){return[new sh({key:new qm("editable"),props:{editable:()=>this.editor.options.editable}})]}}),AWt=new qm("focusEvents"),MWt=hm.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new sh({key:AWt,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}}}})]}}),IWt=hm.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:h,$anchor:m}=c,{pos:x,parent:g}=m,v=m.parent.isTextblock&&x>0?o.doc.resolve(x-1):m,j=v.parent.type.spec.isolating,b=m.pos-m.parentOffset,N=j&&v.parent.childCount===1?b===m.pos:vi.atStart(d).from===x;return!h||!g.type.isTextblock||g.textContent.length||!N||N&&m.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...n},i={...n,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return fhe()||pot()?i:a},addProseMirrorPlugins(){return[new sh({key:new qm("clearDocument"),appendTransaction:(s,t,r)=>{if(s.some(j=>j.getMeta("composition")))return;const n=s.some(j=>j.docChanged)&&!t.doc.eq(r.doc),a=s.some(j=>j.getMeta("preventClearDocument"));if(!n||a)return;const{empty:i,from:l,to:o}=t.selection,c=vi.atStart(t.doc).from,d=vi.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!aTe(r.doc))return;const x=r.tr,g=uxe({state:r,transaction:x}),{commands:v}=new hxe({editor:this.editor,state:g});if(v.clearNodes(),!!x.steps.length)return x}})]}}),PWt=hm.create({name:"paste",addProseMirrorPlugins(){return[new sh({key:new qm("tiptapPaste"),props:{handlePaste:(s,t,r)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:r})}}})]}}),LWt=hm.create({name:"tabindex",addProseMirrorPlugins(){return[new sh({key:new qm("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class R4{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 R4(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 R4(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 R4(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 R4(o,this.editor,a,a?r:null);a&&(c.actualDepth=this.depth+1),t.push(new R4(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 DWt=`.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 RWt(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 OWt extends HHt{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=RWt(DWt,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=lot(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?[EWt,iGt.configure({blockSeparator:(r=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||r===void 0?void 0:r.blockSeparator}),CWt,MWt,IWt,LWt,TWt,PWt].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 LA(a,this)}createCommandManager(){this.commandManager=new hxe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let r;try{r=gNe(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=gNe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const n=mot(r,this.options.autofocus);this.view=new Kit(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:PA.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 yot(this.state,t)}isActive(t,r){const n=typeof t=="string"?t:null,a=typeof t=="string"?r:t;return aWt(this.state,n,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return eTe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:r=` `,textSerializers:n={}}=t||{};return eWt(this.state.doc,{blockSeparator:r,textSerializers:{...dot(this.schema),...n}})}get isEmpty(){return aTe(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 R4(r,this)}get $doc(){return this.$pos(0)}}function kI(s){return new fxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=to(s.getAttributes,void 0,n);if(a===!1||a===null)return null;const{tr:i}=t,l=n[n.length-1],o=n[0];if(l){const c=o.search(/\S/),d=r.from+o.indexOf(l),h=d+l.length;if(nTe(r.from,r.to,t.doc).filter(g=>g.mark.type.excluded.find(j=>j===s.type&&j!==g.mark.type)).filter(g=>g.to>d).length)return null;hr.from&&i.delete(r.from+c,d);const x=r.from+c+l.length;i.addMark(r.from+c,x,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function vot(s){return new fxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=to(s.getAttributes,void 0,n)||{},{tr:i}=t,l=r.from;let o=r.to;const c=s.type.create(a);if(n[1]){const d=n[0].lastIndexOf(n[1]);let h=l+d;h>o?h=o:o=h+n[1].length;const m=n[0][n[0].length-1];i.insertText(m,l+n[0].length-1),i.replaceWith(h,o,c)}else if(n[0]){const d=s.type.isInline?l:l-1;i.insert(d,s.type.create(a)).delete(i.mapping.map(l),i.mapping.map(o))}i.scrollIntoView()}})}function vNe(s){return new fxe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=t.doc.resolve(r.from),i=to(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 yF(s){return new fxe({find:s.find,handler:({state:t,range:r,match:n,chain:a})=>{const i=to(s.getAttributes,void 0,n)||{},l=t.tr.delete(r.from,r.to),c=l.doc.resolve(r.from).blockRange(),d=c&&R5e(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:m,storedMarks:x}=t,{splittableMarks:g}=s.editor.extensionManager,v=x||m.$to.parentOffset&&m.$from.marks();if(v){const j=v.filter(b=>g.includes(b.type.name));l.ensureMarks(j)}}if(s.keepAttributes){const m=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,i).run()}const h=l.doc.resolve(r.from-1).nodeBefore;h&&h.type===s.type&&Z2(l.doc,r.from-1)&&(!s.joinPredicate||s.joinPredicate(n,h))&&l.join(r.from-1)}})}let Vm=class bNe{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=to(ba(this,"addOptions",{name:this.name}))),this.storage=to(ba(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new bNe(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>pxe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new bNe(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=to(ba(r,"addOptions",{name:r.name})),r.storage=to(ba(r,"addStorage",{name:r.name,options:r.options})),r}};function S5(s){return new eGt({find:s.find,handler:({state:t,range:r,match:n,pasteEvent:a})=>{const i=to(s.getAttributes,void 0,n,a);if(i===!1||i===null)return null;const{tr:l}=t,o=n[n.length-1],c=n[0];let d=r.to;if(o){const h=c.search(/\S/),m=r.from+c.indexOf(o),x=m+o.length;if(nTe(r.from,r.to,t.doc).filter(v=>v.mark.type.excluded.find(b=>b===s.type&&b!==v.mark.type)).filter(v=>v.to>m).length)return null;xr.from&&l.delete(r.from+h,m),d=r.from+h+o.length,l.addMark(r.from+h,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function FWt(s,t){const{selection:r}=s,{$from:n}=r;if(r instanceof Za){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 BWt(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bot={exports:{}},mbe={};/** * @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 YBe;function zWt(){if(YBe)return mbe;YBe=1;var s=wt;function t(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var r=typeof Object.is=="function"?Object.is:t,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(m,x){var g=x(),v=n({inst:{value:g,getSnapshot:x}}),j=v[0].inst,b=v[1];return i(function(){j.value=g,j.getSnapshot=x,c(j)&&b({inst:j})},[m,g,x]),a(function(){return c(j)&&b({inst:j}),m(function(){c(j)&&b({inst:j})})},[m]),l(g),g}function c(m){var x=m.getSnapshot;m=m.value;try{var g=x();return!r(m,g)}catch{return!0}}function d(m,x){return x()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return mbe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:h,mbe}bot.exports=zWt();var iTe=bot.exports;const $Wt=(...s)=>t=>{s.forEach(r=>{typeof r=="function"?r(t):r&&(r.current=t)})},UWt=({contentComponent:s})=>{const t=iTe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return wt.createElement(wt.Fragment,null,Object.values(t))};function qWt(){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]:$Ye.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 VWt extends wt.Component{constructor(t){var r;super(t),this.editorContentRef=wt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((r=t.editor)===null||r===void 0)&&r.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const r=this.editorContentRef.current;r.append(...t.options.element.childNodes),t.setOptions({element:r}),t.contentComponent=qWt(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const r=document.createElement("div");r.append(...t.options.element.childNodes),t.setOptions({element:r})}render(){const{editor:t,innerRef:r,...n}=this.props;return wt.createElement(wt.Fragment,null,wt.createElement("div",{ref:$Wt(r,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&wt.createElement(UWt,{contentComponent:t.contentComponent}))}}const HWt=k.forwardRef((s,t)=>{const r=wt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return wt.createElement(VWt,{key:r,innerRef:t,...s})}),oTe=wt.memo(HWt);var GWt=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},WWt=BWt(GWt),_ot={exports:{}},fbe={};/** * @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 ZBe;function KWt(){if(ZBe)return fbe;ZBe=1;var s=wt,t=iTe;function r(d,h){return d===h&&(d!==0||1/d===1/h)||d!==d&&h!==h}var n=typeof Object.is=="function"?Object.is:r,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return fbe.useSyncExternalStoreWithSelector=function(d,h,m,x,g){var v=i(null);if(v.current===null){var j={hasValue:!1,value:null};v.current=j}else j=v.current;v=o(function(){function N(D){if(!S){if(S=!0,T=D,D=x(D),g!==void 0&&j.hasValue){var B=j.value;if(g(B,D))return A=B}return A=D}if(B=A,n(T,D))return B;var z=x(D);return g!==void 0&&g(B,z)?B:(T=D,A=z)}var S=!1,T,A,P=m===void 0?null:m;return[function(){return N(h())},P===null?void 0:function(){return N(P())}]},[h,m,x,g]);var b=a(d,v[0],v[1]);return l(function(){j.hasValue=!0,j.value=b},[b]),c(b),b},fbe}_ot.exports=KWt();var YWt=_ot.exports;const ZWt=typeof window<"u"?k.useLayoutEffect:k.useEffect;class XWt{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 QWt(s){var t;const[r]=k.useState(()=>new XWt(s.editor)),n=YWt.useSyncExternalStoreWithSelector(r.subscribe,r.getSnapshot,r.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:WWt);return ZWt(()=>r.watch(s.editor),[s.editor,r]),k.useDebugValue(n),n}const JWt=!1,_Ne=typeof window>"u",eKt=_Ne||!!(typeof window<"u"&&window.next);class lTe{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(){return this.options.current.immediatelyRender===void 0?_Ne||eKt?null:this.createEditor():(this.options.current.immediatelyRender,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 OWt(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?lTe.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 cTe(s={},t=[]){const r=k.useRef(s);r.current=s;const[n]=k.useState(()=>new lTe(r)),a=iTe.useSyncExternalStore(n.subscribe,n.getEditor,n.getServerSnapshot);return k.useDebugValue(a),k.useEffect(n.onRender(t)),QWt({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const tKt=k.createContext({editor:null});tKt.Consumer;const sKt=k.createContext({onDragStart:void 0}),rKt=()=>k.useContext(sKt);wt.forwardRef((s,t)=>{const{onDragStart:r}=rKt(),n=s.as||"div";return wt.createElement(n,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:r,style:{whiteSpace:"normal",...s.style}})});const nKt=/^\s*>\s$/,aKt=Vm.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Zc(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[yF({find:nKt,type:this.type})]}}),iKt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,oKt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,lKt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,cKt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,dKt=m0.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",Zc(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[kI({find:iKt,type:this.type}),kI({find:lKt,type:this.type})]},addPasteRules(){return[S5({find:oKt,type:this.type}),S5({find:cKt,type:this.type})]}}),uKt="listItem",XBe="textStyle",QBe=/^\s*([-+*])\s$/,hKt=Vm.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",Zc(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(uKt,this.editor.getAttributes(XBe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=yF({find:QBe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=yF({find:QBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(XBe),editor:this.editor})),[s]}}),mKt=/(^|[^`])`([^`]+)`(?!`)/,fKt=/(^|[^`])`([^`]+)`(?!`)/g,pKt=m0.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Zc(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[kI({find:mKt,type:this.type})]},addPasteRules(){return[S5({find:fKt,type:this.type})]}}),xKt=/^```([a-z]+)?[\s\n]$/,gKt=/^~~~([a-z]+)?[\s\n]$/,yKt=Vm.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",Zc(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(vi.near(n.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[vNe({find:xKt,type:this.type,getAttributes:s=>({language:s[1]})}),vNe({find:gKt,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new sh({key:new qm("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(Ya.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),vKt=Vm.create({name:"doc",topNode:!0,content:"block+"});function bKt(s={}){return new sh({view(t){return new _Kt(t,s)}})}class _Kt{constructor(t,r){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(n=r.width)!==null&&n!==void 0?n:1,this.color=r.color===!1?void 0:r.color||"black",this.class=r.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:r})=>this.editorView.dom.removeEventListener(t,r))}update(t,r){this.cursorPos!=null&&r.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),r=!t.parent.inlineContent,n,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(r){let m=t.nodeBefore,x=t.nodeAfter;if(m||x){let g=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(g){let v=g.getBoundingClientRect(),j=m?v.bottom:v.top;m&&x&&(j=(j+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*o;n={left:v.left,right:v.right,top:j-b,bottom:j+b}}}}if(!n){let m=this.editorView.coordsAtPos(this.cursorPos),x=this.width/2*l;n={left:m.left-x,right:m.left+x,top:m.top,bottom:m.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",r),this.element.classList.toggle("prosemirror-dropcursor-inline",!r);let d,h;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,h=-pageYOffset;else{let m=c.getBoundingClientRect(),x=m.width/c.offsetWidth,g=m.height/c.offsetHeight;d=m.left-c.scrollLeft*x,h=m.top-c.scrollTop*g}this.element.style.left=(n.left-d)/l+"px",this.element.style.top=(n.top-h)/o+"px",this.element.style.width=(n.right-n.left)/l+"px",this.element.style.height=(n.bottom-n.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let r=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=r&&r.inside>=0&&this.editorView.state.doc.nodeAt(r.inside),a=n&&n.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,r,t):a;if(r&&!i){let l=r.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=nit(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 wKt=hm.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[bKt(this.options)]}});class Id extends vi{constructor(t){super(t,t)}map(t,r){let n=t.resolve(r.map(this.head));return Id.valid(n)?new Id(n):vi.near(n)}content(){return Un.empty}eq(t){return t instanceof Id&&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 Id(t.resolve(r.pos))}getBookmark(){return new dTe(this.anchor)}static valid(t){let r=t.parent;if(r.inlineContent||!jKt(t)||!NKt(t))return!1;let n=r.type.spec.allowGapCursor;if(n!=null)return n;let a=r.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,r,n=!1){e:for(;;){if(!n&&Id.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(Id.valid(c))return c}for(;;){let l=r>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Za.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(Id.valid(o))return o}return null}}}Id.prototype.visible=!1;Id.findFrom=Id.findGapCursorFrom;vi.jsonID("gapcursor",Id);class dTe{constructor(t){this.pos=t}map(t){return new dTe(t.map(this.pos))}resolve(t){let r=t.resolve(this.pos);return Id.valid(r)?new Id(r):vi.near(r)}}function wot(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function jKt(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||wot(a.type))return!0;if(a.inlineContent)return!1}}return!0}function NKt(s){for(let t=s.depth;t>=0;t--){let r=s.indexAfter(t),n=s.node(t);if(r==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||wot(a.type))return!0;if(a.inlineContent)return!1}}return!0}function kKt(){return new sh({props:{decorations:EKt,createSelectionBetween(s,t,r){return t.pos==r.pos&&Id.valid(r)?new Id(r):null},handleClick:CKt,handleKeyDown:SKt,handleDOMEvents:{beforeinput:TKt}}})}const SKt=K5e({ArrowLeft:fU("horiz",-1),ArrowRight:fU("horiz",1),ArrowUp:fU("vert",-1),ArrowDown:fU("vert",1)});function fU(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 Ya){if(!i.endOfTextblock(r)||o.depth==0)return!1;c=!1,o=n.doc.resolve(t>0?o.after():o.before())}let d=Id.findGapCursorFrom(o,t,c);return d?(a&&a(n.tr.setSelection(new Id(d))),!0):!1}}function CKt(s,t,r){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(t);if(!Id.valid(n))return!1;let a=s.posAtCoords({left:r.clientX,top:r.clientY});return a&&a.inside>-1&&Za.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new Id(n))),!0)}function TKt(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof Id))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=an.empty;for(let l=n.length-1;l>=0;l--)a=an.from(n[l].createAndFill(null,a));let i=s.state.tr.replace(r.pos,r.pos,new Un(a,0,0));return i.setSelection(Ya.near(i.doc.resolve(r.pos+1))),s.dispatch(i),!1}function EKt(s){if(!(s.selection instanceof Id))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Md.create(s.doc,[bf.widget(s.selection.head,t,{key:"gapcursor"})])}const AKt=hm.create({name:"gapCursor",addProseMirrorPlugins(){return[kKt()]},extendNodeSchema(s){var t;const r={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=to(ba(s,"allowGapCursor",r)))!==null&&t!==void 0?t:null}}}),MKt=Vm.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",Zc(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:r,editor:n})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=r;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=n.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:h})=>{if(h&&c&&l){const m=c.filter(x=>o.includes(x.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),IKt=Vm.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]}`,Zc(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=>vNe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var phe=200,Ph=function(){};Ph.prototype.append=function(t){return t.length?(t=Ph.from(t),!this.length&&t||t.length=r?Ph.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,r))};Ph.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Ph.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)};Ph.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};Ph.from=function(t){return t instanceof Ph?t:t&&t.length?new jot(t):Ph.empty};var jot=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<=phe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=phe)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}(Ph);Ph.empty=new jot([]);var PKt=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}(Ph);const LKt=500;class Wy{constructor(t,r){this.items=t,this.eventCount=r}popEvent(t,r){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let a,i;r&&(a=this.remapping(n,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],h=[];return this.items.forEach((m,x)=>{if(!m.step){a||(a=this.remapping(n,x+1),i=a.maps.length),i--,h.push(m);return}if(a){h.push(new uv(m.map));let g=m.step.map(a.slice(i)),v;g&&l.maybeStep(g).doc&&(v=l.mapping.maps[l.mapping.maps.length-1],d.push(new uv(v,void 0,void 0,d.length+h.length))),i--,v&&a.appendMap(v,i)}else l.maybeStep(m.step);if(m.selection)return o=a?m.selection.map(a.slice(i)):m.selection,c=new Wy(this.items.slice(0,n).append(h.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,r,n,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let h=0;hRKt&&(o=DKt(o,d),l-=d),new Wy(o.append(i),l)}remapping(t,r){let n=new uF;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 Wy(this.items.append(t.map(r=>new uv(r))),this.eventCount)}rebased(t,r){if(!this.eventCount)return this;let n=[],a=Math.max(0,this.items.length-r),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(x=>{x.selection&&o--},a);let c=r;this.items.forEach(x=>{let g=i.getMirror(--c);if(g==null)return;l=Math.min(l,g);let v=i.maps[g];if(x.step){let j=t.steps[g].invert(t.docs[g]),b=x.selection&&x.selection.map(i.slice(c+1,g));b&&o++,n.push(new uv(v,j,b))}else n.push(new uv(v))},a);let d=[];for(let x=r;xLKt&&(m=m.compress(this.items.length-n.length)),m}emptyItemCount(){let t=0;return this.items.forEach(r=>{r.step||t++}),t}compress(t=this.items.length){let r=this.remapping(0,t),n=r.maps.length,a=[],i=0;return this.items.forEach((l,o)=>{if(o>=t)a.push(l),l.selection&&i++;else if(l.step){let c=l.step.map(r.slice(n)),d=c&&c.getMap();if(n--,d&&r.appendMap(d,n),c){let h=l.selection&&l.selection.map(r.slice(n));h&&i++;let m=new uv(d.invert(),c,h),x,g=a.length-1;(x=a.length&&a[g].merge(m))?a[g]=x:a.push(m)}}else l.map&&n--},this.items.length,0),new Wy(Ph.from(a.reverse()),i)}}Wy.empty=new Wy(Ph.empty,0);function DKt(s,t){let r;return s.forEach((n,a)=>{if(n.selection&&t--==0)return r=a,!1}),s.slice(r)}class uv{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 uv(r.getMap().invert(),r,this.selection)}}}class sj{constructor(t,r,n,a,i){this.done=t,this.undone=r,this.prevRanges=n,this.prevTime=a,this.prevComposition=i}}const RKt=20;function OKt(s,t,r,n){let a=r.getMeta(e5),i;if(a)return a.historyState;r.getMeta(zKt)&&(s=new sj(s.done,s.undone,null,0,-1));let l=r.getMeta("appendedTransaction");if(r.steps.length==0)return s;if(l&&l.getMeta(e5))return l.getMeta(e5).redo?new sj(s.done.addTransform(r,void 0,n,Tde(t)),s.undone,JBe(r.mapping.maps),s.prevTime,s.prevComposition):new sj(s.done,s.undone.addTransform(r,void 0,n,Tde(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||!FKt(r,s.prevRanges)),d=l?pbe(s.prevRanges,r.mapping):JBe(r.mapping.maps);return new sj(s.done.addTransform(r,c?t.selection.getBookmark():void 0,n,Tde(t)),Wy.empty,d,r.time,o??s.prevComposition)}else return(i=r.getMeta("rebased"))?new sj(s.done.rebased(r,i),s.undone.rebased(r,i),pbe(s.prevRanges,r.mapping),s.prevTime,s.prevComposition):new sj(s.done.addMaps(r.mapping.maps),s.undone.addMaps(r.mapping.maps),pbe(s.prevRanges,r.mapping),s.prevTime,s.prevComposition)}function FKt(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 JBe(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 pbe(s,t){if(!s)return null;let r=[];for(let n=0;n{let a=e5.getState(r);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(n){let i=BKt(a,r,s);i&&n(t?i.scrollIntoView():i)}return!0}}const kot=Not(!1,!0),Sot=Not(!0,!0),UKt=hm.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>kot(s,t),redo:()=>({state:s,dispatch:t})=>Sot(s,t)}},addProseMirrorPlugins(){return[$Kt(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),qKt=Vm.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Zc(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!FWt(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}):iWt(r)?i.insertContentAt(a.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({tr:l,dispatch:o})=>{var c;if(o){const{$to:d}=l.selection,h=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(Ya.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Za.create(l.doc,d.pos)):l.setSelection(Ya.create(l.doc,d.pos));else{const m=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();m&&(l.insert(h,m),l.setSelection(Ya.create(l.doc,h+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[vot({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),VKt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,HKt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,GKt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,WKt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,KKt=m0.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",Zc(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[kI({find:VKt,type:this.type}),kI({find:GKt,type:this.type})]},addPasteRules(){return[S5({find:HKt,type:this.type}),S5({find:WKt,type:this.type})]}}),YKt=Vm.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Zc(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)}}}),ZKt="listItem",tze="textStyle",sze=/^(\d+)\.\s$/,XKt=Vm.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",Zc(this.options.HTMLAttributes,r),0]:["ol",Zc(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(ZKt,this.editor.getAttributes(tze)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=yF({find:sze,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=yF({find:sze,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(tze)}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1],editor:this.editor})),[s]}}),QKt=Vm.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Zc(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),JKt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,eYt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,tYt=m0.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",Zc(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[kI({find:JKt,type:this.type})]},addPasteRules(){return[S5({find:eYt,type:this.type})]}}),sYt=Vm.create({name:"text",group:"inline"}),uTe=hm.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(dKt.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(aKt.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(hKt.configure(this.options.bulletList)),this.options.code!==!1&&s.push(pKt.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(yKt.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(vKt.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(wKt.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(AKt.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(MKt.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(IKt.configure(this.options.heading)),this.options.history!==!1&&s.push(UKt.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(qKt.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(KKt.configure(this.options.italic)),this.options.listItem!==!1&&s.push(YKt.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(XKt.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(QKt.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(tYt.configure(this.options.strike)),this.options.text!==!1&&s.push(sYt.configure(this.options.text)),s}}),rYt="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",nYt="ελ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",wNe="numeric",jNe="ascii",NNe="alpha",a8="asciinumeric",SR="alphanumeric",kNe="domain",Cot="emoji",aYt="scheme",iYt="slashscheme",gbe="whitespace";function oYt(s,t){return s in t||(t[s]=[]),t[s]}function Z4(s,t,r){t[wNe]&&(t[a8]=!0,t[SR]=!0),t[jNe]&&(t[a8]=!0,t[NNe]=!0),t[a8]&&(t[SR]=!0),t[NNe]&&(t[SR]=!0),t[SR]&&(t[kNe]=!0),t[Cot]&&(t[kNe]=!0);for(const n in t){const a=oYt(n,r);a.indexOf(s)<0&&a.push(s)}}function lYt(s,t){const r={};for(const n in t)t[n].indexOf(s)>=0&&(r[n]=!0);return r}function ip(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}ip.groups={};ip.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),wd=(s,t,r,n,a)=>s.tr(t,r,n,a),rze=(s,t,r,n,a)=>s.ts(t,r,n,a),un=(s,t,r,n,a)=>s.tt(t,r,n,a),_b="WORD",SNe="UWORD",Tot="ASCIINUMERICAL",Eot="ALPHANUMERICAL",vF="LOCALHOST",CNe="TLD",TNe="UTLD",Ede="SCHEME",mA="SLASH_SCHEME",hTe="NUM",ENe="WS",mTe="NL",i8="OPENBRACE",o8="CLOSEBRACE",xhe="OPENBRACKET",ghe="CLOSEBRACKET",yhe="OPENPAREN",vhe="CLOSEPAREN",bhe="OPENANGLEBRACKET",_he="CLOSEANGLEBRACKET",whe="FULLWIDTHLEFTPAREN",jhe="FULLWIDTHRIGHTPAREN",Nhe="LEFTCORNERBRACKET",khe="RIGHTCORNERBRACKET",She="LEFTWHITECORNERBRACKET",Che="RIGHTWHITECORNERBRACKET",The="FULLWIDTHLESSTHAN",Ehe="FULLWIDTHGREATERTHAN",Ahe="AMPERSAND",Mhe="APOSTROPHE",Ihe="ASTERISK",rj="AT",Phe="BACKSLASH",Lhe="BACKTICK",Dhe="CARET",X4="COLON",fTe="COMMA",Rhe="DOLLAR",hv="DOT",Ohe="EQUALS",pTe="EXCLAMATION",vg="HYPHEN",l8="PERCENT",Fhe="PIPE",Bhe="PLUS",zhe="POUND",c8="QUERY",xTe="QUOTE",Aot="FULLWIDTHMIDDLEDOT",gTe="SEMI",mv="SLASH",d8="TILDE",$he="UNDERSCORE",Mot="EMOJI",Uhe="SYM";var Iot=Object.freeze({__proto__:null,ALPHANUMERICAL:Eot,AMPERSAND:Ahe,APOSTROPHE:Mhe,ASCIINUMERICAL:Tot,ASTERISK:Ihe,AT:rj,BACKSLASH:Phe,BACKTICK:Lhe,CARET:Dhe,CLOSEANGLEBRACKET:_he,CLOSEBRACE:o8,CLOSEBRACKET:ghe,CLOSEPAREN:vhe,COLON:X4,COMMA:fTe,DOLLAR:Rhe,DOT:hv,EMOJI:Mot,EQUALS:Ohe,EXCLAMATION:pTe,FULLWIDTHGREATERTHAN:Ehe,FULLWIDTHLEFTPAREN:whe,FULLWIDTHLESSTHAN:The,FULLWIDTHMIDDLEDOT:Aot,FULLWIDTHRIGHTPAREN:jhe,HYPHEN:vg,LEFTCORNERBRACKET:Nhe,LEFTWHITECORNERBRACKET:She,LOCALHOST:vF,NL:mTe,NUM:hTe,OPENANGLEBRACKET:bhe,OPENBRACE:i8,OPENBRACKET:xhe,OPENPAREN:yhe,PERCENT:l8,PIPE:Fhe,PLUS:Bhe,POUND:zhe,QUERY:c8,QUOTE:xTe,RIGHTCORNERBRACKET:khe,RIGHTWHITECORNERBRACKET:Che,SCHEME:Ede,SEMI:gTe,SLASH:mv,SLASH_SCHEME:mA,SYM:Uhe,TILDE:d8,TLD:CNe,UNDERSCORE:$he,UTLD:TNe,UWORD:SNe,WORD:_b,WS:ENe});const hb=/[a-z]/,WD=new RegExp("\\p{L}","u"),ybe=new RegExp("\\p{Emoji}","u"),mb=/\d/,vbe=/\s/,nze="\r",bbe=` `,cYt="️",dYt="‍",_be="";let pU=null,xU=null;function uYt(s=[]){const t={};ip.groups=t;const r=new ip;pU==null&&(pU=aze(rYt)),xU==null&&(xU=aze(nYt)),un(r,"'",Mhe),un(r,"{",i8),un(r,"}",o8),un(r,"[",xhe),un(r,"]",ghe),un(r,"(",yhe),un(r,")",vhe),un(r,"<",bhe),un(r,">",_he),un(r,"(",whe),un(r,")",jhe),un(r,"「",Nhe),un(r,"」",khe),un(r,"『",She),un(r,"』",Che),un(r,"<",The),un(r,">",Ehe),un(r,"&",Ahe),un(r,"*",Ihe),un(r,"@",rj),un(r,"`",Lhe),un(r,"^",Dhe),un(r,":",X4),un(r,",",fTe),un(r,"$",Rhe),un(r,".",hv),un(r,"=",Ohe),un(r,"!",pTe),un(r,"-",vg),un(r,"%",l8),un(r,"|",Fhe),un(r,"+",Bhe),un(r,"#",zhe),un(r,"?",c8),un(r,'"',xTe),un(r,"/",mv),un(r,";",gTe),un(r,"~",d8),un(r,"_",$he),un(r,"\\",Phe),un(r,"・",Aot);const n=wd(r,mb,hTe,{[wNe]:!0});wd(n,mb,n);const a=wd(n,hb,Tot,{[a8]:!0}),i=wd(n,WD,Eot,{[SR]:!0}),l=wd(r,hb,_b,{[jNe]:!0});wd(l,mb,a),wd(l,hb,l),wd(a,mb,a),wd(a,hb,a);const o=wd(r,WD,SNe,{[NNe]:!0});wd(o,hb),wd(o,mb,i),wd(o,WD,o),wd(i,mb,i),wd(i,hb),wd(i,WD,i);const c=un(r,bbe,mTe,{[gbe]:!0}),d=un(r,nze,ENe,{[gbe]:!0}),h=wd(r,vbe,ENe,{[gbe]:!0});un(r,_be,h),un(d,bbe,c),un(d,_be,h),wd(d,vbe,h),un(h,nze),un(h,bbe),wd(h,vbe,h),un(h,_be,h);const m=wd(r,ybe,Mot,{[Cot]:!0});un(m,"#"),wd(m,ybe,m),un(m,cYt,m);const x=un(m,dYt);un(x,"#"),wd(x,ybe,m);const g=[[hb,l],[mb,a]],v=[[hb,null],[WD,o],[mb,i]];for(let j=0;jj[0]>b[0]?1:-1);for(let j=0;j=0?S[kNe]=!0:hb.test(b)?mb.test(b)?S[a8]=!0:S[jNe]=!0:S[wNe]=!0,rze(r,b,b,S)}return rze(r,"localhost",vF,{ascii:!0}),r.jd=new ip(Uhe),{start:r,tokens:Object.assign({groups:t},Iot)}}function Pot(s,t){const r=hYt(t.replace(/[A-Z]/g,o=>o.toLowerCase())),n=r.length,a=[];let i=0,l=0;for(;l=0&&(m+=r[l].length,x++),d+=r[l].length,i+=r[l].length,l++;i-=m,l-=x,d-=m,a.push({t:h.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function hYt(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 Lw(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 bF={defaultProtocol:"http",events:null,format:ize,formatHref:ize,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function yTe(s,t=null){let r=Object.assign({},bF);s&&(r=Object.assign(r,s instanceof yTe?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=bF.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const t=this,r=this.toHref(s.get("defaultProtocol")),n=s.get("formatHref",r,this),a=s.get("tagName",r,t),i=this.toFormattedString(s),l={},o=s.get("className",r,t),c=s.get("target",r,t),d=s.get("rel",r,t),h=s.getObj("attributes",r,t),m=s.getObj("events",r,t);return l.href=n,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),h&&Object.assign(l,h),{tagName:a,attributes:l,content:i,eventListeners:m}}};function gxe(s,t){class r extends Lot{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 mYt=gxe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),oze=gxe("text"),fYt=gxe("nl"),gU=gxe("url",{isLink:!0,toHref(s=bF.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==vF&&s[1].t===X4}}),hg=s=>new ip(s);function pYt({groups:s}){const t=s.domain.concat([Ahe,Ihe,rj,Phe,Lhe,Dhe,Rhe,Ohe,vg,hTe,l8,Fhe,Bhe,zhe,mv,Uhe,d8,$he]),r=[Mhe,X4,fTe,hv,pTe,l8,c8,xTe,gTe,bhe,_he,i8,o8,ghe,xhe,yhe,vhe,whe,jhe,Nhe,khe,She,Che,The,Ehe],n=[Ahe,Mhe,Ihe,Phe,Lhe,Dhe,Rhe,Ohe,vg,i8,o8,l8,Fhe,Bhe,zhe,c8,mv,Uhe,d8,$he],a=hg(),i=un(a,d8);ro(i,n,i),ro(i,s.domain,i);const l=hg(),o=hg(),c=hg();ro(a,s.domain,l),ro(a,s.scheme,o),ro(a,s.slashscheme,c),ro(l,n,i),ro(l,s.domain,l);const d=un(l,rj);un(i,rj,d),un(o,rj,d),un(c,rj,d);const h=un(i,hv);ro(h,n,i),ro(h,s.domain,i);const m=hg();ro(d,s.domain,m),ro(m,s.domain,m);const x=un(m,hv);ro(x,s.domain,m);const g=hg(mYt);ro(x,s.tld,g),ro(x,s.utld,g),un(d,vF,g);const v=un(m,vg);un(v,vg,v),ro(v,s.domain,m),ro(g,s.domain,m),un(g,hv,x),un(g,vg,v);const j=un(l,vg),b=un(l,hv);un(j,vg,j),ro(j,s.domain,l),ro(b,n,i),ro(b,s.domain,l);const N=hg(gU);ro(b,s.tld,N),ro(b,s.utld,N),ro(N,s.domain,l),ro(N,n,i),un(N,hv,b),un(N,vg,j),un(N,rj,d);const S=un(N,X4),T=hg(gU);ro(S,s.numeric,T);const A=hg(gU),P=hg();ro(A,t,A),ro(A,r,P),ro(P,t,A),ro(P,r,P),un(N,mv,A),un(T,mv,A);const D=un(o,X4),B=un(c,X4),z=un(B,mv),F=un(z,mv);ro(o,s.domain,l),un(o,hv,b),un(o,vg,j),ro(c,s.domain,l),un(c,hv,b),un(c,vg,j),ro(D,s.domain,A),un(D,mv,A),un(D,c8,A),ro(F,s.domain,A),ro(F,t,A),un(F,mv,A);const $=[[i8,o8],[xhe,ghe],[yhe,vhe],[bhe,_he],[whe,jhe],[Nhe,khe],[She,Che],[The,Ehe]];for(let X=0;X<$.length;X++){const[K,Q]=$[X],Y=un(A,K);un(P,K,Y);const ne=hg(gU);ro(Y,t,ne);const de=hg();ro(Y,r,de),un(Y,Q,A),ro(ne,t,ne),ro(ne,r,de),ro(de,t,ne),ro(de,r,de),un(ne,Q,A),un(de,Q,A)}return un(a,vF,N),un(a,mTe,fYt),{start:a,tokens:Iot}}function xYt(s,t,r){let n=r.length,a=0,i=[],l=[];for(;a=0&&x++,a++,h++;if(x<0)a-=h,a0&&(i.push(wbe(oze,t,l)),l=[]),a-=x,h-=x;const g=m.t,v=r.slice(a-h,a);i.push(wbe(g,t,v))}}return l.length>0&&i.push(wbe(oze,t,l)),i}function wbe(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 gYt=typeof console<"u"&&console&&console.warn||(()=>{}),yYt="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Tc={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function vYt(){return ip.groups={},Tc.scanner=null,Tc.parser=null,Tc.tokenQueue=[],Tc.pluginQueue=[],Tc.customSchemes=[],Tc.initialized=!1,Tc}function lze(s,t=!1){if(Tc.initialized&&gYt(`linkifyjs: already initialized - will not register custom scheme "${s}" ${yYt}`),!/^[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`);Tc.customSchemes.push([s,t])}function bYt(){Tc.scanner=uYt(Tc.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=XGt(r.doc,[...t]);if(nWt(o).forEach(({newRange:d})=>{const h=JGt(n.doc,d,g=>g.isTextblock);let m,x;if(h.length>1)m=h[0],x=n.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(h.length){const g=n.doc.textBetween(d.from,d.to," "," ");if(!wYt.test(g))return;m=h[0],x=n.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&x){const g=x.split(_Yt).filter(Boolean);if(g.length<=0)return!1;const v=g[g.length-1],j=m.pos+x.lastIndexOf(v);if(!v)return!1;const b=vTe(v).map(N=>N.toObject(s.defaultProtocol));if(!NYt(b))return!1;b.filter(N=>N.isLink).map(N=>({...N,from:j+N.start+1,to:j+N.end+1})).filter(N=>n.schema.marks.code?!n.doc.rangeHasMark(N.from,N.to,n.schema.marks.code):!0).filter(N=>s.validate(N.value)).filter(N=>s.shouldAutoLink(N.value)).forEach(N=>{nTe(N.from,N.to,n.doc).some(S=>S.mark.type===s.type)||l.addMark(N.from,N.to,s.type.create({href:N.href}))})}}),!!l.steps.length)return l}})}function SYt(s){return new sh({key:new qm("handleClickLink"),props:{handleClick:(t,r,n)=>{var a,i;if(n.button!==0||!t.editable)return!1;let l=n.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(x=>x.nodeName==="A"))return!1;const c=yot(t.state,s.type.name),d=n.target,h=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,m=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&h?(window.open(h,m),!0):!1}}})}function CYt(s){return new sh({key:new qm("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=Dot(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 lk(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(jYt,"").match(new RegExp(`^(?:(?:${r.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const _Te=m0.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"){lze(s);return}lze(s.scheme,s.optionalSlashes)})},onDestroy(){vYt()},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)=>!!lk(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=>!!lk(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=>!!lk(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Zc(this.options.HTMLAttributes,s),0]:["a",Zc(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!lk(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=>!!lk(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[S5({find:s=>{const t=[];if(s){const{protocols:r,defaultProtocol:n}=this.options,a=Dot(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!lk(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(kYt({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:a=>!!lk(a,t),protocols:t,defaultProtocol:r}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(SYt({type:this.type})),this.options.linkOnPaste&&s.push(CYt({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),wTe=hm.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")}}}),TYt=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}`)})},jTe=m0.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&TYt(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Zc(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}}}}),EYt=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,AYt=Vm.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",Zc(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[vot({find:EYt,type:this.type,getAttributes:s=>{const[,,t,r,n]=s;return{src:r,alt:t,title:n}}})]}});let ANe,MNe;if(typeof WeakMap<"u"){let s=new WeakMap;ANe=t=>s.get(t),MNe=(t,r)=>(s.set(t,r),r)}else{const s=[];let r=0;ANe=n=>{for(let a=0;a(r==10&&(r=0),s[r++]=n,s[r++]=a)}var Pd=class{constructor(s,t,r,n){this.width=s,this.height=t,this.map=r,this.problems=n}findCell(s){for(let t=0;t=r){(i||(i=[])).push({type:"overlong_rowspan",pos:h,n:N-T});break}const A=a+T*t;for(let P=0;Pn&&(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 PYt(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 DYt(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 g0(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 yxe(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=C5(t.$head)||RYt(t.$head);if(r)return r;throw new RangeError(`No cell found around position ${t.head}`)}function RYt(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 INe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function OYt(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function NTe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Rot(s,t,r){const n=s.node(-1),a=Pd.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 T5(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 Oot(s,t,r=1){const n={...s,colspan:s.colspan+r};if(n.colwidth){n.colwidth=n.colwidth.slice();for(let a=0;ah!=r.pos-i);c.unshift(r.pos-i);const d=c.map(h=>{const m=n.nodeAt(h);if(!m)throw new RangeError(`No cell with offset ${h} found`);const x=i+h+1;return new cit(o.resolve(x),o.resolve(x+m.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=r}map(t,r){const n=t.resolve(r.map(this.$anchorCell.pos)),a=t.resolve(r.map(this.$headCell.pos));if(INe(n)&&INe(a)&&NTe(n,a)){const i=this.$anchorCell.node(-1)!=n.node(-1);return i&&this.isRowSelection()?wb.rowSelection(n,a):i&&this.isColSelection()?wb.colSelection(n,a):new wb(n,a)}return Ya.between(n,a)}content(){const t=this.$anchorCell.node(-1),r=Pd.get(t),n=this.$anchorCell.start(-1),a=r.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},l=[];for(let c=a.top;c0||b>0){let N=v.attrs;if(j>0&&(N=T5(N,0,j)),b>0&&(N=T5(N,N.colspan-b,b)),g.lefta.bottom){const N={...v.attrs,rowspan:Math.min(g.bottom,a.bottom)-Math.max(g.top,a.top)};g.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=Pd.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 wb&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,r=t){const n=t.node(-1),a=Pd.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(bf.node(n,n+r.nodeSize,{class:"selectedCell"}))}),Md.create(s.doc,t)}function $Yt({$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 UYt({$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 qYt(s,t,r){const n=(t||s).selection,a=(t||s).doc;let i,l;if(n instanceof Za&&(l=n.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=yc.create(a,n.from);else if(l=="row"){const o=a.resolve(n.from+1);i=yc.rowSelection(o,o)}else if(!r){const o=Pd.get(n.node),c=n.from+1,d=c+o.map[o.width*o.height-1];i=yc.create(a,c+1,d)}}else n instanceof Ya&&$Yt(n)?i=Ya.create(a,n.from):n instanceof Ya&&UYt(n)&&(i=Ya.create(a,n.$from.start(),n.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const VYt=new qm("fix-tables");function Bot(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=HYt(s,a,i,r))};return t?t.doc!=s.doc&&Bot(t.doc,s.doc,0,n):s.doc.descendants(n),r}function HYt(s,t,r,n){const a=Pd.get(t);if(!a.problems)return n;n||(n=s.tr);const i=[];for(let c=0;c0){let g="cell";h.firstChild&&(g=h.firstChild.type.spec.tableRole);const v=[];for(let b=0;b0?-1:0;FYt(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;ZYt(t,n,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,h=t.width*a;d0&&a0&&m==t.map[h-t.width]){const x=r.nodeAt(m).attrs;s.setNodeMarkup(s.mapping.slice(o).map(m+n),null,{...x,rowspan:x.rowspan-1}),d+=x.colspan-1}else if(a0&&r[i]==r[i-1]||n.right0&&r[a]==r[a-s]||n.bottom0){const h=c+1+d.content.size,m=cze(d)?c+1:h;i.replaceWith(m+n.tableStart,h+n.tableStart,o)}i.setSelection(new yc(i.doc.resolve(c+n.tableStart))),t(i)}return!0}function uze(s,t){const r=zm(s.schema);return sZt(({node:n})=>r[n.type.spec.tableRole])(s,t)}function sZt(s){return(t,r)=>{const n=t.selection;let a,i;if(n instanceof yc){if(n.$anchorCell.pos!=n.$headCell.pos)return!1;a=n.$anchorCell.nodeAfter,i=n.$anchorCell.pos}else{var l;if(a=DYt(n.$from),!a)return!1;i=(l=C5(n.$from))===null||l===void 0?void 0:l.pos}if(a==null||i==null||a.attrs.colspan==1&&a.attrs.rowspan==1)return!1;if(r){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const h=v1(t),m=t.tr;for(let g=0;g{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 nZt(s){return function(t,r){if(!g0(t))return!1;if(r){const n=zm(t.schema),a=v1(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 g=x+i.tableStart,v=l.doc.nodeAt(g);v&&l.setNodeMarkup(g,m,v.attrs)}),n(l)}return!0}}_F("row",{useDeprecatedLogic:!0});_F("column",{useDeprecatedLogic:!0});const aZt=_F("cell",{useDeprecatedLogic:!0});function iZt(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 yU(s,t){const r=s.selection;if(!(r instanceof yc))return!1;if(t){const n=s.tr,a=zm(s.schema).cell.createAndFill().content;r.forEachCell((i,l)=>{i.content.eq(a)||n.replace(n.mapping.map(l+1),n.mapping.map(l+i.nodeSize-1),new Un(a,0,0))}),n.docChanged&&t(n)}return!0}function lZt(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(an.empty),r[a]n&&(x=x.type.createChecked(T5(x.attrs,x.attrs.colspan,h+x.attrs.colspan-n),x.content)),d.push(x),h+=x.attrs.colspan;for(let g=1;ga&&(m=m.type.create({...m.attrs,rowspan:Math.max(1,a-m.attrs.rowspan)},m.content)),c.push(m)}i.push(an.from(c))}r=i,t=a}return{width:s,height:t,rows:r}}function uZt(s,t,r,n,a,i,l){const o=s.doc.type.schema,c=zm(o);let d,h;if(a>t.width)for(let m=0,x=0;mt.height){const m=[];for(let v=0,j=(t.height-1)*t.width;v=t.width?!1:r.nodeAt(t.map[j+v]).type==c.header_cell;m.push(b?h||(h=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const x=c.row.create(null,an.from(m)),g=[];for(let v=t.height;v{if(!a)return!1;const i=r.selection;if(i instanceof yc)return Ade(r,n,vi.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=qot(a,s,t);if(l==null)return!1;if(s=="horiz")return Ade(r,n,vi.near(r.doc.resolve(i.head+t),t));{const o=r.doc.resolve(l),c=Rot(o,s,t);let d;return c?d=vi.near(c,1):t<0?d=vi.near(r.doc.resolve(o.before(-1)),-1):d=vi.near(r.doc.resolve(o.after(-1)),1),Ade(r,n,d)}}}function bU(s,t){return(r,n,a)=>{if(!a)return!1;const i=r.selection;let l;if(i instanceof yc)l=i;else{const c=qot(a,s,t);if(c==null)return!1;l=new yc(r.doc.resolve(c))}const o=Rot(l.$headCell,s,t);return o?Ade(r,n,new yc(l.$anchorCell,o)):!1}}function mZt(s,t){const r=s.state.doc,n=C5(r.resolve(t));return n?(s.dispatch(s.state.tr.setSelection(new yc(n))),!0):!1}function fZt(s,t,r){if(!g0(s.state))return!1;let n=lZt(r);const a=s.state.selection;if(a instanceof yc){n||(n={width:1,height:1,rows:[an.from(PNe(zm(s.state.schema).cell,r))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=Pd.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return n=dZt(n,o.right-o.left,o.bottom-o.top),xze(s.state,s.dispatch,l,o,n),!0}else if(n){const i=yxe(s.state),l=i.start(-1);return xze(s.state,s.dispatch,l,Pd.get(i.node(-1)).findCell(i.pos-l),n),!0}else return!1}function pZt(s,t){var r;if(t.button!=0||t.ctrlKey||t.metaKey)return;const n=gze(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof yc)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(a=C5(s.state.selection.$anchor))!=null&&((r=jbe(s,t))===null||r===void 0?void 0:r.pos)!=a.pos)i(a,t),t.preventDefault();else if(!n)return;function i(c,d){let h=jbe(s,d);const m=fj.getState(s.state)==null;if(!h||!NTe(c,h))if(m)h=c;else return;const x=new yc(c,h);if(m||!s.state.selection.eq(x)){const g=s.state.tr.setSelection(x);m&&g.setMeta(fj,c.pos),s.dispatch(g)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),fj.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(fj,-1))}function o(c){const d=c,h=fj.getState(s.state);let m;if(h!=null)m=s.state.doc.resolve(h);else if(gze(s,d.target)!=n&&(m=jbe(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 qot(s,t,r){if(!(s.state.selection instanceof Ya))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 gze(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function jbe(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&&C5(s.state.doc.resolve(n))||C5(s.state.doc.resolve(a))}var xZt=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")),LNe(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,LNe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function LNe(s,t,r,n,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let m=0,x=0;mnew n(m,r,x)),new yZt(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=ux.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{vZt(l,o,s,a)},mouseleave:l=>{bZt(l)},mousedown:(l,o)=>{_Zt(l,o,t,r)}},decorations:l=>{const o=ux.getState(l);if(o&&o.activeHandle>-1)return SZt(l,o.activeHandle)},nodeViews:{}}});return i}var yZt=class Mde{constructor(t,r){this.activeHandle=t,this.dragging=r}apply(t){const r=this,n=t.getMeta(ux);if(n&&n.setHandle!=null)return new Mde(n.setHandle,!1);if(n&&n.setDragging!==void 0)return new Mde(r.activeHandle,n.setDragging);if(r.activeHandle>-1&&t.docChanged){let a=t.mapping.map(r.activeHandle,-1);return INe(t.doc.resolve(a))||(a=-1),new Mde(a,r.dragging)}return r}};function vZt(s,t,r,n){if(!s.editable)return;const a=ux.getState(s.state);if(a&&!a.dragging){const i=jZt(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=r?l=yze(s,t,"left",r):c-t.clientX<=r&&(l=yze(s,t,"right",r))}if(l!=a.activeHandle){if(!n&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=Pd.get(c),h=o.start(-1);if(d.colCount(o.pos-h)+o.nodeAfter.attrs.colspan-1==d.width-1)return}Vot(s,l)}}}function bZt(s){if(!s.editable)return;const t=ux.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&Vot(s,-1)}function _Zt(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=ux.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=wZt(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(ux,{setDragging:{startX:t.clientX,startWidth:c}}));function d(m){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",h);const x=ux.getState(s.state);x!=null&&x.dragging&&(NZt(s,x.activeHandle,vze(x.dragging,m,r)),s.dispatch(s.state.tr.setMeta(ux,{setDragging:null})))}function h(m){if(!m.which)return d(m);const x=ux.getState(s.state);if(x&&x.dragging){const g=vze(x.dragging,m,r);bze(s,x.activeHandle,g,n)}}return bze(s,l.activeHandle,c,n),i.addEventListener("mouseup",d),i.addEventListener("mousemove",h),t.preventDefault(),!0}function wZt(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 MZt(s,t,r,n,a){const i=AZt(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!IZt(t))return!1;let r=0;const n=got(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},PZt=Vm.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:TZt,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}=EZt(s,this.options.cellMinWidth),i=["table",Zc(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=MZt(i.schema,s,t,r);if(a){const o=n.selection.from+1;n.replaceSelectionWith(l).scrollIntoView().setSelection(Ya.near(n.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>GYt(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>WYt(s,t),deleteColumn:()=>({state:s,dispatch:t})=>YYt(s,t),addRowBefore:()=>({state:s,dispatch:t})=>XYt(s,t),addRowAfter:()=>({state:s,dispatch:t})=>QYt(s,t),deleteRow:()=>({state:s,dispatch:t})=>eZt(s,t),deleteTable:()=>({state:s,dispatch:t})=>oZt(s,t),mergeCells:()=>({state:s,dispatch:t})=>dze(s,t),splitCell:()=>({state:s,dispatch:t})=>uze(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>_F("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>_F("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>aZt(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>dze(s,t)?!0:uze(s,t),setCellAttribute:(s,t)=>({state:r,dispatch:n})=>rZt(s,t)(r,n),goToNextCell:()=>({state:s,dispatch:t})=>mze(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>mze(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&zot(s),!0),setCellSelection:s=>({tr:t,dispatch:r})=>{if(r){const n=yc.create(t.doc,s.anchorCell,s.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:_U,"Mod-Backspace":_U,Delete:_U,"Mod-Delete":_U}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[gZt({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],CZt({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:to(ba(s,"tableRole",t))}}}),LZt=Vm.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Zc(this.options.HTMLAttributes,s),0]}}),DZt=Vm.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",Zc(this.options.HTMLAttributes,s),0]}}),RZt=Vm.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",Zc(this.options.HTMLAttributes,s),0]}});function y0({content:s,onChange:t,placeholder:r="Enter content...",minHeight:n="150px",compact:a=!1}){const[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState(!0),m=cTe({extensions:[uTe,_Te.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),wTe.configure({types:["heading","paragraph"]}),jTe,AYt.extend({addAttributes(){var j;return{...(j=this.parent)==null?void 0:j.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),PZt.extend({addAttributes(){var j;return{...(j=this.parent)==null?void 0:j.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),LZt.extend({addAttributes(){var j;return{...(j=this.parent)==null?void 0:j.call(this),style:{default:null}}}}),DZt.extend({addAttributes(){var j;return{...(j=this.parent)==null?void 0:j.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),RZt.extend({addAttributes(){var j;return{...(j=this.parent)==null?void 0:j.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:j})=>{t(j.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":r},handlePaste:(j,b)=>{var S;const N=(S=b.clipboardData)==null?void 0:S.items;if(!N)return!1;for(const T of Array.from(N))if(T.type.startsWith("image/")){b.preventDefault();const A=T.getAsFile();if(!A)continue;const P=new FileReader;return P.onload=D=>{var z;const B=(z=D.target)==null?void 0:z.result;j.dispatch(j.state.tr.replaceSelectionWith(j.state.schema.nodes.image.create({src:B})))},P.readAsDataURL(A),!0}return!1}}});k.useEffect(()=>{m&&s!==m.getHTML()&&m.commands.setContent(s)},[s,m]);const x=()=>{if(!m)return;const j=m.getAttributes("link").href||"",b=m.getAttributes("link").target;c(j),h(b==="_blank"),l(!0)},g=()=>{m&&(o===""?m.chain().focus().extendMarkRange("link").unsetLink().run():m.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},v=()=>{m&&m.chain().focus().extendMarkRange("link").unsetLink().run()};return m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:1}).run(),className:m.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(rM,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:2}).run(),className:m.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(nM,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBold().run(),className:m.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(qj,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleItalic().run(),className:m.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(Kj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBulletList().run(),className:m.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(lm,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleOrderedList().run(),className:m.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("left").run(),className:m.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(y3,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("center").run(),className:m.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(g3,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("right").run(),className:m.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(v3,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:x,className:m.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(xo,{className:"h-4 w-4"})}),m.isActive("link")&&e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:v,title:"Remove Link",children:e.jsx(xo,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().undo().run(),disabled:!m.can().undo(),title:"Undo",children:e.jsx(s2,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().redo().run(),disabled:!m.can().redo(),title:"Redo",children:e.jsx(e2,{className:"h-4 w-4"})})]}),e.jsx(oTe,{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(js,{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(he,{htmlFor:"link-url",children:"URL"}),e.jsx(ke,{id:"link-url",value:o,onChange:j=>c(j.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(br,{id:"link-new-tab",checked:d,onCheckedChange:h}),e.jsx(he,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:g,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var OZt=Object.defineProperty,FZt=(s,t,r)=>t in s?OZt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,zc=(s,t,r)=>FZt(s,typeof t!="symbol"?t+"":t,r);const qhe={x:0,y:0,width:0,height:0,unit:"px"},UE=(s,t,r)=>Math.min(Math.max(s,t),r),BZt=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),jze=(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 zZt(s,t,r,n){const a=fv(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==="%"?nj(a,r,n):a}function $Zt(s,t,r){const n=fv(s,t,r);return n.x=(t-n.width)/2,n.y=(r-n.height)/2,s.unit==="%"?nj(n,t,r):n}function nj(s,t,r){return s.unit==="%"?{...qhe,...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 fv(s,t,r){return s.unit?s.unit==="px"?{...qhe,...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}:{...qhe,...s,unit:"px"}}function Nze(s,t,r,n,a,i=0,l=0,o=n,c=a){const d={...s};let h=Math.min(i,n),m=Math.min(l,a),x=Math.min(o,n),g=Math.min(c,a);t&&(t>1?(h=l?l*t:h,m=h/t,x=o*t):(m=i?i/t:m,h=m*t,g=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,m),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,h),d.x=0);const v=n-(d.x+d.width);v<0&&(d.x=Math.min(d.x,n-h),d.width+=v);const j=a-(d.y+d.height);if(j<0&&(d.y=Math.min(d.y,a-m),d.height+=j),d.widthx&&((r==="sw"||r=="nw")&&(d.x-=x-d.width),d.width=x),d.height>g&&((r==="nw"||r=="ne")&&(d.y-=g-d.height),d.height=g),t){const b=d.width/d.height;if(bt){const N=Math.max(d.height*t,h);(r==="sw"||r=="nw")&&(d.x-=N-d.width),d.width=N}}return d}function UZt(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 qE={capture:!0,passive:!1};let qZt=0;const Kw=class Iy extends k.PureComponent{constructor(){super(...arguments),zc(this,"docMoveBound",!1),zc(this,"mouseDownOnCrop",!1),zc(this,"dragStarted",!1),zc(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),zc(this,"componentRef",k.createRef()),zc(this,"mediaRef",k.createRef()),zc(this,"resizeObserver"),zc(this,"initChangeCalled",!1),zc(this,"instanceId",`rc-${qZt++}`),zc(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),zc(this,"onCropPointerDown",t=>{const{crop:r,disabled:n}=this.props,a=this.getBox();if(!r)return;const i=fv(r,a.width,a.height);if(n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,h=i.x,m=i.y;if(l){const x=t.clientX-a.x,g=t.clientY-a.y;let v=0,j=0;l==="ne"||l=="e"?(v=x-(i.x+i.width),j=g-i.y,h=i.x,m=i.y+i.height):l==="se"||l==="s"?(v=x-(i.x+i.width),j=g-(i.y+i.height),h=i.x,m=i.y):l==="sw"||l=="w"?(v=x-i.x,j=g-(i.y+i.height),h=i.x+i.width,m=i.y):(l==="nw"||l=="n")&&(v=x-i.x,j=g-i.y,h=i.x+i.width,m=i.y+i.height),c=h+a.x+v,d=m+a.y+j}this.evData={startClientX:c,startClientY:d,startCropX:h,startCropY:m,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),zc(this,"onComponentPointerDown",t=>{const{crop:r,disabled:n,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(n||a||i&&r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,h={unit:"px",x:c,y:d,width:0,height:0};this.evData={startClientX:t.clientX,startClientY:t.clientY,startCropX:c,startCropY:d,clientX:t.clientX,clientY:t.clientY,isResize:!0},this.mouseDownOnCrop=!0,l(fv(h,o.width,o.height),nj(h,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),zc(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(),jze(r,c)||a(fv(c,l.width,l.height),nj(c,l.width,l.height))}),zc(this,"onComponentKeyDown",t=>{const{crop:r,disabled:n,onChange:a,onComplete:i}=this.props;if(n)return;const l=t.key;let o=!1;if(!r)return;const c=this.getBox(),d=this.makePixelCrop(c),h=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?Iy.nudgeStepLarge:t.shiftKey?Iy.nudgeStepMedium:Iy.nudgeStep;if(l==="ArrowLeft"?(d.x-=h,o=!0):l==="ArrowRight"?(d.x+=h,o=!0):l==="ArrowUp"?(d.y-=h,o=!0):l==="ArrowDown"&&(d.y+=h,o=!0),o){t.cancelable&&t.preventDefault(),d.x=UE(d.x,0,c.width-d.width),d.y=UE(d.y,0,c.height-d.height);const m=fv(d,c.width,c.height),x=nj(d,c.width,c.height);a(m,x),i&&i(m,x)}}),zc(this,"onHandlerKeyDown",(t,r)=>{const{aspect:n=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:h,onComplete:m}=this.props,x=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const g=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?Iy.nudgeStepLarge:t.shiftKey?Iy.nudgeStepMedium:Iy.nudgeStep,v=fv(a,x.width,x.height),j=UZt(v,t.key,g,r),b=Nze(j,n,r,x.width,x.height,l,o,c,d);if(!jze(a,b)){const N=nj(b,x.width,x.height);h(b,N),m&&m(b,N)}}),zc(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(fv(r,l.width,l.height),nj(r,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),zc(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(fv(r,a,i),nj(r,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,qE),this.document.addEventListener("pointerup",this.onDocPointerDone,qE),this.document.addEventListener("pointercancel",this.onDocPointerDone,qE),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,qE),this.document.removeEventListener("pointerup",this.onDocPointerDone,qE),this.document.removeEventListener("pointercancel",this.onDocPointerDone,qE),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=UE(t.startCropX+a,0,r.width-n.width),n.y=UE(t.startCropY+i,0,r.height-n.height),n}getPointRegion(t,r,n,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&r?c=r==="nw"||r==="n"||r==="ne":c=o1?i?[i,i/r]:[l*r,l]:l?[l*r,l]:[i,i/r]}resizeCrop(){const{evData:t}=this,{aspect:r=0,maxWidth:n,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,r,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),h=t.ord||d;let m=t.clientX-t.startClientX,x=t.clientY-t.startClientY;(l&&h==="nw"||h==="w"||h==="sw")&&(m=Math.min(m,-l)),(o&&h==="nw"||h==="n"||h==="ne")&&(x=Math.min(x,-o));const g={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(g.x=t.startCropX,g.width=m,r?(g.height=g.width/r,g.y=t.startCropY-g.height):(g.height=Math.abs(x),g.y=t.startCropY-g.height)):d==="se"?(g.x=t.startCropX,g.y=t.startCropY,g.width=m,r?g.height=g.width/r:g.height=x):d==="sw"?(g.x=t.startCropX+m,g.y=t.startCropY,g.width=Math.abs(m),r?g.height=g.width/r:g.height=x):d==="nw"&&(g.x=t.startCropX+m,g.width=Math.abs(m),r?(g.height=g.width/r,g.y=t.startCropY-g.height):(g.height=Math.abs(x),g.y=t.startCropY+x));const v=Nze(g,r,d,i.width,i.height,l,o,n,a);return r||Iy.xyOrds.indexOf(h)>-1?c=v:Iy.xOrds.indexOf(h)>-1?(c.x=v.x,c.width=v.width):Iy.yOrds.indexOf(h)>-1&&(c.y=v.y,c.height=v.height),c.x=UE(c.x,0,i.width-c.width),c.y=UE(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=Iy.defaultProps.ariaLabels,disabled:r,locked:n,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return wt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!n&&wt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},wt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"nw"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"n"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"ne"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"e"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"se"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"s"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"sw"),role:"button"}),wt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"w"),role:"button"})),a&&wt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&wt.createElement(wt.Fragment,null,wt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),wt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const r={...qhe,...this.props.crop||{}};return fv(r,t.width,t.height)}render(){const{aspect:t,children:r,circularCrop:n,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:h,newCropIsBeingDrawn:m}=this.state,x=i?this.renderCropSelection():null,g=BZt("ReactCrop",a,h&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",m&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&n&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",n&&"ReactCrop--no-animate");return wt.createElement("div",{ref:this.componentRef,className:g,style:c},wt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),i?wt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},wt.createElement("defs",null,wt.createElement("mask",{id:`hole-${this.instanceId}`},wt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),n?wt.createElement("ellipse",{cx:`${i.x+i.width/2}${i.unit}`,cy:`${i.y+i.height/2}${i.unit}`,rx:`${i.width/2}${i.unit}`,ry:`${i.height/2}${i.unit}`,fill:"black"}):wt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),wt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,x)}};zc(Kw,"xOrds",["e","w"]),zc(Kw,"yOrds",["n","s"]),zc(Kw,"xyOrds",["nw","ne","se","sw"]),zc(Kw,"nudgeStep",1),zc(Kw,"nudgeStepMedium",10),zc(Kw,"nudgeStepLarge",100),zc(Kw,"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 VZt=Kw;var Hot=["PageUp","PageDown"],Got=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Wot={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},LP="Slider",[RNe,HZt,GZt]=TB(LP),[kTe]=yd(LP,[GZt]),[WZt,lz]=kTe(LP),STe=k.forwardRef((s,t)=>{const{name:r,min:n=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:h,onValueChange:m=()=>{},onValueCommit:x=()=>{},inverted:g=!1,form:v,...j}=s,b=k.useRef(new Set),N=k.useRef(0),S=k.useRef(!1),A=l==="horizontal"?KZt:YZt,[P=[],D]=Lh({prop:h,defaultProp:d,onChange:K=>{var Y;(Y=[...b.current][N.current])==null||Y.focus({preventScroll:!0,focusVisible:S.current}),S.current=!1,m(K)}}),B=k.useRef(P);function z(K){const Q=JZt(P,K);X(K,Q)}function F(K){X(K,N.current)}function $(){const K=B.current[N.current];P[N.current]!==K&&x(P)}function X(K,Q,{commit:Y}={commit:!1}){const ne=rXt(i),de=nXt(Math.round((K-n)/i)*i+n,ne),ce=tF(de,[n,a]);D((ae=[])=>{const ie=XZt(ae,ce,Q);if(sXt(ie,c*i)){N.current=ie.indexOf(ce);const me=String(ie)!==String(ae);return me&&Y&&x(ie),me?ie:ae}else return ae})}return e.jsx(WZt,{scope:s.__scopeSlider,name:r,disabled:o,min:n,max:a,valueIndexToChangeRef:N,thumbs:b.current,values:P,orientation:l,form:v,children:e.jsx(RNe.Provider,{scope:s.__scopeSlider,children:e.jsx(RNe.Slot,{scope:s.__scopeSlider,children:e.jsx(A,{"aria-disabled":o,"data-disabled":o?"":void 0,...j,ref:t,onPointerDown:Or(j.onPointerDown,()=>{o||(B.current=P,S.current=!1)}),min:n,max:a,inverted:g,onSlideStart:o?void 0:z,onSlideMove:o?void 0:F,onSlideEnd:o?void 0:$,onHomeKeyDown:()=>{o||(S.current=!0,X(n,0,{commit:!0}))},onEndKeyDown:()=>{o||(S.current=!0,X(a,P.length-1,{commit:!0}))},onStepKeyDown:({event:K,direction:Q})=>{if(!o){S.current=!0;const de=Hot.includes(K.key)||K.shiftKey&&Got.includes(K.key)?10:1,ce=N.current,ae=P[ce],ie=i*de*Q;X(ae+ie,ce,{commit:!0})}}})})})})});STe.displayName=LP;var[Kot,Yot]=kTe(LP,{startEdge:"left",endEdge:"right",size:"width",direction:1}),KZt=k.forwardRef((s,t)=>{const{min:r,max:n,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...h}=s,[m,x]=k.useState(null),g=Qa(t,T=>x(T)),v=k.useRef(void 0),j=$2(a),b=j==="ltr",N=b&&!i||!b&&i;function S(T){const A=v.current||m.getBoundingClientRect(),P=[0,A.width],B=CTe(P,N?[r,n]:[n,r]);return v.current=A,B(T-A.left)}return e.jsx(Kot,{scope:s.__scopeSlider,startEdge:N?"left":"right",endEdge:N?"right":"left",direction:N?1:-1,size:"width",children:e.jsx(Zot,{dir:j,"data-orientation":"horizontal",...h,ref:g,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:T=>{const A=S(T.clientX);l==null||l(A)},onSlideMove:T=>{const A=S(T.clientX);o==null||o(A)},onSlideEnd:()=>{v.current=void 0,c==null||c()},onStepKeyDown:T=>{const P=Wot[N?"from-left":"from-right"].includes(T.key);d==null||d({event:T,direction:P?-1:1})}})})}),YZt=k.forwardRef((s,t)=>{const{min:r,max:n,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,h=k.useRef(null),m=Qa(t,h),x=k.useRef(void 0),g=!a;function v(j){const b=x.current||h.current.getBoundingClientRect(),N=[0,b.height],T=CTe(N,g?[n,r]:[r,n]);return x.current=b,T(j-b.top)}return e.jsx(Kot,{scope:s.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:e.jsx(Zot,{"data-orientation":"vertical",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:j=>{const b=v(j.clientY);i==null||i(b)},onSlideMove:j=>{const b=v(j.clientY);l==null||l(b)},onSlideEnd:()=>{x.current=void 0,o==null||o()},onStepKeyDown:j=>{const N=Wot[g?"from-bottom":"from-top"].includes(j.key);c==null||c({event:j,direction:N?-1:1})}})})}),Zot=k.forwardRef((s,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,h=lz(LP,r);return e.jsx(pn.span,{...d,ref:t,onKeyDown:Or(s.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(o(m),m.preventDefault()):Hot.concat(Got).includes(m.key)&&(c(m),m.preventDefault())}),onPointerDown:Or(s.onPointerDown,m=>{const x=m.target;x.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(x)?x.focus({preventScroll:!0,focusVisible:!1}):n(m)}),onPointerMove:Or(s.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&a(m)}),onPointerUp:Or(s.onPointerUp,m=>{const x=m.target;x.hasPointerCapture(m.pointerId)&&(x.releasePointerCapture(m.pointerId),i(m))})})}),Xot="SliderTrack",Qot=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=lz(Xot,r);return e.jsx(pn.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...n,ref:t})});Qot.displayName=Xot;var ONe="SliderRange",Jot=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=lz(ONe,r),i=Yot(ONe,r),l=k.useRef(null),o=Qa(t,l),c=a.values.length,d=a.values.map(x=>llt(x,a.min,a.max)),h=c>1?Math.min(...d):0,m=100-Math.max(...d);return e.jsx(pn.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...n,ref:o,style:{...s.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}})});Jot.displayName=ONe;var elt="SliderThumb",[ZZt,tlt]=kTe(elt),slt="SliderThumbProvider";function rlt(s){const{__scopeSlider:t,name:r,children:n,internal_do_not_use_render:a}=s,i=lz(slt,t),l=HZt(t),[o,c]=k.useState(null),d=k.useMemo(()=>o?l().findIndex(b=>b.ref.current===o):-1,[l,o]),h=MB(o),m=o?!!i.form||!!o.closest("form"):!0,x=i.values[d],g=r??(i.name?i.name+(i.values.length>1?"[]":""):void 0),v=x===void 0?0:llt(x,i.min,i.max);k.useEffect(()=>{if(o)return i.thumbs.add(o),()=>{i.thumbs.delete(o)}},[o,i.thumbs]);const j={value:x,name:g,form:i.form,isFormControl:m,index:d,thumb:o,onThumbChange:c,percent:v,size:h};return e.jsx(ZZt,{scope:t,...j,children:aXt(a)?a(j):n})}rlt.displayName=slt;var Ide="SliderThumbTrigger",nlt=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=lz(Ide,r),i=Yot(Ide,r),{index:l,value:o,percent:c,size:d,onThumbChange:h}=tlt(Ide,r),m=Qa(t,j=>h(j)),x=QZt(l,a.values.length),g=d==null?void 0:d[i.size],v=g?eXt(g,c,i.direction):0;return e.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[i.startEdge]:`calc(${c}% + ${v}px)`},children:e.jsx(RNe.ItemSlot,{scope:r,children:e.jsx(pn.span,{role:"slider","aria-label":s["aria-label"]||x,"aria-valuemin":a.min,"aria-valuenow":o,"aria-valuemax":a.max,"aria-orientation":a.orientation,"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,tabIndex:a.disabled?void 0:0,...n,ref:m,style:o===void 0?{display:"none"}:s.style,onFocus:Or(s.onFocus,()=>{a.valueIndexToChangeRef.current=l})})})})});nlt.displayName=Ide;var alt=k.forwardRef((s,t)=>{const{__scopeSlider:r,name:n,...a}=s;return e.jsx(rlt,{__scopeSlider:r,name:n,internal_do_not_use_render:({index:i,isFormControl:l})=>e.jsxs(e.Fragment,{children:[e.jsx(nlt,{...a,ref:t,__scopeSlider:r}),l?e.jsx(olt,{__scopeSlider:r},i):null]})})});alt.displayName=elt;var ilt="SliderBubbleInput",olt=k.forwardRef(({__scopeSlider:s,...t},r)=>{const{value:n,name:a,form:i}=tlt(ilt,s),l=k.useRef(null),o=Qa(l,r),c=HB(n);return k.useEffect(()=>{const d=l.current;if(!d)return;const h=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(h,"value").set;if(c!==n&&x){const g=new Event("input",{bubbles:!0});x.call(d,n),d.dispatchEvent(g)}},[c,n]),e.jsx(pn.input,{style:{display:"none"},name:a,form:i,...t,ref:o,defaultValue:n})});olt.displayName=ilt;function XZt(s=[],t,r){const n=[...s];return n[r]=t,n.sort((a,i)=>a-i)}function llt(s,t,r){const i=100/(r-t)*(s-t);return tF(i,[0,100])}function QZt(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function JZt(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 eXt(s,t,r){const n=s/2,i=CTe([0,50],[0,n]);return(n-i(t)*r)*r}function tXt(s){return s.slice(0,-1).map((t,r)=>s[r+1]-t)}function sXt(s,t){if(t>0){const r=tXt(s);return Math.min(...r)>=t}return!0}function CTe(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 rXt(s){if(!Number.isFinite(s))return 0;const t=s.toString();if(t.includes("e")){const[n,a]=t.split("e"),i=n.split(".")[1]||"",l=Number(a);return Math.max(0,i.length-l)}const r=t.split(".")[1];return r?r.length:0}function nXt(s,t){const r=Math.pow(10,t);return Math.round(s*r)/r}function aXt(s){return typeof s=="function"}const Xy=k.forwardRef(({className:s,...t},r)=>e.jsxs(STe,{ref:r,className:Bt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(Qot,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Jot,{className:"absolute h-full bg-primary"})}),e.jsx(alt,{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"})]}));Xy.displayName=STe.displayName;function iXt(s,t,r){return $Zt(zZt({unit:"%",width:90},r,s,t),s,t)}const TTe=({open:s,onClose:t,imageSrc:r,onCropComplete:n,aspectRatio:a=1})=>{const i=k.useRef(null),[l,o]=k.useState(),[c,d]=k.useState(),[h,m]=k.useState(1),[x,g]=k.useState(0),v=k.useCallback(N=>{const{width:S,height:T}=N.currentTarget;o(iXt(S,T,a))},[a]),j=k.useCallback(async()=>{const N=i.current;if(!N||!c)return;const S=document.createElement("canvas"),T=S.getContext("2d");if(!T)return;const A=N.naturalWidth/N.width,P=N.naturalHeight/N.height,D=400;S.width=D,S.height=D,T.imageSmoothingQuality="high";const B=c.x*A,z=c.y*P,F=c.width*A,$=c.height*P,X=x*Math.PI/180,K=S.width/2,Q=S.height/2;return T.save(),T.translate(K,Q),T.rotate(X),T.scale(h,h),T.translate(-K,-Q),T.drawImage(N,B,z,F,$,0,0,D,D),T.restore(),new Promise((Y,ne)=>{S.toBlob(de=>{de?Y(de):ne(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,h,x]),b=async()=>{try{const N=await j();N&&(n(N),t())}catch(N){console.error("Error cropping image:",N)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(js,{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(VZt,{crop:l,onChange:(N,S)=>o(S),onComplete:N=>d(N),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:r,alt:"Crop preview",style:{transform:`scale(${h}) rotate(${x}deg)`,maxHeight:"400px",width:"auto"},onLoad:v})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yM,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Xy,{value:[h],min:.5,max:3,step:.1,onValueChange:([N])=>m(N),className:"flex-1"}),e.jsx(r2,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Xy,{value:[x],min:-180,max:180,step:1,onValueChange:([N])=>g(N),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[x,"°"]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(G,{onClick:b,children:"Save Photo"})]})]})})},oXt=()=>{const{user:s}=As(),{toast:t}=Ea(),[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 H.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 H.auth.getSession();if(!m)throw new Error("Not authenticated");const{data:x,error:g}=await H.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${m.access_token}`}});if(g)throw g;x!=null&&x.url&&window.open(x.url,"_blank")}catch(m){console.error("Error opening customer portal:",m),t({title:"Error",description:m.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},h=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Ge,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Ge,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Ge,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Ge,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Ge,{variant:"secondary",children:"Canceled"});default:return e.jsx(Ge,{variant:"outline",children:"No Subscription"})}};return r?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(gx,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(gx,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Nr,{children:"Manage your subscription and billing"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children:h()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs(G,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Yr,{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."})]})]})},lXt=()=>{const{user:s}=As(),t=vr(),{toast:r}=Ea(),[n]=Lc(),a=n.get("setup")==="true",i=n.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:h}=gnt(),[m,x]=k.useState(!1),[g,v]=k.useState(""),[j,b]=k.useState(!1),[N,S]=k.useState(!1),[T,A]=k.useState(""),[P,D]=k.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[B,z]=k.useState(!1),[F,$]=k.useState(!1),[X,K]=k.useState({newPassword:"",confirmPassword:""});k.useEffect(()=>{s&&Q()},[s]),k.useEffect(()=>{i&&s&&setTimeout(()=>{var ae;(ae=document.getElementById("change-password-section"))==null||ae.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const Q=async()=>{var ae,ie,me;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:oe,error:ge}=await H.from("profiles").select("name, email, phone, digest_opt_out, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(ge)throw console.error("Profile query error:",ge),ge;oe?(console.log("Profile loaded successfully:",oe),D({name:oe.name||"",email:oe.email||"",phone:oe.phone||"",title:oe.title||"",bio:oe.bio||"",areas_served:oe.areas_served||"",years_experience:((ae=oe.years_experience)==null?void 0:ae.toString())||"",instagram_url:oe.instagram_url||"",facebook_url:oe.facebook_url||"",linkedin_url:oe.linkedin_url||"",email_signature:oe.email_signature||"",use_email_signature:oe.use_email_signature||!1}),z(oe.digest_opt_out||!1)):(console.warn("No profile found for user"),D({name:((ie=s.user_metadata)==null?void 0:ie.name)||((me=s.email)==null?void 0:me.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}));const{data:be}=await H.storage.from("avatars").list(`${s.id}`);if(be&&be.length>0){const{data:Oe}=H.storage.from("avatars").getPublicUrl(`${s.id}/${be[0].name}`);v(Oe.publicUrl)}}catch(oe){console.error("Error loading profile:",oe),r({title:"Error",description:oe.message||"Failed to load profile",variant:"destructive"})}},Y=ae=>{var oe;const ie=(oe=ae.target.files)==null?void 0:oe[0];if(!ie)return;const me=new FileReader;me.onloadend=()=>{A(me.result),S(!0)},me.readAsDataURL(ie),ae.target.value=""},ne=async ae=>{if(s){b(!0);try{const{data:ie}=await H.storage.from("avatars").list(`${s.id}`);ie&&ie.length>0&&await H.storage.from("avatars").remove(ie.map(Me=>`${s.id}/${Me.name}`));const oe=`${s.id}/avatar.jpg`,{error:ge}=await H.storage.from("avatars").upload(oe,ae,{upsert:!0,contentType:"image/jpeg"});if(ge)throw ge;const{data:be}=H.storage.from("avatars").getPublicUrl(oe),Oe=be.publicUrl;v(`${Oe}?t=${Date.now()}`),await H.from("profiles").update({avatar_url:Oe}).eq("id",s.id),r({title:"Success",description:"Profile photo updated successfully"})}catch(ie){console.error("Error uploading avatar:",ie),r({title:"Error",description:ie.message||"Failed to upload photo",variant:"destructive"})}finally{b(!1)}}},de=async()=>{if(!P.name.trim()||!P.email.trim()){r({title:"Error",description:"Name and email are required",variant:"destructive"});return}x(!0);try{const{error:ae}=await H.from("profiles").update({name:P.name.trim(),email:P.email.trim(),phone:P.phone.trim()||null,title:P.title.trim()||null,bio:P.bio.trim()||null,areas_served:P.areas_served.trim()||null,years_experience:P.years_experience?parseInt(P.years_experience):null,instagram_url:P.instagram_url.trim()||null,facebook_url:P.facebook_url.trim()||null,linkedin_url:P.linkedin_url.trim()||null,email_signature:P.email_signature||"",use_email_signature:P.use_email_signature}).eq("id",s==null?void 0:s.id);if(ae)throw ae;r({title:"Success",description:"Profile updated successfully"})}catch(ae){console.error("Error updating profile:",ae),r({title:"Error",description:ae.message||"Failed to update profile",variant:"destructive"})}finally{x(!1)}},ce=async()=>{if(!X.newPassword){r({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(X.newPassword.length<6){r({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(X.newPassword!==X.confirmPassword){r({title:"Error",description:"Passwords do not match",variant:"destructive"});return}x(!0);try{const{error:ae}=await H.auth.updateUser({password:X.newPassword});if(ae)throw ae;r({title:"Success",description:"Password updated successfully"}),K({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ae){console.error("Error updating password:",ae),r({title:"Error",description:ae.message||"Failed to update password",variant:"destructive"})}finally{x(!1)}};return e.jsx(_s,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(G,{variant:"outline",onClick:()=>{var ae;(ae=document.getElementById("change-password-section"))==null||ae.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(E3,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Profile Photo"}),e.jsx(Nr,{children:"Upload a professional photo for your profile"})]}),e.jsxs(De,{className:"flex items-center gap-6",children:[e.jsxs(vn,{className:"h-24 w-24",children:[e.jsx(ga,{src:g}),e.jsx(bn,{className:"text-2xl",children:P.name.split(" ").map(ae=>ae[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:Y,disabled:j}),e.jsxs(G,{variant:"outline",onClick:()=>{var ae;return(ae=document.getElementById("avatar-upload"))==null?void 0:ae.click()},disabled:j,children:[e.jsx(oa,{className:"mr-2 h-4 w-4"}),j?"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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Personal Information"}),e.jsx(Nr,{children:"Update your profile details"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",value:P.name,onChange:ae=>D({...P,name:ae.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{id:"email",type:"email",value:P.email,onChange:ae=>D({...P,email:ae.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ke,{id:"phone",type:"tel",value:P.phone,onChange:ae=>D({...P,phone:ae.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Job Title"}),e.jsx(ke,{id:"title",value:P.title,onChange:ae=>D({...P,title:ae.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"bio",children:"Bio"}),e.jsx(ur,{id:"bio",value:P.bio,onChange:ae=>D({...P,bio:ae.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(ke,{id:"areas_served",value:P.areas_served,onChange:ae=>D({...P,areas_served:ae.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(ke,{id:"years_experience",type:"number",min:"0",value:P.years_experience,onChange:ae=>D({...P,years_experience:ae.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(ke,{value:P.linkedin_url,onChange:ae=>D({...P,linkedin_url:ae.target.value}),placeholder:"LinkedIn URL"}),e.jsx(ke,{value:P.instagram_url,onChange:ae=>D({...P,instagram_url:ae.target.value}),placeholder:"Instagram URL"}),e.jsx(ke,{value:P.facebook_url,onChange:ae=>D({...P,facebook_url:ae.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(G,{onClick:de,disabled:m,children:[e.jsx(ql,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(vv,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Nr,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(De,{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:P.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(br,{checked:P.use_email_signature,onCheckedChange:ae=>D({...P,use_email_signature:ae})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Signature"}),e.jsx(y0,{content:P.email_signature,onChange:ae=>D({...P,email_signature:ae}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs(G,{onClick:de,disabled:m,children:[e.jsx(ql,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(Ne,{id:"change-password-section",children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Nr,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"newPassword",children:"New Password"}),e.jsx(ke,{id:"newPassword",type:"password",value:X.newPassword,onChange:ae=>K({...X,newPassword:ae.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(ke,{id:"confirmPassword",type:"password",value:X.confirmPassword,onChange:ae=>K({...X,confirmPassword:ae.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(G,{onClick:ce,disabled:m,children:[e.jsx(ql,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(G,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[o?e.jsx(Rm,{className:"h-5 w-5"}):e.jsx(Fv,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Nr,{children:"Receive browser notifications when new content is added"})]}),e.jsx(De,{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(br,{checked:o,onCheckedChange:ae=>{ae?d():h()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[B?e.jsx(dM,{className:"h-5 w-5"}):e.jsx(Qs,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Nr,{children:"Manage your email subscription settings"})]}),e.jsx(De,{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:B?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(br,{checked:!B,onCheckedChange:async ae=>{$(!0);try{const{error:ie}=await H.from("profiles").update({digest_opt_out:!ae}).eq("id",s==null?void 0:s.id);if(ie)throw ie;z(!ae),r({title:ae?"Subscribed":"Unsubscribed",description:ae?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(ie){r({title:"Error",description:ie.message||"Failed to update preference",variant:"destructive"})}finally{$(!1)}},disabled:F})]})})]}),e.jsx(zUt,{}),e.jsx(oXt,{})]}),e.jsx(TTe,{open:N,onClose:()=>S(!1),imageSrc:T,onCropComplete:ne,aspectRatio:1})]})})};var cXt="AspectRatio",clt=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(pn.div,{...a,ref:t,style:{...n,position:"absolute",top:0,right:0,bottom:0,left:0}})})});clt.displayName=cXt;var dXt=clt;const uXt=dXt;function hXt(){const{user:s}=As(),t=es(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),{data:l,isLoading:o}=gt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await H.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(j)throw j;return v},enabled:!!s&&a}),c=Lt({mutationFn:async()=>{const v=new Uint8Array(12);crypto.getRandomValues(v);const j=btoa(String.fromCharCode(...v)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:b}=await H.from("profiles").update({calendar_token:j}).eq("id",s==null?void 0:s.id);if(b)throw b;return j},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ue.success("Calendar subscription URL generated!")},onError:v=>{ue.error("Failed to generate calendar URL: "+v.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,h=async()=>{d&&(await navigator.clipboard.writeText(d),n(!0),ue.success("Calendar URL copied to clipboard!"),setTimeout(()=>n(!1),2e3))},m=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},x=()=>{if(d){const v=d.replace("https://","webcal://"),j=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(v)}`;window.open(j,"_blank")}},g=()=>{if(d){const v=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(v,"_blank")}};return e.jsxs(vs,{open:a,onOpenChange:i,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Fr,{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(ke,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(G,{variant:"outline",size:"icon",onClick:h,children:r?e.jsx(Hn,{className:"h-4 w-4 text-green-500"}):e.jsx(Ra,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(Yr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:x,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(Yr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:g,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(Yr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(G,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const mXt={first_timer:Qn,regular:s_,dedicated:Xl,veteran:Zi,streak_master:xc,century:Zi},fXt={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 kze(s){return s===1?e.jsx(Zi,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(s_,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Xl,{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 dlt({showUserStats:s=!0,compact:t=!1,brokerageId:r,title:n="Event Leaderboard"}){const{user:a}=As(),{data:i,isLoading:l}=rat(t?5:10,r),{data:o}=nat(a==null?void 0:a.id),{data:c}=iat(a==null?void 0:a.id),{data:d}=aat(a==null?void 0:a.id);return l?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((h,m)=>e.jsx(Vs,{className:"h-12 w-full"},m))})})]}):e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsxs(De,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:["Rank #",c]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-primary",children:o.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:o.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(xc,{className:"h-4 w-4 text-orange-500"}),e.jsx("div",{className:"text-lg font-bold",children:o.current_streak}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Streak"})]})]}),d&&d.length>0&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[d.slice(0,4).map(h=>{const m=mXt[h.badge_type]||Qn;return e.jsxs(Ge,{variant:"outline",className:`text-xs ${fXt[h.badge_type]||""}`,title:h.badge_description||"",children:[e.jsx(m,{className:"h-3 w-3 mr-1"}),h.badge_name]},h.id)}),d.length>4&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(Rn,{defaultValue:"points",className:"w-full",children:[e.jsxs(Dn,{className:"w-full mb-3",children:[e.jsx(Xt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Xt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(as,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((h,m)=>{var x,g,v;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:kze(m+1)}),e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{className:"text-xs",children:((g=(x=h.profile)==null?void 0:x.name)==null?void 0:g.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((v=h.profile)==null?void 0:v.name)||"Unknown",h.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:h.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},h.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(as,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((h,m)=>m.total_events_attended-h.total_events_attended).map((h,m)=>{var x,g,v;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:kze(m+1)}),e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{className:"text-xs",children:((g=(x=h.profile)==null?void 0:x.name)==null?void 0:g.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((v=h.profile)==null?void 0:v.name)||"Unknown",h.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:h.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},h.user_id)})})})]})]})]})}function pXt(){const s=vr(),{user:t,isAdmin:r}=As(),n=es(),{data:a,isLoading:i}=gt({queryKey:["public-events"],queryFn:async()=>{const{data:j,error:b}=await H.from("events").select("*").order("event_date",{ascending:!0});if(b)throw b;return j}}),{data:l}=gt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:j,error:b}=await H.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(b)throw b;return j},enabled:!!t}),{data:o}=gt({queryKey:["event-registration-counts"],queryFn:async()=>{let j=[],b=0;const N=1e3;for(;;){const{data:T,error:A}=await H.from("event_registrations").select("event_id").range(b,b+N-1);if(A)throw A;if(!T||T.length===0||(j=j.concat(T),T.length{S[T.event_id]=(S[T.event_id]||0)+1}),S}}),c=Lt({mutationFn:async j=>{await H.auth.refreshSession();const{data:b,error:N}=await H.functions.invoke("zoom-register",{body:{event_id:j}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:j=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),j!=null&&j.join_url?ue.success("Successfully registered! You'll receive a Zoom confirmation email."):ue.success("Successfully registered for the event!")},onError:j=>{ue.error("Failed to register: "+j.message)}}),d=Lt({mutationFn:async j=>{const{data:b,error:N}=await H.functions.invoke("zoom-unregister",{body:{event_id:j}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),ue.success("Registration cancelled and removed from Zoom")},onError:j=>{ue.error("Failed to cancel: "+j.message)}}),h=j=>l==null?void 0:l.some(b=>b.event_id===j),m=j=>{const b=l==null?void 0:l.find(N=>N.event_id===j);return b==null?void 0:b.zoom_join_url},x=j=>j.capacity?((o==null?void 0:o[j.id])||0)>=j.capacity:!1,g=(a==null?void 0:a.filter(j=>SM(j.event_date)!=="ended"))||[],v=(a==null?void 0:a.filter(j=>SM(j.event_date)==="ended"))||[];return e.jsx(_s,{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(hXt,{}),r&&e.jsx(G,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${r?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:r?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):g.length===0?e.jsx(Ne,{className:"text-center py-12",children:e.jsx(De,{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:g.map(j=>{const b=SM(j.event_date),N=C5e(j.event_date),S=b==="live",T=b==="starting_soon";return e.jsxs(Ne,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${S?"border-red-500 ring-2 ring-red-500/20":T?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${j.id}`),children:[N&&e.jsxs("div",{className:`${S?"bg-red-500":"bg-amber-500"} text-white px-3 py-1.5 flex items-center gap-2 text-sm font-medium`,children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-white"})]}),S?e.jsxs(e.Fragment,{children:[e.jsx(r_,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),j.image_url&&e.jsx(uXt,{ratio:3/2,className:"overflow-hidden",children:e.jsx("img",{src:j.image_url,alt:j.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"})}),e.jsxs(Ot,{children:[e.jsx(zt,{className:"line-clamp-2",children:j.title}),j.description&&e.jsx(Nr,{className:"line-clamp-2",children:j.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(De,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rn,{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(j.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cn,{className:"h-4 w-4"}),lF(new Date(j.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fr,{className:"h-4 w-4"}),(o==null?void 0:o[j.id])||0," registered",j.capacity&&` / ${j.capacity} spots`]})]}),e.jsx(HO,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:h(j.id)?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(j.id),disabled:d.isPending,children:[e.jsx(_r,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(G,{className:"flex-1",onClick:()=>window.open(m(j.id)||j.zoom_link,"_blank"),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(G,{className:"w-full",onClick:()=>c.mutate(j.id),disabled:c.isPending||x(j),children:x(j)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},j.id)})}),v.length>0&&e.jsxs("div",{className:"mt-12",children:[e.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:v.map(j=>e.jsx(Ne,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${j.id}`),children:e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-base line-clamp-1",children:j.title}),e.jsx(Nr,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(j.event_date))})]})},j.id))})]})]}),r&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(dlt,{showUserStats:!0})})]})]})})}const Nbe=[{value:"all",label:"All Roles",icon:fr},{value:"newest",label:"Newest Members",icon:cn},{value:"brokerage_manager",label:"Brokerage Managers",icon:RO},{value:"admin",label:"Admins",icon:Zu}];function xXt({open:s,onOpenChange:t,resourceType:r,resourceId:n,resourceTitle:a}){var ze,Te;const{user:i,isAdmin:l,isBrokerageManager:o}=As(),[c,d]=k.useState([]),[h,m]=k.useState([]),[x,g]=k.useState([]),[v,j]=k.useState([]),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,P]=k.useState(""),[D,B]=k.useState(!1),[z,F]=k.useState(!1),[$,X]=k.useState("agents"),[K,Q]=k.useState("all"),[Y,ne]=k.useState({}),de=l||o;k.useEffect(()=>{s&&i&&(l?ce():ae())},[s,i,l]),k.useEffect(()=>{s||(g([]),j([]),N(""),T(""),P(""),X("agents"),Q("all"))},[s]);const ce=async()=>{if(i){B(!0);try{const{data:ye,error:ct}=await H.from("brokerages").select("id, name").order("name");if(ct)throw ct;const ve=1e3,rt={};let Re=0,Qe=!0;for(;Qe;){const{data:nt,error:$t}=await H.from("profiles").select("brokerage_id").range(Re*ve,(Re+1)*ve-1);if($t)throw $t;nt==null||nt.forEach(lt=>{lt.brokerage_id&&(rt[lt.brokerage_id]=(rt[lt.brokerage_id]||0)+1)}),Qe=(nt==null?void 0:nt.length)===ve,Re++}m((ye==null?void 0:ye.map(nt=>({...nt,agent_count:rt[nt.id]||0})))||[]);const Ke=[];for(Re=0,Qe=!0;Qe;){const{data:nt,error:$t}=await H.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Re*ve,(Re+1)*ve-1);if($t)throw $t;nt&&Ke.push(...nt),Qe=(nt==null?void 0:nt.length)===ve,Re++}const Ce={};for(Re=0,Qe=!0;Qe;){const{data:nt,error:$t}=await H.from("user_roles").select("user_id, role").range(Re*ve,(Re+1)*ve-1);if($t)throw $t;nt==null||nt.forEach(lt=>{Ce[lt.user_id]||(Ce[lt.user_id]=[]),Ce[lt.user_id].push(lt.role)}),Qe=(nt==null?void 0:nt.length)===ve,Re++}ne(Ce),d(Ke.map(nt=>{var $t;return{id:nt.id,name:nt.name,email:nt.email,brokerage_name:(($t=nt.brokerages)==null?void 0:$t.name)||"No Brokerage",roles:Ce[nt.id]||[],created_at:nt.created_at}}))}catch(ye){console.error("Error loading data:",ye),ue.error("Failed to load agents and brokerages")}finally{B(!1)}}},ae=async()=>{if(i){B(!0);try{const{data:ye}=await H.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ye!=null&&ye.brokerage_id)){ue.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:ct,error:ve}=await H.from("profiles").select("id, name, email").eq("brokerage_id",ye.brokerage_id).neq("id",i.id).order("name");if(ve)throw ve;d(ct||[])}catch(ye){console.error("Error loading agents:",ye),ue.error("Failed to load agents")}finally{B(!1)}}},ie=c.filter(ye=>{var ve;const ct=ye.name.toLowerCase().includes(b.toLowerCase())||ye.email.toLowerCase().includes(b.toLowerCase())||((ve=ye.brokerage_name)==null?void 0:ve.toLowerCase().includes(b.toLowerCase()));if(l&&K!=="all"&&K!=="newest"){const rt=Y[ye.id]||[];return ct&&rt.includes(K)}return ct}).sort((ye,ct)=>K==="newest"?(ct.created_at||"").localeCompare(ye.created_at||""):0),me=h.filter(ye=>ye.name.toLowerCase().includes(S.toLowerCase())),oe=()=>{x.length===ie.length?g([]):g(ie.map(ye=>ye.id))},ge=()=>{v.length===me.length?j([]):j(me.map(ye=>ye.id))},be=ye=>{if(!de){g([ye]);return}g(ct=>ct.includes(ye)?ct.filter(ve=>ve!==ye):[...ct,ye])},Oe=ye=>{j(ct=>ct.includes(ye)?ct.filter(ve=>ve!==ye):[...ct,ye])},Me=async()=>{if(!(x.length>0||v.length>0)){ue.error("Please select at least one agent or brokerage to share with");return}F(!0);try{const{data:ct,error:ve}=await H.functions.invoke("send-share-notification",{body:{recipientIds:x,brokerageIds:v,resourceType:r,resourceId:n,resourceTitle:a,message:A.trim()||void 0}});if(ve)throw ve;const rt=(ct==null?void 0:ct.sharesCreated)||x.length;ue.success(`Shared with ${rt} agent${rt!==1?"s":""}`),t(!1)}catch(ct){console.error("Error sharing resource:",ct),ue.error("Failed to share resource")}finally{F(!1)}},Pe=ye=>ye.split(" ").map(ct=>ct[0]).join("").toUpperCase().slice(0,2),Ee=ye=>{const ct=Y[ye]||[];return ct.includes("admin")?e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):ct.includes("brokerage_manager")?e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},$e=x.length+v.length,Se=K!=="all"&&K!=="newest"?ie.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(js,{className:"flex-shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Fr,{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(Rn,{value:$,onValueChange:X,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Xt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),x.length>0&&e.jsx(Ge,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:x.length})]}),e.jsxs(Xt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),v.length>0&&e.jsx(Ge,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:v.length})]})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, or brokerage...",value:b,onChange:ye=>N(ye.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:K,onValueChange:Q,children:[e.jsxs(Os,{className:"w-[180px]",children:[e.jsx(s0,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Us,{placeholder:"Filter by role"})]}),e.jsx(Fs,{children:Nbe.map(ye=>e.jsx(mt,{value:ye.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ye.label})]})},ye.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:oe,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Se!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Se," ",(ze=Nbe.find(ye=>ye.value===K))==null?void 0:ze.label]}),e.jsxs("span",{className:"font-medium",children:[x.length," selected"]})]})]}),e.jsx(ti,{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"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(fr,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:K!=="all"?`No ${(Te=Nbe.find(ye=>ye.value===K))==null?void 0:Te.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ie.map(ye=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(ye.id)?"bg-accent":""}`,onClick:()=>be(ye.id),children:[e.jsx(Ei,{checked:x.includes(ye.id),onCheckedChange:()=>be(ye.id),className:"flex-shrink-0"}),e.jsx(vn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(bn,{className:"text-xs bg-primary/10 text-primary",children:Pe(ye.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:ye.name}),Ee(ye.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ye.email,ye.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ye.brokerage_name]})]})]})]},ye.id))})})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search brokerages...",value:S,onChange:ye=>T(ye.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:ge,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1.5"}),v.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[v.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(ti,{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"})}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Sa,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No brokerages found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:me.map(ye=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${v.includes(ye.id)?"bg-accent":""}`,onClick:()=>Oe(ye.id),children:[e.jsx(Ei,{checked:v.includes(ye.id),onCheckedChange:()=>Oe(ye.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Sa,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ye.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ye.agent_count," agent",ye.agent_count!==1?"s":""]})]})]},ye.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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents...",value:b,onChange:ye=>N(ye.target.value),className:"pl-9"})]}),de&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:oe,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[x.length," selected"]})]}),e.jsx(ti,{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"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(fr,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ie.map(ye=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(ye.id)?"bg-accent":""}`,onClick:()=>be(ye.id),children:[e.jsx(Ei,{checked:x.includes(ye.id),onCheckedChange:()=>be(ye.id),className:"flex-shrink-0"}),e.jsx(vn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(bn,{className:"text-xs bg-primary/10 text-primary",children:Pe(ye.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ye.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ye.email})]})]},ye.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(he,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(ur,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:ye=>P(ye.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:Me,disabled:$e===0||z,children:z?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(Zr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function DP({resourceType:s,resourceId:t,resourceTitle:r,variant:n="outline",size:a="sm",className:i=""}){const[l,o]=k.useState(!1),{user:c}=As();return c?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:n,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Pc,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(xXt,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:r})]}):null}function gXt(){const{eventId:s}=Xi(),t=vr(),{user:r}=As(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(0),[d,h]=k.useState(!0),[m,x]=k.useState(!1);k.useEffect(()=>{s&&g()},[s,r]);const g=async()=>{try{const{data:T,error:A}=await H.from("events").select("*").eq("id",s).single();if(A)throw A;a(T);const{count:P}=await H.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(P||0),r){const{data:D}=await H.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",r.id).maybeSingle();l(D)}}catch(T){console.error("Error loading event:",T),ue.error("Failed to load event"),t("/events")}finally{h(!1)}},v=async()=>{if(!(!r||!n)){x(!0);try{const{error:T}=await H.auth.refreshSession();if(T){console.error("Session refresh failed:",T),ue.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await H.functions.invoke("zoom-unregister",{body:{event_id:n.id}});if(A)throw A;ue.success("Successfully cancelled registration"),l(null),c(P=>P-1)}else{const{data:A,error:P}=await H.functions.invoke("zoom-register",{body:{event_id:n.id}});if(P)throw P;ue.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(D=>D+1)}}catch(T){console.error("Registration error:",T),ue.error(i?"Failed to cancel registration":"Failed to register for event")}finally{x(!1)}}},j=T=>{var A,P,D;if(T.includes("iframe.mediadelivery.net")||T.includes("video.bunnycdn.com")){const B=T.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(B)return`https://iframe.mediadelivery.net/embed/${B[1]}/${B[2]}?autoplay=false&preload=true`}if(T.includes("youtube.com")||T.includes("youtu.be")){const B=T.includes("youtu.be")?(A=T.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(P=T.split("v=")[1])==null?void 0:P.split("&")[0];if(B)return`https://www.youtube.com/embed/${B}`}if(T.includes("vimeo.com")){const B=(D=T.split("vimeo.com/")[1])==null?void 0:D.split("?")[0];if(B)return`https://player.vimeo.com/video/${B}`}return T};if(d)return e.jsx(_s,{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(_s,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(G,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const b=Xv(new Date(n.event_date)),N=n.capacity&&o>=n.capacity,S=(i==null?void 0:i.zoom_join_url)||n.zoom_link;return e.jsx(_s,{title:n.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(G,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Events"]}),n.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:n.image_url,alt:n.title,className:"w-full h-full object-cover"}),b&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ge,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:n.title}),e.jsx(DP,{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(mf,{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:j(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(Ne,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(rn,{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:lF(new Date(n.event_date))})]})]}),n.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(fr,{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(mi,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!b&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(G,{className:"w-full gap-2",onClick:()=>window.open(S,"_blank"),children:[e.jsx(Yr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(G,{variant:"outline",className:"w-full",onClick:v,disabled:m,children:[m?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(G,{className:"w-full gap-2",onClick:v,disabled:m||(N??!1),children:m?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):N?"Event Full":"Register Now"})}),b&&i&&e.jsxs(G,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(n.zoom_link,"_blank"),children:[e.jsx(Yr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const yXt=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(sn,{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(gx,{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(n0,{className:"h-6 w-6"}),path:"/mission-control/presentations",category:"Marketing",color:"bg-amber-500/15 text-amber-600"},{id:"landing-pages",name:"Landing Pages",description:"Build custom landing pages to capture leads",icon:e.jsx(ln,{className:"h-6 w-6"}),path:"/mission-control/landing-pages",category:"Marketing",color:"bg-emerald-500/15 text-emerald-600"},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in to capture visitor info",icon:e.jsx(Th,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(jr,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(Qs,{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(Nh,{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(Zr,{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(vv,{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(vO,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"}],vXt=()=>{const{user:s,isAdmin:t}=As(),r=vr(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[g,v]=k.useState(new Set);k.useEffect(()=>{j()},[s]);const j=async()=>{try{const{data:F}=await H.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),$=(F==null?void 0:F.map(ie=>ie.tag))||[],{data:X,error:K}=await H.from("app_tiles").select("*").order("name");if(K)throw K;const[{data:Q},{data:Y}]=await Promise.all([H.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),H.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id)]),ne=new Set((Q==null?void 0:Q.map(ie=>ie.app_id))||[]);x(ne);const de=new Set((Y||[]).map(ie=>ie.tool_id));v(de);const ae=((X==null?void 0:X.filter(ie=>!ie.required_tags||ie.required_tags.length===0?!0:ie.required_tags.some(me=>$.includes(me))))||[]).sort((ie,me)=>ie.name==="LevelUp Members Portal"?-1:me.name==="LevelUp Members Portal"?1:0);a(ae)}catch(F){console.error("Error loading apps:",F),ue.error("Failed to load apps")}finally{l(!1)}},b=async F=>{var X;const $=window.open("about:blank","_blank");try{const{data:K,error:Q}=await H.auth.getSession();if(Q||!K.session){$==null||$.close(),ue.error("Session expired. Please refresh the page and try again.");return}const Y=K.session.access_token;await H.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:F.app_id,app_name:F.name,user_agent:navigator.userAgent});const{data:ne,error:de}=await H.functions.invoke("sso-launch",{body:{app_id:F.app_id},headers:{Authorization:`Bearer ${Y}`}});if(de)throw de;ne!=null&&ne.redirect_url?$&&!$.closed?($.location.href=ne.redirect_url,(X=$.focus)==null||X.call($)):window.location.assign(ne.redirect_url):($==null||$.close(),ue.error("Launch link unavailable"))}catch(K){$==null||$.close(),console.error("Error launching app:",K),ue.error("Failed to launch app. Please try again.")}},N=async(F,$)=>{F.stopPropagation();const X=m.has($);try{if(X){const{error:K}=await H.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",$);if(K)throw K;x(Q=>{const Y=new Set(Q);return Y.delete($),Y}),ue.success("Removed from favorites")}else{const{error:K}=await H.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:$});if(K)throw K;x(Q=>new Set(Q).add($)),ue.success("Added to favorites")}}catch(K){console.error("Error toggling favorite:",K),ue.error("Failed to update favorites")}},S=async(F,$)=>{F.stopPropagation();const X=g.has($);try{if(X){const{error:K}=await H.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",$);if(K)throw K;v(Q=>{const Y=new Set(Q);return Y.delete($),Y}),ue.success("Removed from favorites")}else{const{error:K}=await H.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:$});if(K)throw K;v(Q=>new Set(Q).add($)),ue.success("Added to favorites")}}catch(K){console.error("Error toggling tool favorite:",K),ue.error("Failed to update favorites")}},T=n.filter(F=>{var X;const $=F.name.toLowerCase().includes(o.toLowerCase())||((X=F.description)==null?void 0:X.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?$&&m.has(F.id):$}),A=yXt.filter(F=>{if(F.adminOnly&&!t)return!1;const $=F.name.toLowerCase().includes(o.toLowerCase())||F.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?$&&g.has(F.id):$}),P=A.reduce((F,$)=>(F[$.category]||(F[$.category]=[]),F[$.category].push($),F),{}),D=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(_s,{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 B=d==="all"||d==="tools"||d==="favorites",z=d==="all"||d==="apps"||d==="favorites";return e.jsxs(_s,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:F=>c(F.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:D.map(F=>e.jsxs("button",{onClick:()=>h(F.id),className:Bt("pb-3 text-sm font-medium transition-colors relative",d===F.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[F.label,d===F.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},F.id))}),B&&Object.keys(P).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(i0,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(P).map(([F,$])=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-muted px-2.5 py-1 rounded-full",children:F})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:$.map(X=>{const K=g.has(X.id);return e.jsxs("div",{onClick:()=>r(X.path),className:Bt("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",X.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[X.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:Bt("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",X.color||"bg-primary/10 text-primary"),children:X.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:[X.name,X.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:X.description})]}),e.jsx("button",{className:Bt("flex-shrink-0 p-1 transition-colors",K?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:Q=>S(Q,X.id),children:e.jsx(Bg,{className:Bt("h-5 w-5",K&&"fill-current")})})]},X.id)})})]},F))]}),z&&e.jsxs("div",{children:[d==="all"&&T.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),T.length===0&&d!=="all"&&!(d==="favorites"&&A.length>0)?e.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:d==="favorites"?e.jsxs(e.Fragment,{children:[e.jsx(Bg,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app or tool to add it to your favorites"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Kc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(G,{className:"mt-4",onClick:()=>r("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:T.map(F=>{const $=m.has(F.id),X=F.name.toLowerCase().includes("agent review")||F.app_id==="agent_review";return e.jsxs("div",{className:"group flex flex-col p-5 bg-card rounded-xl border border-border transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"flex items-start gap-4 cursor-pointer",onClick:()=>b(F),children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:F.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:F.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:F.description})]}),e.jsx("button",{className:Bt("flex-shrink-0 p-1 transition-colors",$?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:K=>N(K,F.id),children:e.jsx(Bg,{className:Bt("h-5 w-5",$&&"fill-current")})})]}),X&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:K=>K.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},F.id)})})]}),B&&z&&T.length===0&&A.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(fn,{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"})]})]})},bXt=()=>{var T;const s=vr(),{isAdmin:t}=As(),[r,n]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState("all"),[c,d]=k.useState("grid"),{data:h=[]}=gt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:P}=await H.from("template_categories").select("*").order("name");if(P)throw P;return A}}),{data:m=[]}=gt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:P}=await H.from("template_types").select("*").order("name");if(P)throw P;return A}}),{data:x=[],isLoading:g}=gt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:P}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(P)throw P;const{data:D,error:B}=await H.from("template_links").select("*").order("sort_order");if(B)throw B;const z=async ne=>{let ce=0;const ae=[];for(;;){const{data:ie,error:me}=await ne().range(ce,ce+1e3-1);if(me)throw me;if(!ie||ie.length===0||(ae.push(...ie),ie.length<1e3))break;ce+=1e3}return ae},F=await z(()=>H.from("template_likes").select("template_id")),$=await z(()=>H.from("template_comments").select("template_id")),X=new Map;F.forEach(ne=>{X.set(ne.template_id,(X.get(ne.template_id)||0)+1)});const K=new Map;$.forEach(ne=>{K.set(ne.template_id,(K.get(ne.template_id)||0)+1)});const Q=new Map;return t&&(await z(()=>H.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(de=>{Q.set(de.resource_id,(Q.get(de.resource_id)||0)+1)}),(A||[]).map(ne=>({...ne,links:(D||[]).filter(de=>de.template_id===ne.id)||[],likesCount:X.get(ne.id)||0,commentsCount:K.get(ne.id)||0,viewsCount:Q.get(ne.id)||0}))}}),v=x.filter(A=>{var z;const P=A.name.toLowerCase().includes(r.toLowerCase())||((z=A.description)==null?void 0:z.toLowerCase().includes(r.toLowerCase())),D=a==="all"||A.category_id===a,B=l==="all"||A.type_id===l;return P&&D&&B}),j=()=>{n(""),i("all"),o("all")},b=r||a!=="all"||l!=="all",N=(T=[...x].sort((A,P)=>new Date(P.publish_date||P.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:T.id,S=A=>{s(`/templates/${A}`)};return e.jsx(_s,{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"})]}),!g&&x.filter(A=>A.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:x.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>S(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===N&&e.jsx(Ge,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(De,{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:H8(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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search templates...",value:r,onChange:A=>n(A.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:a,onValueChange:i,children:[e.jsx(Os,{className:"w-full sm:w-48",children:e.jsx(Us,{placeholder:"All Categories"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Categories"}),h.map(A=>e.jsx(mt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(zs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-full sm:w-48",children:e.jsx(Us,{placeholder:"All Types"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),m.map(A=>e.jsx(mt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[b&&e.jsx(G,{variant:"outline",size:"sm",onClick:j,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(Sf,{className:"h-4 w-4"})}),e.jsx(G,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(lm,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[v.length," template",v.length!==1?"s":""," found"]}),g&&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,P)=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(Vs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Vs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Vs,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Vs,{className:"h-5 w-16"}),e.jsx(Vs,{className:"h-5 w-20"})]})]})},P))}),!g&&v.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:b?"No templates match your filters":"No templates available yet"}),b&&e.jsx(G,{variant:"outline",onClick:j,children:"Clear Filters"})]}),!g&&v.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:v.map(A=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>S(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===N&&e.jsx(Ge,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),A.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(xo,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(De,{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:H8(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:A.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mh,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{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(jn,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:P=>{P.stopPropagation(),S(A.id)},children:[e.jsx(Yr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var _Xt="Separator",Sze="horizontal",wXt=["horizontal","vertical"],ult=k.forwardRef((s,t)=>{const{decorative:r,orientation:n=Sze,...a}=s,i=jXt(n)?n:Sze,o=r?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(pn.div,{"data-orientation":i,...o,...a,ref:t})});ult.displayName=_Xt;function jXt(s){return wXt.includes(s)}var hlt=ult;const po=k.forwardRef(({className:s,orientation:t="horizontal",decorative:r=!0,...n},a)=>e.jsx(hlt,{ref:a,decorative:r,orientation:t,className:Bt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...n}));po.displayName=hlt.displayName;const NXt=()=>{const{templateId:s}=Xi(),t=vr(),{user:r,isAdmin:n}=As(),{toast:a}=Ea(),i=es(),{trackEngagement:l}=MP(),[o,c]=k.useState(""),{data:d,isLoading:h}=gt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:P}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(P)throw P;const{data:D}=await H.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:B}=await H.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:D||[],guides:B||[]}},enabled:!!s}),{data:m=[]}=gt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:P}=await H.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(P)throw P;return(A||[]).map(D=>D.resource_kits).filter(Boolean)},enabled:!!s});k.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:x=[]}=gt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:P}=await H.from("template_likes").select("*").eq("template_id",s);if(P)throw P;return A},enabled:!!s}),{data:g=[]}=gt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:P}=await H.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(P)throw P;const D=[...new Set(A.map(F=>F.user_id))],{data:B}=await H.from("profiles").select("id, name").in("id",D),z=new Map((B==null?void 0:B.map(F=>[F.id,F.name]))||[]);return A.map(F=>({...F,user_name:z.get(F.user_id)||"Unknown User"}))},enabled:!!s}),v=Lt({mutationFn:async A=>{const{error:P}=await H.from("template_comments").insert({template_id:s,user_id:r.id,content:A});if(P)throw P},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),j=Lt({mutationFn:async A=>{const{error:P}=await H.from("template_comments").delete().eq("id",A);if(P)throw P},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),b=Lt({mutationFn:async()=>{const A=x.find(P=>P.user_id===(r==null?void 0:r.id));if(A){const{error:P}=await H.from("template_likes").delete().eq("id",A.id);if(P)throw P}else{const{error:P}=await H.from("template_likes").insert({template_id:s,user_id:r.id});if(P)throw P}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),N=x.some(A=>A.user_id===(r==null?void 0:r.id)),S=A=>A.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2),T=A=>{A.preventDefault(),!(!o.trim()||!r)&&v.mutate(o.trim())};return h?e.jsx(_s,{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(_s,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/templates",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Templates"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:d.name}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d.category&&e.jsx(Ge,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Ge,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Kn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(DP,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(G,{variant:N?"default":"outline",className:"gap-2 rounded-full",onClick:()=>b.mutate(),disabled:!r||b.isPending,children:[e.jsx(Mh,{className:`h-4 w-4 ${N?"fill-current":""}`}),x.length," ",x.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(xo,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(A=>e.jsxs(G,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(A.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(G,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(A.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:A.name}),A.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(A.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),m.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Pl,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:m.map(A=>e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${A.id}`),children:[A.featured_image_url?e.jsx("img",{src:A.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Pl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(tc,{className:"h-5 w-5"}),"Comments (",g.length,")"]}),r?e.jsxs("form",{onSubmit:T,className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||v.isPending,children:e.jsx(Zr,{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:g.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):g.map(A=>e.jsx(Ne,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(bn,{className:"text-sm",children:S(A.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:A.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:al(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>j.mutate(A.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(_s,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(xo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/templates",children:"Back to Templates"})})]})})},kXt=()=>{const{user:s}=As(),[t,r]=k.useState(""),[n,a]=k.useState("all"),{data:i=[]}=gt({queryKey:["academy-categories"],queryFn:async()=>{const{data:x,error:g}=await H.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(g)throw g;return x}}),{data:l=[],isLoading:o}=gt({queryKey:["academy-videos"],queryFn:async()=>{const{data:x,error:g}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;const{data:v,error:j}=await H.from("academy_resources").select("*").order("sort_order");if(j)throw j;return x.map(N=>({...N,resources:(v==null?void 0:v.filter(S=>S.video_id===N.id))||[]}))}}),{data:c=[]}=gt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:x,error:g}=await H.from("academy_video_likes").select("video_id, user_id");if(g)throw g;return x}}),d=l.filter(x=>{var j;const g=t===""||x.title.toLowerCase().includes(t.toLowerCase())||((j=x.description)==null?void 0:j.toLowerCase().includes(t.toLowerCase())),v=n==="all"||x.category_id===n;return g&&v}),h=x=>c.filter(g=>g.video_id===x).length,m=x=>c.some(g=>g.video_id===x&&g.user_id===(s==null?void 0:s.id));return e.jsx(_s,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search videos...",value:t,onChange:x=>r(x.target.value),className:"pl-10"})]})}),e.jsx(Rn,{value:n,onValueChange:a,children:e.jsxs(Dn,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Xt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(x=>e.jsx(Xt,{value:x.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:x.name},x.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(sn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(x=>e.jsx(Kn,{to:`/academy/${x.id}`,children:e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[x.thumbnail_url?e.jsx("img",{src:x.thumbnail_url,alt:x.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sn,{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(Ho,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),x.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),x.duration]})]}),e.jsxs(Ot,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(zt,{className:"text-lg line-clamp-2",children:x.title})}),x.category&&e.jsx(Ge,{variant:"secondary",className:"w-fit",children:x.category.name})]}),e.jsxs(De,{className:"pt-0",children:[x.description&&e.jsx(Nr,{className:"line-clamp-2",children:x.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mh,{className:`h-4 w-4 ${m(x.id)?"fill-primary text-primary":""}`}),h(x.id)]}),x.resources&&x.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4"}),x.resources.length]})]})]})]})},x.id))})]})})};function mlt({resourceType:s,resourceId:t}){const{data:r=[]}=gt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:n,error:a}=await H.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 H.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(pl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(n=>e.jsx(Kn,{to:`/templates/${n.id}`,children:e.jsxs(Ge,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 transition-colors gap-1.5 px-3 py-1.5 text-xs font-medium rounded-full",children:[e.jsx(pl,{className:"h-3 w-3"}),n.name]})},n.id))})]})}const SXt=(s,t)=>{if(t==="bunny_stream"){let r=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(t==="youtube"){const r=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,n=s.match(r);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const r=/vimeo\.com\/(?:video\/)?(\d+)/,n=s.match(r);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const r=/loom\.com\/share\/([a-zA-Z0-9]+)/,n=s.match(r);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},CXt=()=>{const{videoId:s}=Xi();vr();const{user:t,isAdmin:r}=As(),{toast:n}=Ea(),a=es(),{trackEngagement:i}=MP(),[l,o]=k.useState(""),{data:c,isLoading:d}=gt({queryKey:["academy-video",s],queryFn:async()=>{const{data:T,error:A}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:P}=await H.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...T,resources:P||[]}},enabled:!!s});k.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:h=[]}=gt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:T,error:A}=await H.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return T},enabled:!!s}),{data:m=[]}=gt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:T,error:A}=await H.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const P=[...new Set(T.map(z=>z.user_id))],{data:D}=await H.from("profiles").select("id, name").in("id",P),B=new Map((D==null?void 0:D.map(z=>[z.id,z.name]))||[]);return T.map(z=>({...z,user_name:B.get(z.user_id)||"Unknown User"}))},enabled:!!s}),x=Lt({mutationFn:async T=>{const{error:A}=await H.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:T});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),g=Lt({mutationFn:async T=>{const{error:A}=await H.from("academy_video_comments").delete().eq("id",T);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),n({title:"Comment deleted"})}}),v=Lt({mutationFn:async()=>{const T=h.find(A=>A.user_id===(t==null?void 0:t.id));if(T){const{error:A}=await H.from("academy_video_likes").delete().eq("id",T.id);if(A)throw A}else{const{error:A}=await H.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),j=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>{switch(T==null?void 0:T.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},N=T=>T.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),S=T=>{T.preventDefault(),!(!l.trim()||!t)&&x.mutate(l.trim())};return d?e.jsx(_s,{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(_s,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/academy",children:[e.jsx(wa,{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:SXt(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(sn,{className:"h-16 w-16 opacity-50"}),e.jsx(G,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(Ge,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Kn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(DP,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(G,{variant:j?"default":"outline",className:"gap-2 w-fit",onClick:()=>v.mutate(),disabled:!t||v.isPending,children:[e.jsx(Mh,{className:`h-4 w-4 ${j?"fill-current":""}`}),h.length," ",h.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.resources&&c.resources.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(T=>e.jsxs("a",{href:T.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:b(T.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:T.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:T.file_type})]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]},T.id))})]})}),e.jsx(mlt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(tc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||x.isPending,children:e.jsx(Zr,{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(Ne,{children:e.jsx(De,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(Ne,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(bn,{className:"text-sm",children:N(T.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:al(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>g.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(_s,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(sn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/academy",children:"Back to Academy"})})]})})};function TXt(){const s=vr(),[t,r]=k.useState(""),{data:n,isLoading:a}=gt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:g,error:v}=await H.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return g}}),{data:i}=gt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:g,error:v}=await H.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(v)throw v;return g}}),{data:l}=gt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:g,error:v}=await H.from("resource_kit_likes").select("kit_id");if(v)throw v;return g}}),{data:o}=gt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:g,error:v}=await H.from("resource_kit_comments").select("kit_id");if(v)throw v;return g}}),c=n==null?void 0:n.filter(g=>{var v;return g.name.toLowerCase().includes(t.toLowerCase())||((v=g.description)==null?void 0:v.toLowerCase().includes(t.toLowerCase()))}),d=g=>(i==null?void 0:i.filter(v=>v.kit_id===g))||[],h=g=>(l==null?void 0:l.filter(v=>v.kit_id===g).length)||0,m=g=>(o==null?void 0:o.filter(v=>v.kit_id===g).length)||0,x=g=>{s(`/toolbox/${g}`)};return e.jsx(_s,{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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search resource kits...",value:t,onChange:g=>r(g.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((g,v)=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(Vs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Vs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Vs,{className:"h-4 w-full mb-4"}),e.jsx(Vs,{className:"h-4 w-2/3"})]})},v))}):(c==null?void 0:c.length)===0?e.jsxs(Ne,{className:"p-12 text-center",children:[e.jsx(Pl,{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(g=>{const v=d(g.id).length,j=h(g.id),b=m(g.id);return e.jsxs(Ne,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>x(g.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:g.featured_image_url?e.jsx("img",{src:g.featured_image_url,alt:g.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(Pl,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:g.name}),g.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:H8(g.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4"}),v," file",v!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mh,{className:"h-3.5 w-3.5"}),j]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{className:"h-3.5 w-3.5"}),b]})]})]})]})]},g.id)})})]})})}const EXt=()=>{const{kitId:s}=Xi(),{user:t,isAdmin:r}=As(),{toast:n}=Ea(),a=es(),{trackEngagement:i}=MP(),[l,o]=k.useState(""),{data:c,isLoading:d}=gt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:T,error:A}=await H.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:P}=await H.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:D}=await H.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...T,files:P||[],links:D||[]}},enabled:!!s});k.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:h=[]}=gt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:T,error:A}=await H.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return T},enabled:!!s}),{data:m=[]}=gt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:T,error:A}=await H.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const P=[...new Set(T.map(z=>z.user_id))],{data:D}=await H.from("profiles").select("id, name").in("id",P),B=new Map((D==null?void 0:D.map(z=>[z.id,z.name]))||[]);return T.map(z=>({...z,user_name:B.get(z.user_id)||"Unknown User"}))},enabled:!!s}),x=Lt({mutationFn:async T=>{const{error:A}=await H.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:T});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),g=Lt({mutationFn:async T=>{const{error:A}=await H.from("resource_kit_comments").delete().eq("id",T);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),n({title:"Comment deleted"})}}),v=Lt({mutationFn:async()=>{const T=h.find(A=>A.user_id===(t==null?void 0:t.id));if(T){const{error:A}=await H.from("resource_kit_likes").delete().eq("id",T.id);if(A)throw A}else{const{error:A}=await H.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),j=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>T.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),N=T=>T?T<1024?T+" B":T<1024*1024?(T/1024).toFixed(1)+" KB":(T/(1024*1024)).toFixed(1)+" MB":"",S=T=>{T.preventDefault(),!(!l.trim()||!t)&&x.mutate(l.trim())};return d?e.jsx(_s,{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(_s,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/toolbox",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Kn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(DP,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(G,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!t||v.isPending,children:[e.jsx(Mh,{className:`h-4 w-4 ${j?"fill-current":""}`}),h.length," ",h.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.files&&c.files.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(T=>e.jsxs("a",{href:T.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ln,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:T.name}),T.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:N(T.file_size)})]})]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},T.id))})]})}),c.links&&c.links.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(T=>e.jsxs("a",{href:T.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:e.jsx(Yr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:T.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},T.id))})]})}),e.jsx(mlt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(tc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||x.isPending,children:e.jsx(Zr,{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(Ne,{children:e.jsx(De,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(Ne,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(bn,{className:"text-sm",children:b(T.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:al(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>g.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(_s,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Pl,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},AXt=()=>{const s=vr(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),{data:i=[],isLoading:l}=gt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:h}=await H.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(h)throw h;const{data:m,error:x}=await H.from("social_swag_links").select("*").order("sort_order");if(x)throw x;const{data:g}=await H.from("social_swag_likes").select("swag_id"),{data:v}=await H.from("social_swag_comments").select("swag_id"),j=new Map;g==null||g.forEach(S=>{j.set(S.swag_id,(j.get(S.swag_id)||0)+1)});const b=new Map;return v==null||v.forEach(S=>{b.set(S.swag_id,(b.get(S.swag_id)||0)+1)}),(d||[]).map(S=>({...S,links:(m||[]).filter(T=>T.swag_id===S.id)||[],likesCount:j.get(S.id)||0,commentsCount:b.get(S.id)||0}))}}),o=i.filter(d=>{var m;return d.title.toLowerCase().includes(t.toLowerCase())||((m=d.description)==null?void 0:m.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(_s,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search social swag...",value:t,onChange:d=>r(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Sf,{className:"h-4 w-4"})}),e.jsx(G,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(lm,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,h)=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(Vs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Vs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Vs,{className:"h-4 w-full mb-4"})]})},h))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx(G,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(xo,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(De,{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(Mh,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:h=>{h.stopPropagation(),c(d.id)},children:[e.jsx(Yr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var ji=function(){return ji=Object.assign||function(t){for(var r,n=1,a=arguments.length;n1&&(c||!d),m=t>1&&(d||!c),x=function(){n&&i(n)},g=function(){a&&i(a)};return e.jsx(cQt,{displayMonth:s.displayMonth,hideNext:h,hidePrevious:m,nextMonth:a,previousMonth:n,onPreviousClick:x,onNextClick:g})}function dQt(s){var t,r=vc(),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:xlt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(Cze,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Cze,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(Tze,{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(Tze,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:n.caption,style:i.caption,children:d})}function uQt(s){var t=vc(),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 hQt(s,t,r){for(var n=r?v_(new Date):Fm(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Hl(n,i);a.push(l)}return a}function mQt(){var s=vc(),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=hQt(a,i,l);return e.jsxs("tr",{style:r.head_row,className:t.head_row,children:[n&&e.jsx("td",{style:r.head_cell,className:t.head_cell}),d.map(function(h,m){return e.jsx("th",{scope:"col",className:t.head_cell,style:r.head_cell,"aria-label":c(h,{locale:a}),children:o(h,{locale:a})},m)})]})}function fQt(){var s,t=vc(),r=t.classNames,n=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:mQt;return e.jsx("thead",{style:n.head,className:r.head,children:e.jsx(i,{})})}function pQt(s){var t=vc(),r=t.locale,n=t.formatters.formatDay;return e.jsx(e.Fragment,{children:n(s.date,{locale:r})})}var ETe=k.createContext(void 0);function xQt(s){if(!cz(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(ETe.Provider,{value:t,children:s.children})}return e.jsx(gQt,{initialProps:s.initialProps,children:s.children})}function gQt(s){var t=s.initialProps,r=s.children,n=t.selected,a=t.min,i=t.max,l=function(d,h,m){var x,g;(x=t.onDayClick)===null||x===void 0||x.call(t,d,h,m);var v=!!(h.selected&&a&&(n==null?void 0:n.length)===a);if(!v){var j=!!(!h.selected&&i&&(n==null?void 0:n.length)===i);if(!j){var b=n?flt([],n):[];if(h.selected){var N=b.findIndex(function(S){return $l(d,S)});b.splice(N,1)}else b.push(d);(g=t.onSelect)===null||g===void 0||g.call(t,b,d,h,m)}}},o={disabled:[]};n&&o.disabled.push(function(d){var h=i&&n.length>i-1,m=n.some(function(x){return $l(x,d)});return!!(h&&!m)});var c={selected:n,onDayClick:l,modifiers:o};return e.jsx(ETe.Provider,{value:c,children:r})}function ATe(){var s=k.useContext(ETe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function yQt(s,t){var r=t||{},n=r.from,a=r.to;return n&&a?$l(a,s)&&$l(n,s)?void 0:$l(a,s)?{from:a,to:void 0}:$l(n,s)?void 0:y5(n,s)?{from:s,to:a}:{from:n,to:s}:a?y5(s,a)?{from:a,to:s}:{from:s,to:a}:n?v5(s,n)?{from:s,to:n}:{from:n,to:s}:{from:s,to:void 0}}var MTe=k.createContext(void 0);function vQt(s){if(!dz(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(MTe.Provider,{value:t,children:s.children})}return e.jsx(bQt,{initialProps:s.initialProps,children:s.children})}function bQt(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(g,v,j){var b,N;(b=t.onDayClick)===null||b===void 0||b.call(t,g,v,j);var S=yQt(g,n);(N=t.onSelect)===null||N===void 0||N.call(t,S,g,v,j)},h={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(h.range_start=[i],l?(h.range_end=[l],$l(i,l)||(h.range_middle=[{after:i,before:l}])):h.range_end=[i]):l&&(h.range_start=[l],h.range_end=[l]),o&&(i&&!l&&h.disabled.push({after:fde(i,o-1),before:Hl(i,o-1)}),i&&l&&h.disabled.push({after:i,before:Hl(i,o-1)}),!i&&l&&h.disabled.push({after:fde(l,o-1),before:Hl(l,o-1)})),c){if(i&&!l&&(h.disabled.push({before:Hl(i,-c+1)}),h.disabled.push({after:Hl(i,c-1)})),i&&l){var m=fx(l,i)+1,x=c-m;h.disabled.push({before:fde(i,x)}),h.disabled.push({after:Hl(l,x)})}!i&&l&&(h.disabled.push({before:Hl(l,-c+1)}),h.disabled.push({after:Hl(l,c-1)}))}return e.jsx(MTe.Provider,{value:{selected:n,onDayClick:d,modifiers:h},children:r})}function ITe(){var s=k.useContext(MTe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Pde(s){return Array.isArray(s)?flt([],s):s!==void 0?[s]:[]}function _Qt(s){var t={};return Object.entries(s).forEach(function(r){var n=r[0],a=r[1];t[n]=Pde(a)}),t}var f0;(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"})(f0||(f0={}));var wQt=f0.Selected,fb=f0.Disabled,jQt=f0.Hidden,NQt=f0.Today,kbe=f0.RangeEnd,Sbe=f0.RangeMiddle,Cbe=f0.RangeStart,kQt=f0.Outside;function SQt(s,t,r){var n,a=(n={},n[wQt]=Pde(s.selected),n[fb]=Pde(s.disabled),n[jQt]=Pde(s.hidden),n[NQt]=[s.today],n[kbe]=[],n[Sbe]=[],n[Cbe]=[],n[kQt]=[],n);return s.fromDate&&a[fb].push({before:s.fromDate}),s.toDate&&a[fb].push({after:s.toDate}),cz(s)?a[fb]=a[fb].concat(t.modifiers[fb]):dz(s)&&(a[fb]=a[fb].concat(r.modifiers[fb]),a[Cbe]=r.modifiers[Cbe],a[Sbe]=r.modifiers[Sbe],a[kbe]=r.modifiers[kbe]),a}var vlt=k.createContext(void 0);function CQt(s){var t=vc(),r=ATe(),n=ITe(),a=SQt(t,r,n),i=_Qt(t.modifiers),l=ji(ji({},a),i);return e.jsx(vlt.Provider,{value:l,children:s.children})}function blt(){var s=k.useContext(vlt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function TQt(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function EQt(s){return!!(s&&typeof s=="object"&&"from"in s)}function AQt(s){return!!(s&&typeof s=="object"&&"after"in s)}function MQt(s){return!!(s&&typeof s=="object"&&"before"in s)}function IQt(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function PQt(s,t){var r,n=t.from,a=t.to;if(n&&a){var i=fx(a,n)<0;i&&(r=[a,n],n=r[0],a=r[1]);var l=fx(s,n)>=0&&fx(a,s)>=0;return l}return a?$l(a,s):n?$l(n,s):!1}function LQt(s){return g3e(s)}function DQt(s){return Array.isArray(s)&&s.every(g3e)}function RQt(s,t){return t.some(function(r){if(typeof r=="boolean")return r;if(LQt(r))return $l(s,r);if(DQt(r))return r.includes(s);if(EQt(r))return PQt(s,r);if(IQt(r))return r.dayOfWeek.includes(s.getDay());if(TQt(r)){var n=fx(r.before,s),a=fx(r.after,s),i=n>0,l=a<0,o=y5(r.before,r.after);return o?l&&i:i||l}return AQt(r)?fx(s,r.after)>0:MQt(r)?fx(r.before,s)>0:typeof r=="function"?r(s):!1})}function PTe(s,t,r){var n=Object.keys(t).reduce(function(i,l){var o=t[l];return RQt(s,o)&&i.push(l),i},[]),a={};return n.forEach(function(i){return a[i]=!0}),r&&!Epe(s,r)&&(a.outside=!0),a}function OQt(s,t){for(var r=Hc(s[0]),n=jg(s[s.length-1]),a,i,l=r;l<=n;){var o=PTe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Hl(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Hl(l,1)}return i||a}var FQt=365;function _lt(s,t){var r=t.moveBy,n=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,h=a.toDate,m=a.locale,x={day:Hl,week:U4,month:Cf,year:PIt,startOfWeek:function(b){return a.ISOWeek?v_(b):Fm(b,{locale:m,weekStartsOn:c})},endOfWeek:function(b){return a.ISOWeek?Het(b):Cpe(b,{locale:m,weekStartsOn:c})}},g=x[r](s,n==="after"?1:-1);n==="before"&&d?g=LIt([d,g]):n==="after"&&h&&(g=DIt([h,g]));var v=!0;if(i){var j=PTe(g,i);v=!j.disabled&&!j.hidden}return v?g:o.count>FQt?o.lastFocused:_lt(g,{moveBy:r,direction:n,context:a,modifiers:i,retry:ji(ji({},o),{count:o.count+1})})}var wlt=k.createContext(void 0);function BQt(s){var t=uz(),r=blt(),n=k.useState(),a=n[0],i=n[1],l=k.useState(),o=l[0],c=l[1],d=OQt(t.displayMonths,r),h=a??(o&&t.isDateDisplayed(o))?o:d,m=function(){c(a),i(void 0)},x=function(b){i(b)},g=vc(),v=function(b,N){if(a){var S=_lt(a,{moveBy:b,direction:N,context:g,modifiers:r});$l(a,S)||(t.goToDate(S,a),x(S))}},j={focusedDay:a,focusTarget:h,blur:m,focus:x,focusDayAfter:function(){return v("day","after")},focusDayBefore:function(){return v("day","before")},focusWeekAfter:function(){return v("week","after")},focusWeekBefore:function(){return v("week","before")},focusMonthBefore:function(){return v("month","before")},focusMonthAfter:function(){return v("month","after")},focusYearBefore:function(){return v("year","before")},focusYearAfter:function(){return v("year","after")},focusStartOfWeek:function(){return v("startOfWeek","before")},focusEndOfWeek:function(){return v("endOfWeek","after")}};return e.jsx(wlt.Provider,{value:j,children:s.children})}function LTe(){var s=k.useContext(wlt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function zQt(s,t){var r=blt(),n=PTe(s,r,t);return n}var DTe=k.createContext(void 0);function $Qt(s){if(!vxe(s.initialProps)){var t={selected:void 0};return e.jsx(DTe.Provider,{value:t,children:s.children})}return e.jsx(UQt,{initialProps:s.initialProps,children:s.children})}function UQt(s){var t=s.initialProps,r=s.children,n=function(i,l,o){var c,d,h;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(h=t.onSelect)===null||h===void 0||h.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:n};return e.jsx(DTe.Provider,{value:a,children:r})}function jlt(){var s=k.useContext(DTe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function qQt(s,t){var r=vc(),n=jlt(),a=ATe(),i=ITe(),l=LTe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,h=l.focusWeekBefore,m=l.blur,x=l.focus,g=l.focusMonthBefore,v=l.focusMonthAfter,j=l.focusYearBefore,b=l.focusYearAfter,N=l.focusStartOfWeek,S=l.focusEndOfWeek,T=function(ce){var ae,ie,me,oe;vxe(r)?(ae=n.onDayClick)===null||ae===void 0||ae.call(n,s,t,ce):cz(r)?(ie=a.onDayClick)===null||ie===void 0||ie.call(a,s,t,ce):dz(r)?(me=i.onDayClick)===null||me===void 0||me.call(i,s,t,ce):(oe=r.onDayClick)===null||oe===void 0||oe.call(r,s,t,ce)},A=function(ce){var ae;x(s),(ae=r.onDayFocus)===null||ae===void 0||ae.call(r,s,t,ce)},P=function(ce){var ae;m(),(ae=r.onDayBlur)===null||ae===void 0||ae.call(r,s,t,ce)},D=function(ce){var ae;(ae=r.onDayMouseEnter)===null||ae===void 0||ae.call(r,s,t,ce)},B=function(ce){var ae;(ae=r.onDayMouseLeave)===null||ae===void 0||ae.call(r,s,t,ce)},z=function(ce){var ae;(ae=r.onDayPointerEnter)===null||ae===void 0||ae.call(r,s,t,ce)},F=function(ce){var ae;(ae=r.onDayPointerLeave)===null||ae===void 0||ae.call(r,s,t,ce)},$=function(ce){var ae;(ae=r.onDayTouchCancel)===null||ae===void 0||ae.call(r,s,t,ce)},X=function(ce){var ae;(ae=r.onDayTouchEnd)===null||ae===void 0||ae.call(r,s,t,ce)},K=function(ce){var ae;(ae=r.onDayTouchMove)===null||ae===void 0||ae.call(r,s,t,ce)},Q=function(ce){var ae;(ae=r.onDayTouchStart)===null||ae===void 0||ae.call(r,s,t,ce)},Y=function(ce){var ae;(ae=r.onDayKeyUp)===null||ae===void 0||ae.call(r,s,t,ce)},ne=function(ce){var ae;switch(ce.key){case"ArrowLeft":ce.preventDefault(),ce.stopPropagation(),r.dir==="rtl"?o():c();break;case"ArrowRight":ce.preventDefault(),ce.stopPropagation(),r.dir==="rtl"?c():o();break;case"ArrowDown":ce.preventDefault(),ce.stopPropagation(),d();break;case"ArrowUp":ce.preventDefault(),ce.stopPropagation(),h();break;case"PageUp":ce.preventDefault(),ce.stopPropagation(),ce.shiftKey?j():g();break;case"PageDown":ce.preventDefault(),ce.stopPropagation(),ce.shiftKey?b():v();break;case"Home":ce.preventDefault(),ce.stopPropagation(),N();break;case"End":ce.preventDefault(),ce.stopPropagation(),S();break}(ae=r.onDayKeyDown)===null||ae===void 0||ae.call(r,s,t,ce)},de={onClick:T,onFocus:A,onBlur:P,onKeyDown:ne,onKeyUp:Y,onMouseEnter:D,onMouseLeave:B,onPointerEnter:z,onPointerLeave:F,onTouchCancel:$,onTouchEnd:X,onTouchMove:K,onTouchStart:Q};return de}function VQt(){var s=vc(),t=jlt(),r=ATe(),n=ITe(),a=vxe(s)?t.selected:cz(s)?r.selected:dz(s)?n.selected:void 0;return a}function HQt(s){return Object.values(f0).includes(s)}function GQt(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(HQt(n)){var i=s.classNames["day_".concat(n)];i&&r.push(i)}}),r}function WQt(s,t){var r=ji({},s.styles.day);return Object.keys(t).forEach(function(n){var a;r=ji(ji({},r),(a=s.modifiersStyles)===null||a===void 0?void 0:a[n])}),r}function KQt(s,t,r){var n,a,i,l=vc(),o=LTe(),c=zQt(s,t),d=qQt(s,c),h=VQt(),m=!!(l.onDayClick||l.mode!=="default");k.useEffect(function(){var D;c.outside||o.focusedDay&&m&&$l(o.focusedDay,s)&&((D=r.current)===null||D===void 0||D.focus())},[o.focusedDay,s,r,m,c.outside]);var x=GQt(l,c).join(" "),g=WQt(l,c),v=!!(c.outside&&!l.showOutsideDays||c.hidden),j=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:pQt,b=e.jsx(j,{date:s,displayMonth:t,activeModifiers:c}),N={style:g,className:x,children:b,role:"gridcell"},S=o.focusTarget&&$l(o.focusTarget,s)&&!c.outside,T=o.focusedDay&&$l(o.focusedDay,s),A=ji(ji(ji({},N),(n={disabled:c.disabled,role:"gridcell"},n["aria-selected"]=c.selected,n.tabIndex=T||S?0:-1,n)),d),P={isButton:m,isHidden:v,activeModifiers:c,selectedDays:h,buttonProps:A,divProps:N};return P}function YQt(s){var t=k.useRef(null),r=KQt(s.date,s.displayMonth,t);return r.isHidden?e.jsx("div",{role:"gridcell"}):r.isButton?e.jsx(Vhe,ji({name:"day",ref:t},r.buttonProps)):e.jsx("div",ji({},r.divProps))}function ZQt(s){var t=s.number,r=s.dates,n=vc(),a=n.onWeekNumberClick,i=n.styles,l=n.classNames,o=n.locale,c=n.labels.labelWeekNumber,d=n.formatters.formatWeekNumber,h=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:h});var m=c(Number(t),{locale:o}),x=function(g){a(t,r,g)};return e.jsx(Vhe,{name:"week-number","aria-label":m,className:l.weeknumber,style:i.weeknumber,onClick:x,children:h})}function XQt(s){var t,r,n=vc(),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:YQt,d=(r=o==null?void 0:o.WeekNumber)!==null&&r!==void 0?r:ZQt,h;return l&&(h=e.jsx("td",{className:i.cell,style:a.cell,children:e.jsx(d,{number:s.weekNumber,dates:s.dates})})),e.jsxs("tr",{className:i.row,style:a.row,children:[h,s.dates.map(function(m){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:m})},FPt(m))})]})}function Eze(s,t,r){for(var n=r!=null&&r.ISOWeek?Het(t):Cpe(t,r),a=r!=null&&r.ISOWeek?v_(s):Fm(s,r),i=fx(n,a),l=[],o=0;o<=i;o++)l.push(Hl(a,o));var c=l.reduce(function(d,h){var m=r!=null&&r.ISOWeek?y3e(h):b3e(h,r),x=d.find(function(g){return g.weekNumber===m});return x?(x.dates.push(h),d):(d.push({weekNumber:m,dates:[h]}),d)},[]);return c}function QQt(s,t){var r=Eze(Hc(s),jg(s),t);if(t!=null&&t.useFixedWeeks){var n=zPt(s,t);if(n<6){var a=r[r.length-1],i=a.dates[a.dates.length-1],l=U4(i,6-n),o=Eze(U4(i,1),l,t);r.push.apply(r,o)}}return r}function JQt(s){var t,r,n,a=vc(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,h=a.components,m=a.weekStartsOn,x=a.firstWeekContainsDate,g=a.ISOWeek,v=QQt(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:g,locale:i,weekStartsOn:m,firstWeekContainsDate:x}),j=(t=h==null?void 0:h.Head)!==null&&t!==void 0?t:fQt,b=(r=h==null?void 0:h.Row)!==null&&r!==void 0?r:XQt,N=(n=h==null?void 0:h.Footer)!==null&&n!==void 0?n:uQt;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(j,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:v.map(function(S){return e.jsx(b,{displayMonth:s.displayMonth,dates:S.dates,weekNumber:S.weekNumber},S.weekNumber)})}),e.jsx(N,{displayMonth:s.displayMonth})]})}function eJt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var tJt=eJt()?k.useLayoutEffect:k.useEffect,Tbe=!1,sJt=0;function Aze(){return"react-day-picker-".concat(++sJt)}function rJt(s){var t,r=s??(Tbe?Aze():null),n=k.useState(r),a=n[0],i=n[1];return tJt(function(){a===null&&i(Aze())},[]),k.useEffect(function(){Tbe===!1&&(Tbe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function nJt(s){var t,r,n=vc(),a=n.dir,i=n.classNames,l=n.styles,o=n.components,c=uz().displayMonths,d=rJt(n.id?"".concat(n.id,"-").concat(s.displayIndex):void 0),h=n.id?"".concat(n.id,"-grid-").concat(s.displayIndex):void 0,m=[i.month],x=l.month,g=s.displayIndex===0,v=s.displayIndex===c.length-1,j=!g&&!v;a==="rtl"&&(t=[g,v],v=t[0],g=t[1]),g&&(m.push(i.caption_start),x=ji(ji({},x),l.caption_start)),v&&(m.push(i.caption_end),x=ji(ji({},x),l.caption_end)),j&&(m.push(i.caption_between),x=ji(ji({},x),l.caption_between));var b=(r=o==null?void 0:o.Caption)!==null&&r!==void 0?r:dQt;return e.jsxs("div",{className:m.join(" "),style:x,children:[e.jsx(b,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(JQt,{id:h,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function aJt(s){var t=vc(),r=t.classNames,n=t.styles;return e.jsx("div",{className:r.months,style:n.months,children:s.children})}function iJt(s){var t,r,n=s.initialProps,a=vc(),i=LTe(),l=uz(),o=k.useState(!1),c=o[0],d=o[1];k.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var h=[a.classNames.root,a.className];a.numberOfMonths>1&&h.push(a.classNames.multiple_months),a.showWeekNumber&&h.push(a.classNames.with_weeknumber);var m=ji(ji({},a.styles.root),a.style),x=Object.keys(n).filter(function(v){return v.startsWith("data-")}).reduce(function(v,j){var b;return ji(ji({},v),(b={},b[j]=n[j],b))},{}),g=(r=(t=n.components)===null||t===void 0?void 0:t.Months)!==null&&r!==void 0?r:aJt;return e.jsx("div",ji({className:h.join(" "),style:m,dir:a.dir,id:a.id,nonce:n.nonce,title:n.title,lang:n.lang},x,{children:e.jsx(g,{children:l.displayMonths.map(function(v,j){return e.jsx(nJt,{displayIndex:j,displayMonth:v},j)})})}))}function oJt(s){var t=s.children,r=MXt(s,["children"]);return e.jsx(ZXt,{initialProps:r,children:e.jsx(iQt,{children:e.jsx($Qt,{initialProps:r,children:e.jsx(xQt,{initialProps:r,children:e.jsx(vQt,{initialProps:r,children:e.jsx(CQt,{children:e.jsx(BQt,{children:t})})})})})})})}function lJt(s){return e.jsx(oJt,ji({},s,{children:e.jsx(iJt,{initialProps:s})}))}function Nx({className:s,classNames:t,showOutsideDays:r=!0,...n}){return e.jsx(lJt,{showOutsideDays:r,className:Bt("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:Bt(uI({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:Bt(uI({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(Vo,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(ya,{className:"h-4 w-4"})},...n})}Nx.displayName="Calendar";var bxe="Popover",[Nlt]=yd(bxe,[x1]),hz=x1(),[cJt,J2]=Nlt(bxe),klt=s=>{const{__scopePopover:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=hz(t),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=Lh({prop:n,defaultProp:a??!1,onChange:i,caller:bxe});return e.jsx(IB,{...o,children:e.jsx(cJt,{scope:t,contentId:Qu(),triggerRef:c,open:m,onOpenChange:x,onOpenToggle:k.useCallback(()=>x(g=>!g),[x]),hasCustomAnchor:d,onCustomAnchorAdd:k.useCallback(()=>h(!0),[]),onCustomAnchorRemove:k.useCallback(()=>h(!1),[]),modal:l,children:r})})};klt.displayName=bxe;var Slt="PopoverAnchor",dJt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=J2(Slt,r),i=hz(r),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return k.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(bP,{...i,...n,ref:t})});dJt.displayName=Slt;var Clt="PopoverTrigger",Tlt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=J2(Clt,r),i=hz(r),l=Qa(t,a.triggerRef),o=e.jsx(pn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Plt(a.open),...n,ref:l,onClick:Or(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(bP,{asChild:!0,...i,children:o})});Tlt.displayName=Clt;var RTe="PopoverPortal",[uJt,hJt]=Nlt(RTe,{forceMount:void 0}),Elt=s=>{const{__scopePopover:t,forceMount:r,children:n,container:a}=s,i=J2(RTe,t);return e.jsx(uJt,{scope:t,forceMount:r,children:e.jsx(qd,{present:r||i.open,children:e.jsx(xP,{asChild:!0,container:a,children:n})})})};Elt.displayName=RTe;var SI="PopoverContent",Alt=k.forwardRef((s,t)=>{const r=hJt(SI,s.__scopePopover),{forceMount:n=r.forceMount,...a}=s,i=J2(SI,s.__scopePopover);return e.jsx(qd,{present:n||i.open,children:i.modal?e.jsx(fJt,{...a,ref:t}):e.jsx(pJt,{...a,ref:t})})});Alt.displayName=SI;var mJt=v2("PopoverContent.RemoveScroll"),fJt=k.forwardRef((s,t)=>{const r=J2(SI,s.__scopePopover),n=k.useRef(null),a=Qa(t,n),i=k.useRef(!1);return k.useEffect(()=>{const l=n.current;if(l)return dpe(l)},[]),e.jsx(BB,{as:mJt,allowPinchZoom:!0,children:e.jsx(Mlt,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Or(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:Or(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),pJt=k.forwardRef((s,t)=>{const r=J2(SI,s.__scopePopover),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(Mlt,{...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()}})}),Mlt=k.forwardRef((s,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:h,...m}=s,x=J2(SI,r),g=hz(r);return ope(),e.jsx(OB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(F2,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:h,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>x.onOpenChange(!1),children:e.jsx(PB,{"data-state":Plt(x.open),role:"dialog",id:x.contentId,...g,...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)"}})})})}),Ilt="PopoverClose",xJt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=J2(Ilt,r);return e.jsx(pn.button,{type:"button",...n,ref:t,onClick:Or(s.onClick,()=>a.onOpenChange(!1))})});xJt.displayName=Ilt;var gJt="PopoverArrow",yJt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=hz(r);return e.jsx(LB,{...a,...n,ref:t})});yJt.displayName=gJt;function Plt(s){return s?"open":"closed"}var vJt=klt,bJt=Tlt,_Jt=Elt,Llt=Alt;const Ao=vJt,Mo=bJt,wo=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(_Jt,{children:e.jsx(Llt,{ref:a,align:t,sideOffset:r,className:Bt("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})}));wo.displayName=Llt.displayName;const wJt=V5("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"}}),OTe=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx("div",{ref:n,role:"alert",className:Bt(wJt({variant:t}),s),...r}));OTe.displayName="Alert";const jJt=k.forwardRef(({className:s,...t},r)=>e.jsx("h5",{ref:r,className:Bt("mb-1 font-medium leading-none tracking-tight",s),...t}));jJt.displayName="AlertTitle";const FTe=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:Bt("text-sm [&_p]:leading-relaxed",s),...t}));FTe.displayName="AlertDescription";function NJt({open:s,onOpenChange:t,imageUrl:r,imageId:n,defaultCaption:a="",swagItemId:i,reelId:l}){const o=es(),[c,d]=k.useState(a),[h,m]=k.useState([]),[x,g]=k.useState(null),[v,j]=k.useState("now"),[b,N]=k.useState(_Oe(COe(new Date),1)),[S,T]=k.useState("12"),[A,P]=k.useState("00"),[D,B]=k.useState("PM");k.useEffect(()=>{if(s){d(a),j("now"),m([]);const be=_Oe(COe(new Date),1);N(be);const Oe=be.getHours();T(String(Oe>12?Oe-12:Oe===0?12:Oe)),P("00"),B(Oe>=12?"PM":"AM")}},[s,a]);const z=()=>{if(!b)return null;let be=parseInt(S);const Oe=parseInt(A);return D==="PM"&&be!==12&&(be+=12),D==="AM"&&be===12&&(be=0),WO(GO(b,be),Oe)},{data:F,isLoading:$}=gt({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:be}}=await H.auth.getUser();if(!be)return[];const{data:Oe,error:Me}=await H.from("social_accounts").select("*").eq("user_id",be.id).eq("is_active",!0).order("platform",{ascending:!0});if(Me)throw Me;return console.log("Fetched social accounts for posting:",Oe),Oe},enabled:s,staleTime:0}),X=Lt({mutationFn:async({accountId:be,platform:Oe})=>{g(be);const{data:Me,error:Pe}=await H.functions.invoke("social-post",{body:{platform:Oe,accountId:be,imageUrl:r,caption:c}});if(Pe)throw Pe;if(Me!=null&&Me.error)throw new Error(Me.error);return Me},onSuccess:be=>{const Oe=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":be.platform==="linkedin"?"LinkedIn":"Google Business";ue.success(`Posted to ${Oe}!`)},onError:be=>{ue.error(`Failed to post: ${be.message}`)},onSettled:()=>{g(null)}}),K=Lt({mutationFn:async({accountId:be,platform:Oe,scheduledFor:Me})=>{const{data:{user:Pe}}=await H.auth.getUser();if(!Pe)throw new Error("Not authenticated");const{error:Ee}=await H.from("scheduled_posts").insert({user_id:Pe.id,social_account_id:be,platform:Oe,image_url:r,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Me.toISOString(),status:"scheduled"});if(Ee)throw Ee;return{platform:Oe}},onSuccess:be=>{const Oe=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":"LinkedIn";ue.success(`Post scheduled for ${Oe}!`)},onError:be=>{ue.error(`Failed to schedule: ${be.message}`)}}),Q=async()=>{if(h.length===0){ue.error("Please select at least one account");return}if(v==="schedule"){const be=z();if(!be||be<=new Date){ue.error("Please select a future date and time");return}for(const Oe of h){const Me=F==null?void 0:F.find(Pe=>Pe.id===Oe);Me&&await K.mutateAsync({accountId:Oe,platform:Me.platform,scheduledFor:be})}o.invalidateQueries({queryKey:["scheduled-posts"]}),ue.success(`${h.length} post(s) scheduled for ${Ss(be,"PPp")}`)}else for(const be of h){const Oe=F==null?void 0:F.find(Me=>Me.id===be);Oe&&await X.mutateAsync({accountId:be,platform:Oe.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),m([]),t(!1)},Y=be=>{m(Oe=>Oe.includes(be)?Oe.filter(Me=>Me!==be):[...Oe,be])},ne=(F==null?void 0:F.filter(be=>be.platform==="facebook"))||[],de=(F==null?void 0:F.filter(be=>be.platform==="instagram"))||[],ce=(F==null?void 0:F.filter(be=>be.platform==="linkedin"))||[],ae=(F==null?void 0:F.filter(be=>be.platform==="google_business"))||[],ie=((F==null?void 0:F.length)||0)>0,me=X.isPending||K.isPending,oe=Array.from({length:12},(be,Oe)=>String(Oe+1)),ge=["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(js,{children:[e.jsx(bs,{children:"Create Social Post"}),e.jsx(Fr,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:r,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"caption",children:"Caption"}),e.jsx(ur,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:be=>d(be.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>j("now"),className:Bt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>j("schedule"),className:Bt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),v==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(cn,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),b?Ss(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:b,onSelect:N,disabled:be=>bee.jsx(mt,{value:be,children:be},be))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(zs,{value:A,onValueChange:P,children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:ge.map(be=>e.jsx(mt,{value:be,children:be},be))})]}),e.jsxs(zs,{value:D,onValueChange:be=>B(be),children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"AM",children:"AM"}),e.jsx(mt,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Ss(z()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Post to"}),$&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-6 w-6 animate-spin"})}),!$&&!ie&&e.jsxs(OTe,{children:[e.jsx(Hi,{className:"h-4 w-4"}),e.jsxs(FTe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Kn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(lo,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),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(ku,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),ne.map(be=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ei,{checked:h.includes(be.id),onCheckedChange:()=>Y(be.id),disabled:x===be.id}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:be.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(ku,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),x===be.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},be.id))]}),de.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(au,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),de.map(be=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ei,{checked:h.includes(be.id),onCheckedChange:()=>Y(be.id),disabled:x===be.id}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:be.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(au,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",be.platform_username]}),x===be.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},be.id))]}),ce.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(om,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ce.map(be=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ei,{checked:h.includes(be.id),onCheckedChange:()=>Y(be.id),disabled:x===be.id}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:be.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(om,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.platform_username}),x===be.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},be.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(ja,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ae.map(be=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ei,{checked:h.includes(be.id),onCheckedChange:()=>Y(be.id),disabled:x===be.id}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:be.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(ja,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),x===be.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},be.id))]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:Q,disabled:h.length===0||me,className:"gap-2",children:[me?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(rn,{className:"h-4 w-4"}):e.jsx(Zr,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${h.length} post${h.length!==1?"s":""}`:`Post to ${h.length} account${h.length!==1?"s":""}`]})]})]})})}function kJt(){const s=es(),[t,r]=k.useState(void 0),[n,a]=k.useState("all"),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(void 0),[m,x]=k.useState("12"),[g,v]=k.useState("00"),[j,b]=k.useState("PM"),{data:N=[],isLoading:S}=gt({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:ae,error:ie}=await H.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(ie)throw ie;return ae}}),T=N.filter(ae=>{if(n!=="all"&&ae.status!==n)return!1;if(t&&ae.scheduled_for){const ie=new Date(ae.scheduled_for);if(!$l(ie,t))return!1}return!0}),A=N.filter(ae=>ae.scheduled_for).map(ae=>Tf(new Date(ae.scheduled_for))),P=Lt({mutationFn:async ae=>{const{error:ie}=await H.from("scheduled_posts").update({caption:ae.caption,scheduled_for:ae.scheduled_for}).eq("id",ae.id);if(ie)throw ie},onSuccess:()=>{ue.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:ae=>{ue.error(`Failed to update: ${ae.message}`)}}),D=Lt({mutationFn:async ae=>{const{error:ie}=await H.from("scheduled_posts").update({status:"cancelled"}).eq("id",ae);if(ie)throw ie},onSuccess:()=>{ue.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ae=>{ue.error(`Failed to cancel: ${ae.message}`)}}),B=Lt({mutationFn:async ae=>{const{error:ie}=await H.from("scheduled_posts").delete().eq("id",ae);if(ie)throw ie},onSuccess:()=>{ue.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ae=>{ue.error(`Failed to delete: ${ae.message}`)}}),z=Lt({mutationFn:async ae=>{const{data:ie,error:me}=await H.functions.invoke("social-post",{body:{platform:ae.platform,accountId:ae.social_account_id,imageUrl:ae.image_url,caption:ae.caption}});if(me)throw me;if(ie!=null&&ie.error)throw new Error(ie.error);return await H.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ie.postId}).eq("id",ae.id),ie},onSuccess:ae=>{const ie=ae.platform==="facebook"?"Facebook":ae.platform==="instagram"?"Instagram":"LinkedIn";ue.success(`Posted to ${ie}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ae=>{ue.error(`Failed to post: ${ae.message}`)}}),F=ae=>{if(l(ae),c(ae.caption||""),ae.scheduled_for){const ie=new Date(ae.scheduled_for);h(ie);const me=ie.getHours();x(String(me>12?me-12:me===0?12:me)),v(String(ie.getMinutes()).padStart(2,"0")),b(me>=12?"PM":"AM")}},$=()=>{if(!i||!d)return;let ae=parseInt(m);const ie=parseInt(g);j==="PM"&&ae!==12&&(ae+=12),j==="AM"&&ae===12&&(ae=0);const me=WO(GO(d,ae),ie);P.mutate({id:i.id,caption:o,scheduled_for:me.toISOString()})},X=ae=>{switch(ae){case"facebook":return e.jsx(ku,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(au,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(om,{className:"h-4 w-4 text-blue-700"});default:return null}},K=ae=>{switch(ae){case"scheduled":return e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Ge,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(mi,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Ge,{variant:"destructive",className:"gap-1",children:[e.jsx(Mc,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Ge,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Hi,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Ge,{variant:"outline",children:ae})}},Q=Array.from({length:12},(ae,ie)=>String(ie+1)),Y=["00","15","30","45"],ne=N.filter(ae=>ae.status==="scheduled").length,de=N.filter(ae=>ae.status==="posted").length,ce=N.filter(ae=>ae.status==="scheduled"&&ae.scheduled_for&&$Pt(new Date(ae.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(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:de}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:N.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(Ne,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(pd,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Nx,{mode:"single",selected:t,onSelect:r,className:Bt("pointer-events-auto"),modifiers:{hasPost:A},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>r(void 0),className:"w-full mt-2",children:"Clear date filter"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s0,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ae=>e.jsx(G,{variant:n===ae?"default":"outline",size:"sm",onClick:()=>a(ae),className:"capitalize",children:ae},ae))})]}),S&&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"})}),!S&&T.length===0&&e.jsxs(Ne,{className:"p-8 text-center",children:[e.jsx(rn,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?`No posts scheduled for ${Ss(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(ae=>{var ie,me;return e.jsx(Ne,{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:ae.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(De,{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:[X(ae.platform),e.jsx("span",{className:"font-medium",children:((ie=ae.social_accounts)==null?void 0:ie.page_name)||((me=ae.social_accounts)==null?void 0:me.platform_username)||"Unknown"}),K(ae.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ae.status==="scheduled"&&e.jsxs(A_,{children:[e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>F(ae),children:e.jsx(Ta,{className:"h-4 w-4"})})}),e.jsx(Wl,{children:"Edit post"})]}),e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>z.mutate(ae),disabled:z.isPending,children:z.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"})})}),e.jsx(Wl,{children:"Post now"})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Cancel this scheduled post?"}),e.jsx(Uo,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Keep"}),e.jsx(Eo,{onClick:()=>D.mutate(ae.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Eo,{onClick:()=>B.mutate(ae.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ae.status==="posted"||ae.status==="cancelled"||ae.status==="failed")&&e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete this post?"}),e.jsx(Uo,{children:"This will permanently remove this post from your history."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>B.mutate(ae.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ae.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ae.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),ae.status==="posted"&&ae.posted_at?`Posted ${Ss(new Date(ae.posted_at),"PPp")}`:ae.scheduled_for?`Scheduled for ${Ss(new Date(ae.scheduled_for),"PPp")}`:"Not scheduled"]}),ae.status==="failed"&&ae.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ae.error_message]})]})]})},ae.id)})})]})]}),e.jsx(vs,{open:!!i,onOpenChange:ae=>!ae&&l(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Scheduled Post"}),e.jsx(Fr,{children:"Update the caption or reschedule this post"})]}),i&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-32 mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:i.image_url,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Caption"}),e.jsx(ur,{value:o,onChange:ae=>c(ae.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(he,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),d?Ss(d,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:d,onSelect:h,disabled:ae=>aee.jsx(mt,{value:ae,children:ae},ae))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Y.map(ae=>e.jsx(mt,{value:ae,children:ae},ae))})]}),e.jsxs(zs,{value:j,onValueChange:ae=>b(ae),children:[e.jsx(Os,{className:"w-[70px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"AM",children:"AM"}),e.jsx(mt,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(G,{onClick:$,disabled:P.isPending,children:[P.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function wU(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 Dlt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(r){s.exports=r()})(function(){return function r(n,a,i){function l(d,h){if(!a[d]){if(!n[d]){var m=typeof wU=="function"&&wU;if(!h&&m)return m(d,!0);if(o)return o(d,!0);var x=new Error("Cannot find module '"+d+"'");throw x.code="MODULE_NOT_FOUND",x}var g=a[d]={exports:{}};n[d][0].call(g.exports,function(v){var j=n[d][1][v];return l(j||v)},g,g.exports,r,n,a,i)}return a[d].exports}for(var o=typeof wU=="function"&&wU,c=0;c>2,g=(3&d)<<4|h>>4,v=1>6:64,j=2>4,h=(15&x)<<4|(g=o.indexOf(c.charAt(j++)))>>2,m=(3&g)<<6|(v=o.indexOf(c.charAt(j++))),S[b++]=d,g!==64&&(S[b++]=h),v!==64&&(S[b++]=m);return S}},{"./support":30,"./utils":32}],2:[function(r,n,a){var i=r("./external"),l=r("./stream/DataWorker"),o=r("./stream/Crc32Probe"),c=r("./stream/DataLengthProbe");function d(h,m,x,g,v){this.compressedSize=h,this.uncompressedSize=m,this.crc32=x,this.compression=g,this.compressedContent=v}d.prototype={getContentWorker:function(){var h=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),m=this;return h.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(h,m,x){return h.pipe(new o).pipe(new c("uncompressedSize")).pipe(m.compressWorker(x)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},n.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,a){var i=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,a){var i=r("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var h=0;h<8;h++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();n.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,h,m,x){var g=l,v=x+m;d^=-1;for(var j=x;j>>8^g[255&(d^h[j])];return-1^d}(0|c,o,o.length,0):function(d,h,m,x){var g=l,v=x+m;d^=-1;for(var j=x;j>>8^g[255&(d^h.charCodeAt(j))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(r,n,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(r,n,a){var i=null;i=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:i}},{lie:37}],7:[function(r,n,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=r("pako"),o=r("./utils"),c=r("./stream/GenericWorker"),d=i?"uint8array":"array";function h(m,x){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=x,this.meta={}}a.magic="\b\0",o.inherits(h,c),h.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,m.data),!1)},h.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(x){m.push({data:x,meta:m.meta})}},a.compressWorker=function(m){return new h("Deflate",m)},a.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,a){function i(g,v){var j,b="";for(j=0;j>>=8;return b}function l(g,v,j,b,N,S){var T,A,P=g.file,D=g.compression,B=S!==d.utf8encode,z=o.transformTo("string",S(P.name)),F=o.transformTo("string",d.utf8encode(P.name)),$=P.comment,X=o.transformTo("string",S($)),K=o.transformTo("string",d.utf8encode($)),Q=F.length!==P.name.length,Y=K.length!==$.length,ne="",de="",ce="",ae=P.dir,ie=P.date,me={crc32:0,compressedSize:0,uncompressedSize:0};v&&!j||(me.crc32=g.crc32,me.compressedSize=g.compressedSize,me.uncompressedSize=g.uncompressedSize);var oe=0;v&&(oe|=8),B||!Q&&!Y||(oe|=2048);var ge=0,be=0;ae&&(ge|=16),N==="UNIX"?(be=798,ge|=function(Me,Pe){var Ee=Me;return Me||(Ee=Pe?16893:33204),(65535&Ee)<<16}(P.unixPermissions,ae)):(be=20,ge|=function(Me){return 63&(Me||0)}(P.dosPermissions)),T=ie.getUTCHours(),T<<=6,T|=ie.getUTCMinutes(),T<<=5,T|=ie.getUTCSeconds()/2,A=ie.getUTCFullYear()-1980,A<<=4,A|=ie.getUTCMonth()+1,A<<=5,A|=ie.getUTCDate(),Q&&(de=i(1,1)+i(h(z),4)+F,ne+="up"+i(de.length,2)+de),Y&&(ce=i(1,1)+i(h(X),4)+K,ne+="uc"+i(ce.length,2)+ce);var Oe="";return Oe+=` \0`,Oe+=i(oe,2),Oe+=D.magic,Oe+=i(T,2),Oe+=i(A,2),Oe+=i(me.crc32,4),Oe+=i(me.compressedSize,4),Oe+=i(me.uncompressedSize,4),Oe+=i(z.length,2),Oe+=i(ne.length,2),{fileRecord:m.LOCAL_FILE_HEADER+Oe+z+ne,dirRecord:m.CENTRAL_FILE_HEADER+i(be,2)+Oe+i(X.length,2)+"\0\0\0\0"+i(ge,4)+i(b,4)+z+ne+X}}var o=r("../utils"),c=r("../stream/GenericWorker"),d=r("../utf8"),h=r("../crc32"),m=r("../signature");function x(g,v,j,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=v,this.zipPlatform=j,this.encodeFileName=b,this.streamFiles=g,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(x,c),x.prototype.push=function(g){var v=g.meta.percent||0,j=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(g):(this.bytesWritten+=g.data.length,c.prototype.push.call(this,{data:g.data,meta:{currentFile:this.currentFile,percent:j?(v+100*(j-b-1))/j:100}}))},x.prototype.openedSource=function(g){this.currentSourceOffset=this.bytesWritten,this.currentFile=g.file.name;var v=this.streamFiles&&!g.file.dir;if(v){var j=l(g,v,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:j.fileRecord,meta:{percent:0}})}else this.accumulate=!0},x.prototype.closedSource=function(g){this.accumulate=!1;var v=this.streamFiles&&!g.file.dir,j=l(g,v,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(j.dirRecord),v)this.push({data:function(b){return m.DATA_DESCRIPTOR+i(b.crc32,4)+i(b.compressedSize,4)+i(b.uncompressedSize,4)}(g),meta:{percent:100}});else for(this.push({data:j.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},x.prototype.flush=function(){for(var g=this.bytesWritten,v=0;v=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},n.exports=l},{"../utils":32}],19:[function(r,n,a){var i=r("./Uint8ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,n,a){var i=r("./DataReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./DataReader":18}],21:[function(r,n,a){var i=r("./ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(r,n,a){var i=r("../utils"),l=r("../support"),o=r("./ArrayReader"),c=r("./StringReader"),d=r("./NodeBufferReader"),h=r("./Uint8ArrayReader");n.exports=function(m){var x=i.getTypeOf(m);return i.checkSupport(x),x!=="string"||l.uint8array?x==="nodebuffer"?new d(m):l.uint8array?new h(i.transformTo("uint8array",m)):new o(i.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,n,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(r,n,a){var i=r("./GenericWorker"),l=r("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},n.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(r,n,a){var i=r("./GenericWorker"),l=r("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},n.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},n.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(h){d.dataIsReady=!0,d.data=h,d.max=h&&h.length||0,d.type=i.getTypeOf(h),d.isPaused||d._tickAndRepeat()},function(h){d.error(h)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},n.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(r,n,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},n.exports=i},{}],29:[function(r,n,a){var i=r("../utils"),l=r("./ConvertWorker"),o=r("./GenericWorker"),c=r("../base64"),d=r("../support"),h=r("../external"),m=null;if(d.nodestream)try{m=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function x(v,j){return new h.Promise(function(b,N){var S=[],T=v._internalType,A=v._outputType,P=v._mimeType;v.on("data",function(D,B){S.push(D),j&&j(B)}).on("error",function(D){S=[],N(D)}).on("end",function(){try{var D=function(B,z,F){switch(B){case"blob":return i.newBlob(i.transformTo("arraybuffer",z),F);case"base64":return c.encode(z);default:return i.transformTo(B,z)}}(A,function(B,z){var F,$=0,X=null,K=0;for(F=0;F"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,n,a){for(var i=r("./utils"),l=r("./support"),o=r("./nodejsUtils"),c=r("./stream/GenericWorker"),d=new Array(256),h=0;h<256;h++)d[h]=252<=h?6:248<=h?5:240<=h?4:224<=h?3:192<=h?2:1;d[254]=d[254]=1;function m(){c.call(this,"utf-8 decode"),this.leftOver=null}function x(){c.call(this,"utf-8 encode")}a.utf8encode=function(g){return l.nodebuffer?o.newBufferFrom(g,"utf-8"):function(v){var j,b,N,S,T,A=v.length,P=0;for(S=0;S>>6:(b<65536?j[T++]=224|b>>>12:(j[T++]=240|b>>>18,j[T++]=128|b>>>12&63),j[T++]=128|b>>>6&63),j[T++]=128|63&b);return j}(g)},a.utf8decode=function(g){return l.nodebuffer?i.transformTo("nodebuffer",g).toString("utf-8"):function(v){var j,b,N,S,T=v.length,A=new Array(2*T);for(j=b=0;j>10&1023,A[b++]=56320|1023&N)}return A.length!==b&&(A.subarray?A=A.subarray(0,b):A.length=b),i.applyFromCharCode(A)}(g=i.transformTo(l.uint8array?"uint8array":"array",g))},i.inherits(m,c),m.prototype.processChunk=function(g){var v=i.transformTo(l.uint8array?"uint8array":"array",g.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var j=v;(v=new Uint8Array(j.length+this.leftOver.length)).set(this.leftOver,0),v.set(j,this.leftOver.length)}else v=this.leftOver.concat(v);this.leftOver=null}var b=function(S,T){var A;for((T=T||S.length)>S.length&&(T=S.length),A=T-1;0<=A&&(192&S[A])==128;)A--;return A<0||A===0?T:A+d[S[A]]>T?A:T}(v),N=v;b!==v.length&&(l.uint8array?(N=v.subarray(0,b),this.leftOver=v.subarray(b,v.length)):(N=v.slice(0,b),this.leftOver=v.slice(b,v.length))),this.push({data:a.utf8decode(N),meta:g.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=m,i.inherits(x,c),x.prototype.processChunk=function(g){this.push({data:a.utf8encode(g.data),meta:g.meta})},a.Utf8EncodeWorker=x},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,n,a){var i=r("./support"),l=r("./base64"),o=r("./nodejsUtils"),c=r("./external");function d(j){return j}function h(j,b){for(var N=0;N>8;this.dir=!!(16&this.externalFileAttributes),g==0&&(this.dosPermissions=63&this.externalFileAttributes),g==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var g=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=g.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=g.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=g.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=g.readInt(4))}},readExtraFields:function(g){var v,j,b,N=g.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});g.index+4>>6:(g<65536?x[b++]=224|g>>>12:(x[b++]=240|g>>>18,x[b++]=128|g>>>12&63),x[b++]=128|g>>>6&63),x[b++]=128|63&g);return x},a.buf2binstring=function(m){return h(m,m.length)},a.binstring2buf=function(m){for(var x=new i.Buf8(m.length),g=0,v=x.length;g>10&1023,S[v++]=56320|1023&j)}return h(S,v)},a.utf8border=function(m,x){var g;for((x=x||m.length)>m.length&&(x=m.length),g=x-1;0<=g&&(192&m[g])==128;)g--;return g<0||g===0?x:g+c[m[g]]>x?g:x}},{"./common":41}],43:[function(r,n,a){n.exports=function(i,l,o,c){for(var d=65535&i|0,h=i>>>16&65535|0,m=0;o!==0;){for(o-=m=2e3>>1:l>>>1;o[c]=l}return o}();n.exports=function(l,o,c,d){var h=i,m=d+c;l^=-1;for(var x=d;x>>8^h[255&(l^o[x])];return-1^l}},{}],46:[function(r,n,a){var i,l=r("../utils/common"),o=r("./trees"),c=r("./adler32"),d=r("./crc32"),h=r("./messages"),m=0,x=4,g=0,v=-2,j=-1,b=4,N=2,S=8,T=9,A=286,P=30,D=19,B=2*A+1,z=15,F=3,$=258,X=$+F+1,K=42,Q=113,Y=1,ne=2,de=3,ce=4;function ae(ve,rt){return ve.msg=h[rt],rt}function ie(ve){return(ve<<1)-(4ve.avail_out&&(Re=ve.avail_out),Re!==0&&(l.arraySet(ve.output,rt.pending_buf,rt.pending_out,Re,ve.next_out),ve.next_out+=Re,rt.pending_out+=Re,ve.total_out+=Re,ve.avail_out-=Re,rt.pending-=Re,rt.pending===0&&(rt.pending_out=0))}function ge(ve,rt){o._tr_flush_block(ve,0<=ve.block_start?ve.block_start:-1,ve.strstart-ve.block_start,rt),ve.block_start=ve.strstart,oe(ve.strm)}function be(ve,rt){ve.pending_buf[ve.pending++]=rt}function Oe(ve,rt){ve.pending_buf[ve.pending++]=rt>>>8&255,ve.pending_buf[ve.pending++]=255&rt}function Me(ve,rt){var Re,Qe,Ke=ve.max_chain_length,Ce=ve.strstart,nt=ve.prev_length,$t=ve.nice_match,lt=ve.strstart>ve.w_size-X?ve.strstart-(ve.w_size-X):0,it=ve.window,Nt=ve.w_mask,Ft=ve.prev,at=ve.strstart+$,Ie=it[Ce+nt-1],et=it[Ce+nt];ve.prev_length>=ve.good_match&&(Ke>>=2),$t>ve.lookahead&&($t=ve.lookahead);do if(it[(Re=rt)+nt]===et&&it[Re+nt-1]===Ie&&it[Re]===it[Ce]&&it[++Re]===it[Ce+1]){Ce+=2,Re++;do;while(it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&it[++Ce]===it[++Re]&&Celt&&--Ke!=0);return nt<=ve.lookahead?nt:ve.lookahead}function Pe(ve){var rt,Re,Qe,Ke,Ce,nt,$t,lt,it,Nt,Ft=ve.w_size;do{if(Ke=ve.window_size-ve.lookahead-ve.strstart,ve.strstart>=Ft+(Ft-X)){for(l.arraySet(ve.window,ve.window,Ft,Ft,0),ve.match_start-=Ft,ve.strstart-=Ft,ve.block_start-=Ft,rt=Re=ve.hash_size;Qe=ve.head[--rt],ve.head[rt]=Ft<=Qe?Qe-Ft:0,--Re;);for(rt=Re=Ft;Qe=ve.prev[--rt],ve.prev[rt]=Ft<=Qe?Qe-Ft:0,--Re;);Ke+=Ft}if(ve.strm.avail_in===0)break;if(nt=ve.strm,$t=ve.window,lt=ve.strstart+ve.lookahead,it=Ke,Nt=void 0,Nt=nt.avail_in,it=F)for(Ce=ve.strstart-ve.insert,ve.ins_h=ve.window[Ce],ve.ins_h=(ve.ins_h<=F&&(ve.ins_h=(ve.ins_h<=F)if(Qe=o._tr_tally(ve,ve.strstart-ve.match_start,ve.match_length-F),ve.lookahead-=ve.match_length,ve.match_length<=ve.max_lazy_match&&ve.lookahead>=F){for(ve.match_length--;ve.strstart++,ve.ins_h=(ve.ins_h<=F&&(ve.ins_h=(ve.ins_h<=F&&ve.match_length<=ve.prev_length){for(Ke=ve.strstart+ve.lookahead-F,Qe=o._tr_tally(ve,ve.strstart-1-ve.prev_match,ve.prev_length-F),ve.lookahead-=ve.prev_length-1,ve.prev_length-=2;++ve.strstart<=Ke&&(ve.ins_h=(ve.ins_h<ve.pending_buf_size-5&&(Re=ve.pending_buf_size-5);;){if(ve.lookahead<=1){if(Pe(ve),ve.lookahead===0&&rt===m)return Y;if(ve.lookahead===0)break}ve.strstart+=ve.lookahead,ve.lookahead=0;var Qe=ve.block_start+Re;if((ve.strstart===0||ve.strstart>=Qe)&&(ve.lookahead=ve.strstart-Qe,ve.strstart=Qe,ge(ve,!1),ve.strm.avail_out===0)||ve.strstart-ve.block_start>=ve.w_size-X&&(ge(ve,!1),ve.strm.avail_out===0))return Y}return ve.insert=0,rt===x?(ge(ve,!0),ve.strm.avail_out===0?de:ce):(ve.strstart>ve.block_start&&(ge(ve,!1),ve.strm.avail_out),Y)}),new Se(4,4,8,4,Ee),new Se(4,5,16,8,Ee),new Se(4,6,32,32,Ee),new Se(4,4,16,16,$e),new Se(8,16,32,32,$e),new Se(8,16,128,128,$e),new Se(8,32,128,256,$e),new Se(32,128,258,1024,$e),new Se(32,258,258,4096,$e)],a.deflateInit=function(ve,rt){return ct(ve,rt,S,15,8,0)},a.deflateInit2=ct,a.deflateReset=ye,a.deflateResetKeep=Te,a.deflateSetHeader=function(ve,rt){return ve&&ve.state?ve.state.wrap!==2?v:(ve.state.gzhead=rt,g):v},a.deflate=function(ve,rt){var Re,Qe,Ke,Ce;if(!ve||!ve.state||5>8&255),be(Qe,Qe.gzhead.time>>16&255),be(Qe,Qe.gzhead.time>>24&255),be(Qe,Qe.level===9?2:2<=Qe.strategy||Qe.level<2?4:0),be(Qe,255&Qe.gzhead.os),Qe.gzhead.extra&&Qe.gzhead.extra.length&&(be(Qe,255&Qe.gzhead.extra.length),be(Qe,Qe.gzhead.extra.length>>8&255)),Qe.gzhead.hcrc&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending,0)),Qe.gzindex=0,Qe.status=69):(be(Qe,0),be(Qe,0),be(Qe,0),be(Qe,0),be(Qe,0),be(Qe,Qe.level===9?2:2<=Qe.strategy||Qe.level<2?4:0),be(Qe,3),Qe.status=Q);else{var nt=S+(Qe.w_bits-8<<4)<<8;nt|=(2<=Qe.strategy||Qe.level<2?0:Qe.level<6?1:Qe.level===6?2:3)<<6,Qe.strstart!==0&&(nt|=32),nt+=31-nt%31,Qe.status=Q,Oe(Qe,nt),Qe.strstart!==0&&(Oe(Qe,ve.adler>>>16),Oe(Qe,65535&ve.adler)),ve.adler=1}if(Qe.status===69)if(Qe.gzhead.extra){for(Ke=Qe.pending;Qe.gzindex<(65535&Qe.gzhead.extra.length)&&(Qe.pending!==Qe.pending_buf_size||(Qe.gzhead.hcrc&&Qe.pending>Ke&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),oe(ve),Ke=Qe.pending,Qe.pending!==Qe.pending_buf_size));)be(Qe,255&Qe.gzhead.extra[Qe.gzindex]),Qe.gzindex++;Qe.gzhead.hcrc&&Qe.pending>Ke&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),Qe.gzindex===Qe.gzhead.extra.length&&(Qe.gzindex=0,Qe.status=73)}else Qe.status=73;if(Qe.status===73)if(Qe.gzhead.name){Ke=Qe.pending;do{if(Qe.pending===Qe.pending_buf_size&&(Qe.gzhead.hcrc&&Qe.pending>Ke&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),oe(ve),Ke=Qe.pending,Qe.pending===Qe.pending_buf_size)){Ce=1;break}Ce=Qe.gzindexKe&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),Ce===0&&(Qe.gzindex=0,Qe.status=91)}else Qe.status=91;if(Qe.status===91)if(Qe.gzhead.comment){Ke=Qe.pending;do{if(Qe.pending===Qe.pending_buf_size&&(Qe.gzhead.hcrc&&Qe.pending>Ke&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),oe(ve),Ke=Qe.pending,Qe.pending===Qe.pending_buf_size)){Ce=1;break}Ce=Qe.gzindexKe&&(ve.adler=d(ve.adler,Qe.pending_buf,Qe.pending-Ke,Ke)),Ce===0&&(Qe.status=103)}else Qe.status=103;if(Qe.status===103&&(Qe.gzhead.hcrc?(Qe.pending+2>Qe.pending_buf_size&&oe(ve),Qe.pending+2<=Qe.pending_buf_size&&(be(Qe,255&ve.adler),be(Qe,ve.adler>>8&255),ve.adler=0,Qe.status=Q)):Qe.status=Q),Qe.pending!==0){if(oe(ve),ve.avail_out===0)return Qe.last_flush=-1,g}else if(ve.avail_in===0&&ie(rt)<=ie(Re)&&rt!==x)return ae(ve,-5);if(Qe.status===666&&ve.avail_in!==0)return ae(ve,-5);if(ve.avail_in!==0||Qe.lookahead!==0||rt!==m&&Qe.status!==666){var $t=Qe.strategy===2?function(lt,it){for(var Nt;;){if(lt.lookahead===0&&(Pe(lt),lt.lookahead===0)){if(it===m)return Y;break}if(lt.match_length=0,Nt=o._tr_tally(lt,0,lt.window[lt.strstart]),lt.lookahead--,lt.strstart++,Nt&&(ge(lt,!1),lt.strm.avail_out===0))return Y}return lt.insert=0,it===x?(ge(lt,!0),lt.strm.avail_out===0?de:ce):lt.last_lit&&(ge(lt,!1),lt.strm.avail_out===0)?Y:ne}(Qe,rt):Qe.strategy===3?function(lt,it){for(var Nt,Ft,at,Ie,et=lt.window;;){if(lt.lookahead<=$){if(Pe(lt),lt.lookahead<=$&&it===m)return Y;if(lt.lookahead===0)break}if(lt.match_length=0,lt.lookahead>=F&&0lt.lookahead&&(lt.match_length=lt.lookahead)}if(lt.match_length>=F?(Nt=o._tr_tally(lt,1,lt.match_length-F),lt.lookahead-=lt.match_length,lt.strstart+=lt.match_length,lt.match_length=0):(Nt=o._tr_tally(lt,0,lt.window[lt.strstart]),lt.lookahead--,lt.strstart++),Nt&&(ge(lt,!1),lt.strm.avail_out===0))return Y}return lt.insert=0,it===x?(ge(lt,!0),lt.strm.avail_out===0?de:ce):lt.last_lit&&(ge(lt,!1),lt.strm.avail_out===0)?Y:ne}(Qe,rt):i[Qe.level].func(Qe,rt);if($t!==de&&$t!==ce||(Qe.status=666),$t===Y||$t===de)return ve.avail_out===0&&(Qe.last_flush=-1),g;if($t===ne&&(rt===1?o._tr_align(Qe):rt!==5&&(o._tr_stored_block(Qe,0,0,!1),rt===3&&(me(Qe.head),Qe.lookahead===0&&(Qe.strstart=0,Qe.block_start=0,Qe.insert=0))),oe(ve),ve.avail_out===0))return Qe.last_flush=-1,g}return rt!==x?g:Qe.wrap<=0?1:(Qe.wrap===2?(be(Qe,255&ve.adler),be(Qe,ve.adler>>8&255),be(Qe,ve.adler>>16&255),be(Qe,ve.adler>>24&255),be(Qe,255&ve.total_in),be(Qe,ve.total_in>>8&255),be(Qe,ve.total_in>>16&255),be(Qe,ve.total_in>>24&255)):(Oe(Qe,ve.adler>>>16),Oe(Qe,65535&ve.adler)),oe(ve),0=Re.w_size&&(Ce===0&&(me(Re.head),Re.strstart=0,Re.block_start=0,Re.insert=0),it=new l.Buf8(Re.w_size),l.arraySet(it,rt,Nt-Re.w_size,Re.w_size,0),rt=it,Nt=Re.w_size),nt=ve.avail_in,$t=ve.next_in,lt=ve.input,ve.avail_in=Nt,ve.next_in=0,ve.input=rt,Pe(Re);Re.lookahead>=F;){for(Qe=Re.strstart,Ke=Re.lookahead-(F-1);Re.ins_h=(Re.ins_h<>>=F=z>>>24,T-=F,(F=z>>>16&255)===0)ne[h++]=65535&z;else{if(!(16&F)){if(!(64&F)){z=A[(65535&z)+(S&(1<>>=F,T-=F),T<15&&(S+=Y[c++]<>>=F=z>>>24,T-=F,!(16&(F=z>>>16&255))){if(!(64&F)){z=P[(65535&z)+(S&(1<>>=F,T-=F,(F=h-m)>3,S&=(1<<(T-=$<<3))-1,i.next_in=c,i.next_out=h,i.avail_in=c>>24&255)+(K>>>8&65280)+((65280&K)<<8)+((255&K)<<24)}function S(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function T(K){var Q;return K&&K.state?(Q=K.state,K.total_in=K.total_out=Q.total=0,K.msg="",Q.wrap&&(K.adler=1&Q.wrap),Q.mode=v,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(j),Q.distcode=Q.distdyn=new i.Buf32(b),Q.sane=1,Q.back=-1,x):g}function A(K){var Q;return K&&K.state?((Q=K.state).wsize=0,Q.whave=0,Q.wnext=0,T(K)):g}function P(K,Q){var Y,ne;return K&&K.state?(ne=K.state,Q<0?(Y=0,Q=-Q):(Y=1+(Q>>4),Q<48&&(Q&=15)),Q&&(Q<8||15=ce.wsize?(i.arraySet(ce.window,Q,Y-ce.wsize,ce.wsize,0),ce.wnext=0,ce.whave=ce.wsize):(ne<(de=ce.wsize-ce.wnext)&&(de=ne),i.arraySet(ce.window,Q,Y-ne,de,ce.wnext),(ne-=de)?(i.arraySet(ce.window,Q,Y-ne,ne,0),ce.wnext=ne,ce.whave=ce.wsize):(ce.wnext+=de,ce.wnext===ce.wsize&&(ce.wnext=0),ce.whave>>8&255,Y.check=o(Y.check,Ce,2,0),ge=oe=0,Y.mode=2;break}if(Y.flags=0,Y.head&&(Y.head.done=!1),!(1&Y.wrap)||(((255&oe)<<8)+(oe>>8))%31){K.msg="incorrect header check",Y.mode=30;break}if((15&oe)!=8){K.msg="unknown compression method",Y.mode=30;break}if(ge-=4,ve=8+(15&(oe>>>=4)),Y.wbits===0)Y.wbits=ve;else if(ve>Y.wbits){K.msg="invalid window size",Y.mode=30;break}Y.dmax=1<>8&1),512&Y.flags&&(Ce[0]=255&oe,Ce[1]=oe>>>8&255,Y.check=o(Y.check,Ce,2,0)),ge=oe=0,Y.mode=3;case 3:for(;ge<32;){if(ie===0)break e;ie--,oe+=ne[ce++]<>>8&255,Ce[2]=oe>>>16&255,Ce[3]=oe>>>24&255,Y.check=o(Y.check,Ce,4,0)),ge=oe=0,Y.mode=4;case 4:for(;ge<16;){if(ie===0)break e;ie--,oe+=ne[ce++]<>8),512&Y.flags&&(Ce[0]=255&oe,Ce[1]=oe>>>8&255,Y.check=o(Y.check,Ce,2,0)),ge=oe=0,Y.mode=5;case 5:if(1024&Y.flags){for(;ge<16;){if(ie===0)break e;ie--,oe+=ne[ce++]<>>8&255,Y.check=o(Y.check,Ce,2,0)),ge=oe=0}else Y.head&&(Y.head.extra=null);Y.mode=6;case 6:if(1024&Y.flags&&(ie<(Me=Y.length)&&(Me=ie),Me&&(Y.head&&(ve=Y.head.extra_len-Y.length,Y.head.extra||(Y.head.extra=new Array(Y.head.extra_len)),i.arraySet(Y.head.extra,ne,ce,Me,ve)),512&Y.flags&&(Y.check=o(Y.check,ne,Me,ce)),ie-=Me,ce+=Me,Y.length-=Me),Y.length))break e;Y.length=0,Y.mode=7;case 7:if(2048&Y.flags){if(ie===0)break e;for(Me=0;ve=ne[ce+Me++],Y.head&&ve&&Y.length<65536&&(Y.head.name+=String.fromCharCode(ve)),ve&&Me>9&1,Y.head.done=!0),K.adler=Y.check=0,Y.mode=12;break;case 10:for(;ge<32;){if(ie===0)break e;ie--,oe+=ne[ce++]<>>=7&ge,ge-=7&ge,Y.mode=27;break}for(;ge<3;){if(ie===0)break e;ie--,oe+=ne[ce++]<>>=1)){case 0:Y.mode=14;break;case 1:if($(Y),Y.mode=20,Q!==6)break;oe>>>=2,ge-=2;break e;case 2:Y.mode=17;break;case 3:K.msg="invalid block type",Y.mode=30}oe>>>=2,ge-=2;break;case 14:for(oe>>>=7&ge,ge-=7≥ge<32;){if(ie===0)break e;ie--,oe+=ne[ce++]<>>16^65535)){K.msg="invalid stored block lengths",Y.mode=30;break}if(Y.length=65535&oe,ge=oe=0,Y.mode=15,Q===6)break e;case 15:Y.mode=16;case 16:if(Me=Y.length){if(ie>>=5,ge-=5,Y.ndist=1+(31&oe),oe>>>=5,ge-=5,Y.ncode=4+(15&oe),oe>>>=4,ge-=4,286>>=3,ge-=3}for(;Y.have<19;)Y.lens[nt[Y.have++]]=0;if(Y.lencode=Y.lendyn,Y.lenbits=7,Re={bits:Y.lenbits},rt=d(0,Y.lens,0,19,Y.lencode,0,Y.work,Re),Y.lenbits=Re.bits,rt){K.msg="invalid code lengths set",Y.mode=30;break}Y.have=0,Y.mode=19;case 19:for(;Y.have>>16&255,ze=65535&Ke,!(($e=Ke>>>24)<=ge);){if(ie===0)break e;ie--,oe+=ne[ce++]<>>=$e,ge-=$e,Y.lens[Y.have++]=ze;else{if(ze===16){for(Qe=$e+2;ge>>=$e,ge-=$e,Y.have===0){K.msg="invalid bit length repeat",Y.mode=30;break}ve=Y.lens[Y.have-1],Me=3+(3&oe),oe>>>=2,ge-=2}else if(ze===17){for(Qe=$e+3;ge>>=$e)),oe>>>=3,ge-=3}else{for(Qe=$e+7;ge>>=$e)),oe>>>=7,ge-=7}if(Y.have+Me>Y.nlen+Y.ndist){K.msg="invalid bit length repeat",Y.mode=30;break}for(;Me--;)Y.lens[Y.have++]=ve}}if(Y.mode===30)break;if(Y.lens[256]===0){K.msg="invalid code -- missing end-of-block",Y.mode=30;break}if(Y.lenbits=9,Re={bits:Y.lenbits},rt=d(h,Y.lens,0,Y.nlen,Y.lencode,0,Y.work,Re),Y.lenbits=Re.bits,rt){K.msg="invalid literal/lengths set",Y.mode=30;break}if(Y.distbits=6,Y.distcode=Y.distdyn,Re={bits:Y.distbits},rt=d(m,Y.lens,Y.nlen,Y.ndist,Y.distcode,0,Y.work,Re),Y.distbits=Re.bits,rt){K.msg="invalid distances set",Y.mode=30;break}if(Y.mode=20,Q===6)break e;case 20:Y.mode=21;case 21:if(6<=ie&&258<=me){K.next_out=ae,K.avail_out=me,K.next_in=ce,K.avail_in=ie,Y.hold=oe,Y.bits=ge,c(K,Oe),ae=K.next_out,de=K.output,me=K.avail_out,ce=K.next_in,ne=K.input,ie=K.avail_in,oe=Y.hold,ge=Y.bits,Y.mode===12&&(Y.back=-1);break}for(Y.back=0;Se=(Ke=Y.lencode[oe&(1<>>16&255,ze=65535&Ke,!(($e=Ke>>>24)<=ge);){if(ie===0)break e;ie--,oe+=ne[ce++]<>Te)])>>>16&255,ze=65535&Ke,!(Te+($e=Ke>>>24)<=ge);){if(ie===0)break e;ie--,oe+=ne[ce++]<>>=Te,ge-=Te,Y.back+=Te}if(oe>>>=$e,ge-=$e,Y.back+=$e,Y.length=ze,Se===0){Y.mode=26;break}if(32&Se){Y.back=-1,Y.mode=12;break}if(64&Se){K.msg="invalid literal/length code",Y.mode=30;break}Y.extra=15&Se,Y.mode=22;case 22:if(Y.extra){for(Qe=Y.extra;ge>>=Y.extra,ge-=Y.extra,Y.back+=Y.extra}Y.was=Y.length,Y.mode=23;case 23:for(;Se=(Ke=Y.distcode[oe&(1<>>16&255,ze=65535&Ke,!(($e=Ke>>>24)<=ge);){if(ie===0)break e;ie--,oe+=ne[ce++]<>Te)])>>>16&255,ze=65535&Ke,!(Te+($e=Ke>>>24)<=ge);){if(ie===0)break e;ie--,oe+=ne[ce++]<>>=Te,ge-=Te,Y.back+=Te}if(oe>>>=$e,ge-=$e,Y.back+=$e,64&Se){K.msg="invalid distance code",Y.mode=30;break}Y.offset=ze,Y.extra=15&Se,Y.mode=24;case 24:if(Y.extra){for(Qe=Y.extra;ge>>=Y.extra,ge-=Y.extra,Y.back+=Y.extra}if(Y.offset>Y.dmax){K.msg="invalid distance too far back",Y.mode=30;break}Y.mode=25;case 25:if(me===0)break e;if(Me=Oe-me,Y.offset>Me){if((Me=Y.offset-Me)>Y.whave&&Y.sane){K.msg="invalid distance too far back",Y.mode=30;break}Pe=Me>Y.wnext?(Me-=Y.wnext,Y.wsize-Me):Y.wnext-Me,Me>Y.length&&(Me=Y.length),Ee=Y.window}else Ee=de,Pe=ae-Y.offset,Me=Y.length;for(meB?(F=Pe[Ee+b[Q]],ge[be+b[Q]]):(F=96,0),S=1<>ae)+(T-=S)]=z<<24|F<<16|$|0,T!==0;);for(S=1<>=1;if(S!==0?(oe&=S-1,oe+=S):oe=0,Q++,--Oe[K]==0){if(K===ne)break;K=m[x+b[Q]]}if(de>>7)]}function be(Ke,Ce){Ke.pending_buf[Ke.pending++]=255&Ce,Ke.pending_buf[Ke.pending++]=Ce>>>8&255}function Oe(Ke,Ce,nt){Ke.bi_valid>N-nt?(Ke.bi_buf|=Ce<>N-Ke.bi_valid,Ke.bi_valid+=nt-N):(Ke.bi_buf|=Ce<>>=1,nt<<=1,0<--Ce;);return nt>>>1}function Ee(Ke,Ce,nt){var $t,lt,it=new Array(b+1),Nt=0;for($t=1;$t<=b;$t++)it[$t]=Nt=Nt+nt[$t-1]<<1;for(lt=0;lt<=Ce;lt++){var Ft=Ke[2*lt+1];Ft!==0&&(Ke[2*lt]=Pe(it[Ft]++,Ft))}}function $e(Ke){var Ce;for(Ce=0;Ce>1;1<=nt;nt--)Te(Ke,it,nt);for(lt=at;nt=Ke.heap[1],Ke.heap[1]=Ke.heap[Ke.heap_len--],Te(Ke,it,1),$t=Ke.heap[1],Ke.heap[--Ke.heap_max]=nt,Ke.heap[--Ke.heap_max]=$t,it[2*lt]=it[2*nt]+it[2*$t],Ke.depth[lt]=(Ke.depth[nt]>=Ke.depth[$t]?Ke.depth[nt]:Ke.depth[$t])+1,it[2*nt+1]=it[2*$t+1]=lt,Ke.heap[1]=lt++,Te(Ke,it,1),2<=Ke.heap_len;);Ke.heap[--Ke.heap_max]=Ke.heap[1],function(et,Dt){var Jt,cs,Ht,dt,Qt,yt,ss=Dt.dyn_tree,Is=Dt.max_code,fs=Dt.stat_desc.static_tree,ar=Dt.stat_desc.has_stree,Er=Dt.stat_desc.extra_bits,Tr=Dt.stat_desc.extra_base,Lr=Dt.stat_desc.max_length,$r=0;for(dt=0;dt<=b;dt++)et.bl_count[dt]=0;for(ss[2*et.heap[et.heap_max]+1]=0,Jt=et.heap_max+1;Jt>=7;lt>>=1)if(1&Ie&&Ft.dyn_ltree[2*at]!==0)return l;if(Ft.dyn_ltree[18]!==0||Ft.dyn_ltree[20]!==0||Ft.dyn_ltree[26]!==0)return o;for(at=32;at>>3,(it=Ke.static_len+3+7>>>3)<=lt&&(lt=it)):lt=it=nt+5,nt+4<=lt&&Ce!==-1?Qe(Ke,Ce,nt,$t):Ke.strategy===4||it===lt?(Oe(Ke,2+($t?1:0),3),ye(Ke,X,K)):(Oe(Ke,4+($t?1:0),3),function(Ft,at,Ie,et){var Dt;for(Oe(Ft,at-257,5),Oe(Ft,Ie-1,5),Oe(Ft,et-4,4),Dt=0;Dt>>8&255,Ke.pending_buf[Ke.d_buf+2*Ke.last_lit+1]=255&Ce,Ke.pending_buf[Ke.l_buf+Ke.last_lit]=255&nt,Ke.last_lit++,Ce===0?Ke.dyn_ltree[2*nt]++:(Ke.matches++,Ce--,Ke.dyn_ltree[2*(Y[nt]+m+1)]++,Ke.dyn_dtree[2*ge(Ce)]++),Ke.last_lit===Ke.lit_bufsize-1},a._tr_align=function(Ke){Oe(Ke,2,3),Me(Ke,T,X),function(Ce){Ce.bi_valid===16?(be(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)}(Ke)}},{"../utils/common":41}],53:[function(r,n,a){n.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(r,n,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,h,m,x=1,g={},v=!1,j=l.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(l);b=b&&b.setTimeout?b:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){S(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,P=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=P,A}}()?(m="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",T,!1):l.attachEvent("onmessage",T),function(A){l.postMessage(m+A,"*")}):l.MessageChannel?((h=new MessageChannel).port1.onmessage=function(A){S(A.data)},function(A){h.port2.postMessage(A)}):j&&"onreadystatechange"in j.createElement("script")?(d=j.documentElement,function(A){var P=j.createElement("script");P.onreadystatechange=function(){S(A),P.onreadystatechange=null,d.removeChild(P),P=null},d.appendChild(P)}):function(A){setTimeout(S,0,A)},b.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var P=new Array(arguments.length-1),D=0;D"u"?i===void 0?this:i:self)}).call(this,typeof su<"u"?su:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Dlt);var SJt=Dlt.exports;const CJt=Io(SJt);function Ebe(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 TJt=()=>{const{isAdmin:s}=As(),[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState("all"),[o,c]=k.useState(new Set),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState("images"),[j,b]=k.useState(null),{data:N=[],isLoading:S}=gt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ie,error:me}=await H.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(me)throw me;return ie}}),{data:T=[]}=gt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ie,error:me}=await H.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(me)throw me;return ie}}),{data:A=[]}=gt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ie,error:me}=await H.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(me)throw me;return ie}}),{data:P=[]}=gt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ie,error:me}=await H.from("social_accounts").select("id, platform").eq("is_active",!0);if(me)throw me;return ie||[]}}),D=P.length>0,B=k.useMemo(()=>i==="all"?null:A.find(ie=>ie.month===i)||null,[i,A]),z=k.useMemo(()=>[...new Set(N.map(me=>me.month))].sort((me,oe)=>oe.localeCompare(me)),[N]);k.useEffect(()=>{z.length>0&&i==="all"&&l(z[0])},[z,i]);const F=ie=>{try{const me=j3e(ie,"yyyy-MM",new Date);return Ss(me,"MMMM yyyy")}catch{return ie}},$=k.useMemo(()=>i==="all"?N:N.filter(ie=>ie.month===i),[i,N]),X=k.useMemo(()=>{var ie;return i==="all"?null:((ie=T.find(me=>me.month===i))==null?void 0:ie.canva_link)||null},[i,T]),K=async ie=>{try{await navigator.clipboard.writeText(ie),ue.success("Caption copied to clipboard!")}catch{ue.error("Failed to copy caption")}},Q=async(ie,me)=>{try{const ge=await(await fetch(ie)).blob(),be=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),Oe=navigator.canShare&&navigator.canShare({files:[new File([ge],"test.jpg",{type:"image/jpeg"})]});if(be&&Oe){const Me=new File([ge],`social-swag-${me}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Me],title:"Social Swag Image"}),ue.success("Image ready to save!")}else{const Me=window.URL.createObjectURL(ge),Pe=document.createElement("a");Pe.href=Me,Pe.download=`social-swag-${me}.jpg`,document.body.appendChild(Pe),Pe.click(),document.body.removeChild(Pe),window.URL.revokeObjectURL(Me),ue.success("Image downloaded!")}}catch(oe){oe.name!=="AbortError"&&ue.error("Failed to download image")}},Y=ie=>{c(me=>{const oe=new Set(me);return oe.has(ie)?oe.delete(ie):oe.add(ie),oe})},ne=()=>{c(new Set($.map(ie=>ie.id)))},de=()=>{c(new Set),h(!1)},ce=async()=>{const ie=$.filter(me=>o.has(me.id));if(ie.length===0){ue.error("No images selected");return}x(!0),ue.info(`Preparing ${ie.length} images for download...`);try{const me=new CJt,oe=[...ie].sort((Pe,Ee)=>Pe.sort_order-Ee.sort_order);for(let Pe=0;Pe{d?Y(ie.id):r(ie)};return e.jsx(_s,{title:"Social Swag 2.0",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(fl,{className:"h-3 w-3 mr-1"}),N.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(Rn,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Dn,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Xt,{value:"gallery",className:"gap-2",children:[e.jsx(fl,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Xt,{value:"scheduled",className:"gap-2",children:[e.jsx(pd,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(as,{value:"gallery",className:"space-y-6",children:[D?e.jsx(Ne,{className:"border rounded-xl",children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Kn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(Ne,{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(De,{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(ku,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(au,{className:"h-5 w-5 text-pink-600"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Post directly to social media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Facebook & Instagram accounts to post images with one click!"})]}),e.jsx(G,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(Kn,{to:"/social-connections",children:[e.jsx(rl,{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:z.map(ie=>e.jsx("button",{onClick:()=>l(ie),className:Bt("px-4 py-2 rounded-full text-sm font-medium transition-all",i===ie?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:F(ie)},ie))}),i!=="all"&&(X?e.jsxs("a",{href:X,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(i)," 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(i)," 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:()=>{v("images"),de()},className:Bt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",g==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(fl,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{v("reels"),de()},className:Bt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",g==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Nh,{className:"h-4 w-4"}),"Reels"]})]}),g==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:d?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:ne,className:"gap-2",children:["Select All (",$.length,")"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:de,className:"gap-2",children:[e.jsx(_r,{className:"h-4 w-4"}),"Cancel"]}),o.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{size:"sm",onClick:ce,disabled:m,className:"gap-2",children:[e.jsx(Xa,{className:"h-4 w-4"}),m?"Downloading...":`Download ${o.size} Selected`]}),e.jsx("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:"Please ensure your browser allows downloads from the LevelUp Dashboard."})]})]}):e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2",children:[e.jsx(Hn,{className:"h-4 w-4"}),"Select Images"]})})]}),S&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!S&&g==="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:$.map(ie=>{const me=o.has(ie.id);return e.jsx(Ne,{className:Bt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",d&&me&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ae(ie),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:Ebe(ie.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"}),ie.post_date&&!d&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:Ss(new Date(ie.post_date+"T00:00:00"),"MMM d")})}),d&&e.jsx("div",{className:Bt("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(Hn,{className:"h-4 w-4"})}),!d&&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"})})]})},ie.id)})}),$.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(fl,{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."})]})]}),!S&&g==="reels"&&e.jsx(e.Fragment,{children:B?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(Ne,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>a(B),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:Ebe(B.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(Ge,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Nh,{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(Nh,{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:!!t,onOpenChange:()=>r(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:t&&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:Ebe(t.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(rn,{className:"h-4 w-4"}),Ss(new Date(t.created_at),"MMMM d, yyyy")]}),t.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(rn,{className:"h-3.5 w-3.5"}),"Post on ",Ss(new Date(t.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:t.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(G,{onClick:()=>{b({imageUrl:t.image_url,imageId:t.id,caption:t.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(Zr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(G,{variant:"outline",onClick:()=>K(t.caption),className:"flex-1 gap-2",children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(G,{variant:"outline",onClick:()=>Q(t.image_url,t.id),className:"flex-1 gap-2",children:[e.jsx(Xa,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(vs,{open:!!n,onOpenChange:()=>a(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:n&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:n.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(Nh,{className:"h-4 w-4"}),"Monthly Reel"]}),n.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:n.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[n.caption&&e.jsxs(G,{onClick:()=>K(n.caption||""),className:"flex-1 gap-2",children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy Caption"]}),n.canva_link&&e.jsxs(G,{variant:"outline",onClick:()=>window.open(n.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(NJt,{open:!!j,onOpenChange:ie=>!ie&&b(null),imageUrl:(j==null?void 0:j.imageUrl)||"",imageId:(j==null?void 0:j.imageId)||"",defaultCaption:(j==null?void 0:j.caption)||"",swagItemId:j==null?void 0:j.imageId})]}),e.jsx(as,{value:"scheduled",children:e.jsx(kJt,{})})]})]})})},EJt=()=>{const{swagId:s}=Xi(),{user:t}=As(),{toast:r}=Ea(),n=es(),{trackEngagement:a}=MP(),[i,l]=k.useState(""),{data:o,isLoading:c}=gt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:N,error:S}=await H.from("social_swag").select("*").eq("id",s).single();if(S)throw S;const{data:T}=await H.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...N,links:T||[]}},enabled:!!s});k.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=gt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:N,error:S}=await H.from("social_swag_likes").select("*").eq("swag_id",s);if(S)throw S;return N},enabled:!!s}),{data:h=[]}=gt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:N,error:S}=await H.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(S)throw S;const T=[...new Set(N.map(D=>D.user_id))],{data:A}=await H.from("profiles").select("id, name").in("id",T),P=new Map((A==null?void 0:A.map(D=>[D.id,D.name]))||[]);return N.map(D=>({...D,user_name:P.get(D.user_id)||"Unknown User"}))},enabled:!!s}),m=Lt({mutationFn:async N=>{const{error:S}=await H.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:N});if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),r({title:"Comment added!"})},onError:N=>{r({title:"Error adding comment",description:N.message,variant:"destructive"})}}),x=Lt({mutationFn:async N=>{const{error:S}=await H.from("social_swag_comments").delete().eq("id",N);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),r({title:"Comment deleted"})}}),g=Lt({mutationFn:async()=>{const N=d.find(S=>S.user_id===(t==null?void 0:t.id));if(N){const{error:S}=await H.from("social_swag_likes").delete().eq("id",N.id);if(S)throw S}else{const{error:S}=await H.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-likes",s]})}}),v=d.some(N=>N.user_id===(t==null?void 0:t.id)),j=N=>N.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=N=>{N.preventDefault(),!(!i.trim()||!t)&&m.mutate(i.trim())};return c?e.jsx(_s,{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(_s,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/social-swag",children:[e.jsx(wa,{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(DP,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(G,{variant:v?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Mh,{className:`h-4 w-4 ${v?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(xo,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(N=>e.jsxs(G,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(N.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:N.title}),e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground"})]},N.id))})]})}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(tc,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Add a comment...",value:i,onChange:N=>l(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||m.isPending,children:e.jsx(Zr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(N=>e.jsx(Ne,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(bn,{className:"text-sm",children:j(N.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:N.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:al(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(N.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(_s,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(xo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},AJt=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,h]=k.useState(!0),m=x=>x.split(" ").map(g=>g[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(G,{variant:r==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>n("all"),children:[e.jsx(Wj,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(bx,{open:i,onOpenChange:l,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(so,{className:"h-4 w-4"}):e.jsx(ya,{className:"h-4 w-4"})]})}),e.jsx(wx,{className:"space-y-1 pl-2",children:s.map(x=>e.jsxs(G,{variant:r===x.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(x.id),children:[e.jsx("span",{className:"mr-2",children:x.icon||"📂"}),e.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),t.length>0&&e.jsxs(bx,{open:o,onOpenChange:c,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(so,{className:"h-4 w-4"}):e.jsx(ya,{className:"h-4 w-4"})]})}),e.jsx(wx,{className:"space-y-1 pl-2",children:t.map(x=>e.jsxs(G,{variant:r===`group:${x.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(`group:${x.id}`),children:[e.jsx("span",{className:"mr-2",children:x.icon||"🔒"}),e.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),e.jsxs(bx,{open:d,onOpenChange:h,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(fr,{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(so,{className:"h-4 w-4"}):e.jsx(ya,{className:"h-4 w-4"})]})}),e.jsx(wx,{className:"pl-2 space-y-1",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2 px-2",children:"No one else online right now"}):a.map(x=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(vn,{className:"h-7 w-7",children:[e.jsx(ga,{src:x.avatarUrl}),e.jsx(bn,{className:"text-xs",children:m(x.name)})]}),e.jsx(Bd,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:x.name})]},x.id))})]})]})})})},MJt=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!1),o=d=>d.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),c=()=>{if(r==="all")return"All Posts";if(r.startsWith("group:")){const h=r.replace("group:",""),m=t.find(x=>x.id===h);return m?`🔒 ${m.name}`:"Private Group"}const d=s.find(h=>h.id===r);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(so,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Vd,{className:"w-56 bg-background border",children:[e.jsxs(Da,{onClick:()=>n("all"),children:[e.jsx(Wj,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(y_,{}),e.jsx(Tue,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Da,{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(y_,{}),e.jsxs(Tue,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Da,{onClick:()=>n(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(G2,{open:i,onOpenChange:l,children:[e.jsx(C3e,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(fr,{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(I_,{children:[e.jsx(W2,{children:e.jsxs(K2,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(ti,{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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:d.avatarUrl}),e.jsx(bn,{children:o(d.name)})]}),e.jsx(Bd,{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 Abe,_xe="HoverCard",[Rlt]=yd(_xe,[x1]),wxe=x1(),[IJt,BTe]=Rlt(_xe),Olt=s=>{const{__scopeHoverCard:t,children:r,open:n,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=wxe(t),d=k.useRef(0),h=k.useRef(0),m=k.useRef(!1),x=k.useRef(!1),[g,v]=Lh({prop:n,defaultProp:a??!1,onChange:i,caller:_xe}),j=k.useCallback(()=>{clearTimeout(h.current),d.current=window.setTimeout(()=>v(!0),l)},[l,v]),b=k.useCallback(()=>{clearTimeout(d.current),!m.current&&!x.current&&(h.current=window.setTimeout(()=>v(!1),o))},[o,v]),N=k.useCallback(()=>v(!1),[v]);return k.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(h.current)},[]),e.jsx(IJt,{scope:t,open:g,onOpenChange:v,onOpen:j,onClose:b,onDismiss:N,hasSelectionRef:m,isPointerDownOnContentRef:x,children:e.jsx(IB,{...c,children:r})})};Olt.displayName=_xe;var Flt="HoverCardTrigger",Blt=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=BTe(Flt,r),i=wxe(r);return e.jsx(bP,{asChild:!0,...i,children:e.jsx(pn.a,{"data-state":a.open?"open":"closed",...n,ref:t,onPointerEnter:Or(s.onPointerEnter,Ghe(a.onOpen)),onPointerLeave:Or(s.onPointerLeave,Ghe(a.onClose)),onFocus:Or(s.onFocus,a.onOpen),onBlur:Or(s.onBlur,a.onClose),onTouchStart:Or(s.onTouchStart,l=>l.preventDefault())})})});Blt.displayName=Flt;var PJt="HoverCardPortal",[eqs,LJt]=Rlt(PJt,{forceMount:void 0}),Hhe="HoverCardContent",zlt=k.forwardRef((s,t)=>{const r=LJt(Hhe,s.__scopeHoverCard),{forceMount:n=r.forceMount,...a}=s,i=BTe(Hhe,s.__scopeHoverCard);return e.jsx(qd,{present:n||i.open,children:e.jsx(DJt,{"data-state":i.open?"open":"closed",...a,onPointerEnter:Or(s.onPointerEnter,Ghe(i.onOpen)),onPointerLeave:Or(s.onPointerLeave,Ghe(i.onClose)),ref:t})})});zlt.displayName=Hhe;var DJt=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=BTe(Hhe,r),d=wxe(r),h=k.useRef(null),m=Qa(t,h),[x,g]=k.useState(!1);return k.useEffect(()=>{if(x){const v=document.body;return Abe=v.style.userSelect||v.style.webkitUserSelect,v.style.userSelect="none",v.style.webkitUserSelect="none",()=>{v.style.userSelect=Abe,v.style.webkitUserSelect=Abe}}},[x]),k.useEffect(()=>{if(h.current){const v=()=>{g(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",v),()=>{document.removeEventListener("pointerup",v),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),k.useEffect(()=>{h.current&&FJt(h.current).forEach(j=>j.setAttribute("tabindex","-1"))}),e.jsx(F2,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:Or(i,v=>{v.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(PB,{...d,...o,onPointerDown:Or(o.onPointerDown,v=>{v.currentTarget.contains(v.target)&&g(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:m,style:{...o.style,userSelect:x?"text":void 0,WebkitUserSelect:x?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),RJt="HoverCardArrow",OJt=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=wxe(r);return e.jsx(LB,{...a,...n,ref:t})});OJt.displayName=RJt;function Ghe(s){return t=>t.pointerType==="touch"?void 0:s()}function FJt(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 BJt=Olt,zJt=Blt,$lt=zlt;const $Jt=BJt,UJt=zJt,Ult=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx($lt,{ref:a,align:t,sideOffset:r,className:Bt("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}));Ult.displayName=$lt.displayName;const qJt=[{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"}],VJt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),qlt=({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($Jt,{openDelay:200,closeDelay:100,children:[e.jsx(UJt,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(Ult,{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=qJt.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(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:l.user_avatar||void 0}),e.jsx(bn,{className:"text-[10px]",children:VJt(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 HJt({images:s,initialIndex:t=0,open:r,onOpenChange:n}){const[a,i]=k.useState(t),[l,o]=k.useState(!1);k.useEffect(()=>{r&&(i(t),o(!1))},[r,t]);const c=()=>{i(x=>x>0?x-1:s.length-1),o(!1)},d=()=>{i(x=>x{r&&(x.key==="ArrowLeft"&&c(),x.key==="ArrowRight"&&d(),x.key==="Escape"&&n(!1))},[r,s.length]);k.useEffect(()=>(window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)),[h]);const m=s[a];return e.jsx(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(G,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>n(!1),children:e.jsx(_r,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:c,children:e.jsx(Vo,{className:"h-8 w-8"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:d,children:e.jsx(ya,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(m==null?void 0:m.type)==="image"&&e.jsx(G,{variant:"ghost",size:"icon",className:"absolute top-2 left-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>o(!l),children:l?e.jsx(yM,{className:"h-5 w-5"}):e.jsx(r2,{className:"h-5 w-5"})}),e.jsx("div",{className:Bt("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(m==null?void 0:m.type)==="image"&&o(!l),children:(m==null?void 0:m.type)==="video"?e.jsx("video",{src:m.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:x=>x.stopPropagation()}):e.jsx("img",{src:m==null?void 0:m.url,alt:"",className:Bt("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((x,g)=>e.jsx("button",{onClick:()=>{i(g),o(!1)},className:Bt("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===g?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:x.type==="video"?e.jsx("video",{src:x.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:x.url,alt:"",className:"w-full h-full object-cover"})},g))})]})})}const jU=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],GJt=({commentId:s,reactions:t,currentUserId:r})=>{var d,h;const n=es(),[a,i]=k.useState(!1),l=t.find(m=>m.user_id===r),o=Lt({mutationFn:async m=>{l?l.reaction_type===m?await H.from("community_comment_reactions").delete().eq("id",l.id):await H.from("community_comment_reactions").update({reaction_type:m}).eq("id",l.id):await H.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(qlt,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(m=>{var x;return e.jsx("span",{className:"text-sm",children:(x=jU.find(g=>g.type===m))==null?void 0:x.emoji},m)})}),e.jsx("span",{children:t.length})]})}),r&&e.jsxs(Ao,{open:a,onOpenChange:i,children:[e.jsx(Mo,{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=jU.find(m=>m.type===l.reaction_type))==null?void 0:d.emoji," ",(h=jU.find(m=>m.type===l.reaction_type))==null?void 0:h.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(hi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(wo,{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:jU.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 zTe({content:s,className:t}){const r=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,n=[];let a=0,i,l=0;for(;(i=r.exec(s))!==null;){if(i.index>a&&n.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],h=o==="#";n.push(e.jsx(Kn,{to:h?`/templates/${d}`:`/profile?user=${d}`,className:Bt("font-medium hover:underline",h?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:m=>m.stopPropagation(),children:h?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let h;try{const m=new URL(c);h=m.hostname+(m.pathname!=="/"?m.pathname.slice(0,20)+(m.pathname.length>20?"...":""):"")}catch{h=c.length>40?c.slice(0,40)+"...":c}n.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:m=>m.stopPropagation(),children:h},`url-${l++}`)),d&&n.push(d)}a=i.index+i[0].length}return ae.jsx(k.Fragment,{children:o},c))})}function Whe({value:s,onChange:t,placeholder:r="What's on your mind? Use @ to mention someone",className:n,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const h=k.useRef(null),m=k.useRef(null),[x,g]=k.useState(!1),[v,j]=k.useState("user"),[b,N]=k.useState(""),[S,T]=k.useState(null),[A,P]=k.useState(0),[D,B]=k.useState({top:0,left:0,width:0}),z=k.useRef(new Map),F=k.useRef(new Map),$=ge=>{if(c==="plain"){const Pe=[];return z.current.forEach(($e,Se)=>{ge.includes(`@${Se}`)&&Pe.push($e)}),[...new Set(Pe)]}const be=/@\[([^\]]+)\]\(([^)]+)\)/g,Oe=[];let Me;for(;(Me=be.exec(ge))!==null;)Oe.push(Me[2]);return[...new Set(Oe)]},X=ge=>{if(c==="plain"){const Pe=[];return F.current.forEach(($e,Se)=>{ge.includes(`#${Se}`)&&Pe.push($e)}),[...new Set(Pe)]}const be=/#\[([^\]]+)\]\(([^)]+)\)/g,Oe=[];let Me;for(;(Me=be.exec(ge))!==null;)Oe.push(Me[2]);return[...new Set(Oe)]};k.useEffect(()=>{if(i){const ge=$(s);i(ge)}if(l){const ge=X(s);l(ge)}},[s,i,l,c]);const{data:K=[],isLoading:Q}=gt({queryKey:["mention-users",b],queryFn:async()=>{const ge=H.from("profiles").select("id, name").limit(8),be=b.length>=1?ge.ilike("name",`%${b}%`):ge.order("name"),{data:Oe,error:Me}=await be;if(Me)throw Me;const Pe=Oe.map($e=>$e.id),Ee=await Srt(Pe);return Oe.map($e=>({id:$e.id,name:$e.name||"Unknown",avatar_url:Ee.get($e.id)}))},enabled:x&&v==="user",staleTime:3e4}),{data:Y=[],isLoading:ne}=gt({queryKey:["mention-templates",b],queryFn:async()=>{let ge=H.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&&(ge=ge.ilike("name",`%${b}%`));const{data:be,error:Oe}=await ge;if(Oe)throw Oe;return be||[]},enabled:x&&v==="template"&&d,staleTime:3e4}),de=v==="user"?Q:ne,ce=v==="user"?K:Y,ae=ge=>ge.split(" ").map(be=>be[0]).join("").toUpperCase().slice(0,2),ie=ge=>{const be=ge.target.value,Oe=ge.target.selectionStart;t(be);const Me=be.substring(0,Oe),Pe=Me.lastIndexOf("@"),Ee=d?Me.lastIndexOf("#"):-1;let $e=-1,Se="user";if(Pe>Ee?($e=Pe,Se="user"):Ee>Pe&&d&&($e=Ee,Se="template"),$e!==-1){const ze=Me.substring($e+1),Te=ze.includes(" "),ye=ze.includes(` `);if(!Te&&!ye&&ze.length<=30){T($e),N(ze),j(Se),g(!0),P(0);return}}g(!1),T(null)},me=ge=>{if(S===null)return;const be=s.substring(0,S),Oe=s.substring(S+b.length+1),Me=v==="user"?"@":"#",Pe=c==="plain"?`${Me}${ge.name} `:`${Me}[${ge.name}](${ge.id}) `;c==="plain"&&(v==="user"?z.current.set(ge.name,ge.id):F.current.set(ge.name,ge.id));const Ee=be+Pe+Oe;t(Ee),g(!1),T(null),N(""),setTimeout(()=>{if(h.current){const $e=be.length+Pe.length;h.current.focus(),h.current.setSelectionRange($e,$e)}},0)},oe=ge=>{if(!(!x||ce.length===0))switch(ge.key){case"ArrowDown":ge.preventDefault(),P(be=>(be+1)%ce.length);break;case"ArrowUp":ge.preventDefault(),P(be=>(be-1+ce.length)%ce.length);break;case"Enter":ce[A]&&(ge.preventDefault(),me(ce[A]));break;case"Escape":ge.preventDefault(),g(!1);break;case"Tab":ce[A]&&(ge.preventDefault(),me(ce[A]));break}};return k.useEffect(()=>{const ge=be=>{m.current&&!m.current.contains(be.target)&&h.current&&!h.current.contains(be.target)&&g(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[]),k.useEffect(()=>{if(!x)return;const ge=()=>{const be=h.current;if(!be)return;const Oe=be.getBoundingClientRect();B({top:Oe.bottom+4,left:Oe.left,width:Oe.width})};return ge(),window.addEventListener("resize",ge),window.addEventListener("scroll",ge,!0),()=>{window.removeEventListener("resize",ge),window.removeEventListener("scroll",ge,!0)}},[x,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ur,{ref:h,value:s,onChange:ie,onKeyDown:ge=>{oe(ge),ge.defaultPrevented||o==null||o(ge)},placeholder:r,className:Bt("resize-none",n),style:{minHeight:a}}),x&&pf.createPortal(e.jsxs("div",{ref:m,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:D.top,left:D.left,width:D.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:v==="user"?"👤 Mention a person":"📋 Link a template"}),de?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ce.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:b.length<1?`Type to search ${v==="user"?"people":"templates"}...`:`No ${v==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:ce.map((ge,be)=>e.jsx("li",{className:Bt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",be===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>me(ge),onMouseEnter:()=>P(be),children:v==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:ge.avatar_url}),e.jsx(bn,{className:"text-xs",children:ae(ge.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ge.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:ge.preview_image_url?e.jsx("img",{src:ge.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(pl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:ge.name})]})},ge.id))})]}),document.body)]})}function WJt(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,r=[];let n;for(;(n=t.exec(s))!==null;)r.push(n[2]);return[...new Set(r)]}const Mze=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function Vlt({comment:s,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l=0}){const o=es(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,g]=k.useState([]),v=Lt({mutationFn:async({content:S,parentCommentId:T})=>{const{data:A,error:P}=await H.from("community_comments").insert({post_id:t,user_id:r,content:S,parent_comment_id:T}).select("id").single();if(P)throw P;const D=x;if(D.length>0&&A){const B=D.filter(z=>z!==r).map(z=>({comment_id:A.id,mentioned_user_id:z,mentioned_by_user_id:r}));B.length>0&&await H.from("community_comment_mentions").insert(B)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),m(""),g([]),d(!1)}}),j=Lt({mutationFn:async S=>{const{error:T}=await H.from("community_comments").delete().eq("id",S);if(T)throw T},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),b=()=>{h.trim()&&v.mutate({content:h,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ga,{src:s.user_avatar||void 0}),e.jsx(bn,{className:"text-xs",children:Mze(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(zTe,{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:al(new Date(s.created_at),{addSuffix:!0})}),e.jsx(GJt,{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(SO,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===r||i)&&e.jsx("button",{onClick:()=>j.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(vn,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(ga,{src:n||void 0}),e.jsx(bn,{className:"text-xs",children:Mze((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Whe,{placeholder:`Reply to ${s.user_name}...`,value:h,onChange:m,onMentionsChange:g,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:b,disabled:!h.trim()||v.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Zr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(S=>e.jsx(Vlt,{comment:S,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l+1},S.id))})]})}const NU=[{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"}],KJt=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:r,isAdmin:n}=As(),{avatarUrl:a}=krt(s==null?void 0:s.id),{onlineUsers:i}=aQe(),{toast:l}=Ea(),o=es(),c=k.useRef(null),[d,h]=k.useState("all"),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState([]),[T,A]=k.useState([]),[P,D]=k.useState(""),[B,z]=k.useState(!1),[F,$]=k.useState(null),[X,K]=k.useState(""),[Q,Y]=k.useState(new Set),[ne,de]=k.useState({}),[ce,ae]=k.useState({}),[ie,me]=k.useState([]),[oe,ge]=k.useState([]),[be,Oe]=k.useState({open:!1,images:[],index:0});k.useEffect(()=>{if(d.startsWith("group:")){const Ie=d.replace("group:","");b(Ie),v("")}else d!=="all"?(v(d),b("")):(v(""),b(""))},[d]);const{data:Me=[]}=gt({queryKey:["community-categories"],queryFn:async()=>{const{data:Ie,error:et}=await H.from("community_categories").select("*").order("sort_order");if(et)throw et;return Ie}}),{data:Pe=[]}=gt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:Ie,error:et}=await H.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(et)throw et;return Ie}}),Ee=20,{data:$e,isLoading:Se,hasNextPage:ze,fetchNextPage:Te,isFetchingNextPage:ye}=XSt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:Ie})=>{var bt;const et=Ie*Ee,Dt=et+Ee;let Jt=H.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(et,Dt);if(d.startsWith("group:")){const ut=d.replace("group:","");Jt=Jt.eq("private_group_id",ut)}else d==="all"||(Jt=Jt.eq("category_id",d).is("private_group_id",null));const{data:cs,error:Ht}=await Jt;if(Ht)throw Ht;const dt=((cs==null?void 0:cs.length)||0)>Ee,Qt=(cs||[]).slice(0,Ee);if(Qt.length===0)return{posts:[],hasMore:!1,nextPage:Ie+1};const yt=Qt.map(ut=>ut.id),ss=[...new Set(Qt.filter(ut=>ut.category_id).map(ut=>ut.category_id))].filter(Boolean),[Is,fs,ar,Er,Tr]=await Promise.all([ss.length?H.from("community_categories").select("*").in("id",ss):Promise.resolve({data:[]}),H.from("community_post_media").select("*").in("post_id",yt).order("sort_order"),H.from("community_reactions").select("*").in("post_id",yt),H.from("community_comments").select("*").in("post_id",yt).order("created_at",{ascending:!0}),H.from("community_post_resources").select("*").in("post_id",yt)]),Lr=Is==null?void 0:Is.data,$r=fs==null?void 0:fs.data,kr=ar==null?void 0:ar.data,Sr=Er==null?void 0:Er.data,hn=Tr==null?void 0:Tr.data,zn=(Sr||[]).map(ut=>ut.id),[Xs,Ur]=await Promise.all([zn.length?H.from("community_comment_reactions").select("*").in("comment_id",zn):Promise.resolve({data:[]}),(()=>{const ut=(hn||[]).filter(kt=>kt.resource_type==="template").map(kt=>kt.resource_id);return ut.length===0?Promise.resolve({data:[]}):H.from("canva_templates").select("id, name, preview_image_url").in("id",ut)})()]),xn=(Xs==null?void 0:Xs.data)||[],us=(Ur==null?void 0:Ur.data)||[],pr=new Map(us.map(ut=>[ut.id,{name:ut.name,preview_image_url:ut.preview_image_url}])),Hr=Array.from(new Set([...Qt.map(ut=>ut.user_id),...(kr||[]).map(ut=>ut.user_id),...(Sr||[]).map(ut=>ut.user_id),...xn.map(ut=>ut.user_id)])),[aa,Na]=await Promise.all([Hr.length?H.from("profiles").select("id, name").in("id",Hr):Promise.resolve({data:[]}),Srt(Hr)]),Je=new Map(((bt=aa==null?void 0:aa.data)==null?void 0:bt.map(ut=>[ut.id,ut.name]))||[]),Fe=new Map((Lr||[]).map(ut=>[ut.id,ut])),We=ut=>{const kt=new Map,Gt=[];return ut.forEach(Mt=>{kt.set(Mt.id,{...Mt,user_name:Je.get(Mt.user_id)||"Unknown User",user_avatar:Na.get(Mt.user_id),reactions:xn.filter(Kt=>Kt.comment_id===Mt.id).map(Kt=>({...Kt,user_name:Je.get(Kt.user_id)||"Unknown User",user_avatar:Na.get(Kt.user_id)})),replies:[]})}),ut.forEach(Mt=>{const Kt=kt.get(Mt.id);if(Mt.parent_comment_id&&kt.has(Mt.parent_comment_id)){const Es=kt.get(Mt.parent_comment_id);Es.replies=Es.replies||[],Es.replies.push(Kt)}else Gt.push(Kt)}),Gt};return{posts:Qt.map(ut=>{const kt=(hn||[]).filter(Gt=>Gt.post_id===ut.id).map(Gt=>{let Mt="",Kt=null;if(Gt.resource_type==="template"){const Es=pr.get(Gt.resource_id);Mt=(Es==null?void 0:Es.name)||"Unknown Template",Kt=(Es==null?void 0:Es.preview_image_url)||null}return{id:Gt.id,resource_type:Gt.resource_type,resource_id:Gt.resource_id,resource_name:Mt,resource_preview_url:Kt}});return{...ut,user_name:Je.get(ut.user_id)||"Unknown User",user_avatar:Na.get(ut.user_id),category:ut.category_id?Fe.get(ut.category_id):null,media:($r||[]).filter(Gt=>Gt.post_id===ut.id),reactions:((kr||[]).filter(Gt=>Gt.post_id===ut.id)||[]).map(Gt=>({...Gt,user_name:Je.get(Gt.user_id)||"Unknown User",user_avatar:Na.get(Gt.user_id)})),comments:We((Sr||[]).filter(Gt=>Gt.post_id===ut.id)),resources:kt}}),hasMore:dt,nextPage:Ie+1}},getNextPageParam:Ie=>Ie.hasMore?Ie.nextPage:void 0}),ct=k.useMemo(()=>($e==null?void 0:$e.pages.flatMap(Ie=>Ie.posts))??[],[$e]),ve=Lt({mutationFn:async()=>{z(!0);const{data:Ie,error:et}=await H.from("community_posts").insert({user_id:s.id,category_id:j?null:g||null,private_group_id:j||null,content:m,link_url:P||null}).select().single();if(et)throw et;for(let Jt=0;Jt0){const Jt=ie.filter(cs=>cs!==s.id).map(cs=>({post_id:Ie.id,mentioned_user_id:cs,mentioned_by_user_id:s.id}));Jt.length>0&&await H.from("community_post_mentions").insert(Jt)}const Dt=WJt(m);if(Dt.length>0){const Jt=Dt.map(cs=>({post_id:Ie.id,resource_type:"template",resource_id:cs}));await H.from("community_post_resources").insert(Jt)}return Ie},onSuccess:async Ie=>{var et;o.invalidateQueries({queryKey:["community-posts"]}),x(""),me([]),ge([]),v(""),b(""),S([]),A([]),D(""),l({title:"Post created!"});try{const Dt=((et=s==null?void 0:s.user_metadata)==null?void 0:et.name)||"Someone",Jt=m.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),cs=Jt.length>50?Jt.substring(0,50)+"...":Jt;await H.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Dt}: ${cs}`,url:"/community"}})}catch(Dt){console.error("Failed to send push notification:",Dt)}},onError:Ie=>{l({title:"Error creating post",description:Ie.message,variant:"destructive"})},onSettled:()=>z(!1)}),rt=Lt({mutationFn:async({postId:Ie,content:et})=>{const{error:Dt}=await H.from("community_posts").update({content:et}).eq("id",Ie);if(Dt)throw Dt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),$(null),K(""),l({title:"Post updated!"})}}),Re=Lt({mutationFn:async Ie=>{const{error:et}=await H.from("community_posts").delete().eq("id",Ie);if(et)throw et},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Qe=Lt({mutationFn:async({postId:Ie,isPinned:et})=>{const{error:Dt}=await H.from("community_posts").update({is_pinned:!et,pinned_at:et?null:new Date().toISOString(),pinned_by:et?null:s==null?void 0:s.id}).eq("id",Ie);if(Dt)throw Dt},onSuccess:(Ie,{isPinned:et})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:et?"Post unpinned":"Post pinned to top"})}}),Ke=Lt({mutationFn:async({postId:Ie,reactionType:et})=>{var Jt;const Dt=(Jt=ct.find(cs=>cs.id===Ie))==null?void 0:Jt.reactions.find(cs=>cs.user_id===(s==null?void 0:s.id));Dt?Dt.reaction_type===et?await H.from("community_reactions").delete().eq("id",Dt.id):await H.from("community_reactions").update({reaction_type:et}).eq("id",Dt.id):await H.from("community_reactions").insert({post_id:Ie,user_id:s.id,reaction_type:et})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ce=Lt({mutationFn:async({postId:Ie,content:et})=>{const{data:Dt,error:Jt}=await H.from("community_comments").insert({post_id:Ie,user_id:s.id,content:et}).select("id").single();if(Jt)throw Jt;const cs=ce[Ie]||[];if(cs.length>0&&Dt){const Ht=cs.filter(dt=>dt!==s.id).map(dt=>({comment_id:Dt.id,mentioned_user_id:dt,mentioned_by_user_id:s.id}));Ht.length>0&&await H.from("community_comment_mentions").insert(Ht)}},onSuccess:(Ie,{postId:et})=>{o.invalidateQueries({queryKey:["community-posts"]}),de(Dt=>({...Dt,[et]:""})),ae(Dt=>({...Dt,[et]:[]}))}});Lt({mutationFn:async Ie=>{const{error:et}=await H.from("community_comments").delete().eq("id",Ie);if(et)throw et},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const nt=Ie=>{const et=Array.from(Ie.target.files||[]);if(et.length+N.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}S(Dt=>[...Dt,...et]),et.forEach(Dt=>{const Jt=new FileReader;Jt.onloadend=()=>{A(cs=>[...cs,Jt.result])},Jt.readAsDataURL(Dt)})},$t=Ie=>{S(et=>et.filter((Dt,Jt)=>Jt!==Ie)),A(et=>et.filter((Dt,Jt)=>Jt!==Ie))},lt=Ie=>Ie.split(" ").map(et=>et[0]).join("").toUpperCase().slice(0,2),it=Ie=>{const et={};return Ie.forEach(Dt=>{et[Dt.reaction_type]=(et[Dt.reaction_type]||0)+1}),et},Nt=Ie=>{var et;return(et=Ie.find(Dt=>Dt.user_id===(s==null?void 0:s.id)))==null?void 0:et.reaction_type},Ft=Ie=>Ie.reduce((et,Dt)=>et+1+(Dt.replies?Ft(Dt.replies):0),0),at=Ie=>{if(n)return!0;if(!t||!Ie.private_group_id)return!1;const et=Pe.find(Dt=>Dt.id===Ie.private_group_id);return et!=null&&et.brokerage_id?r.some(Dt=>Dt.id===et.brokerage_id):!1};return e.jsx(_s,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(AJt,{categories:Me,privateGroups:Pe,selectedFilter:d,onFilterChange:h,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(MJt,{categories:Me,privateGroups:Pe,selectedFilter:d,onFilterChange:h,onlineUsers:i}),e.jsx(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:a||void 0}),e.jsx(bn,{children:s!=null&&s.email?lt(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Whe,{placeholder:n?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:m,onChange:x,onMentionsChange:me,onTemplatesChange:ge,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:n}),T.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:T.map((Ie,et)=>{var Dt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Dt=N[et])!=null&&Dt.type.startsWith("video/")?e.jsx("video",{src:Ie,className:"w-full h-full object-cover"}):e.jsx("img",{src:Ie,alt:"",className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>$t(et),children:e.jsx(_r,{className:"h-3 w-3"})})]},et)})}),P&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:P,onChange:Ie=>D(Ie.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(G,{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:nt,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>{var Ie;return(Ie=c.current)==null?void 0:Ie.click()},children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>{var Ie;return(Ie=c.current)==null?void 0:Ie.click()},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>D("https://"),children:[e.jsx(xo,{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:[Pe.length>0?e.jsxs(zs,{value:j||g||"none",onValueChange:Ie=>{Ie==="none"?(v(""),b("")):Ie.startsWith("group:")?(b(Ie.replace("group:","")),v("")):(v(Ie),b(""))},children:[e.jsx(Os,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No category"}),Me.map(Ie=>e.jsxs(mt,{value:Ie.id,children:[Ie.icon," ",Ie.name]},Ie.id)),Pe.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"}),Pe.map(Ie=>e.jsxs(mt,{value:`group:${Ie.id}`,children:[Ie.icon||"🔒"," ",Ie.name]},Ie.id))]})]})]}):e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(Us,{placeholder:"Category"})}),e.jsx(Fs,{children:Me.map(Ie=>e.jsxs(mt,{value:Ie.id,children:[Ie.icon," ",Ie.name]},Ie.id))})]}),e.jsxs(G,{size:"sm",onClick:()=>ve.mutate(),disabled:!m.trim()||B,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Se?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Ie,et)=>e.jsx(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Vs,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Vs,{className:"h-4 w-32"}),e.jsx(Vs,{className:"h-4 w-full"}),e.jsx(Vs,{className:"h-4 w-3/4"})]})]})})},et))}):ct.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(tc,{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:[ct.map(Ie=>{var et,Dt,Jt,cs;return e.jsx(Ne,{children:e.jsxs(De,{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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:Ie.user_avatar||void 0}),e.jsx(bn,{children:lt(Ie.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:Ie.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:al(new Date(Ie.created_at),{addSuffix:!0})}),Ie.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[Ie.category.icon," ",Ie.category.name]})]})]})]})]}),(Ie.user_id===(s==null?void 0:s.id)||at(Ie))&&e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ix,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",children:[at(Ie)&&Ie.private_group_id&&e.jsx(Da,{onClick:()=>Qe.mutate({postId:Ie.id,isPinned:Ie.is_pinned}),children:Ie.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(_O,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jj,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),Ie.user_id===(s==null?void 0:s.id)&&e.jsxs(Da,{onClick:()=>{$(Ie),K(Ie.content)},children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Da,{className:"text-destructive",onClick:()=>Re.mutate(Ie.id),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),Ie.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),Ie.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(Jj,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(zTe,{content:Ie.content})}),Ie.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${Ie.media.length===1?"grid-cols-1":Ie.media.length===2?"grid-cols-2":Ie.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:Ie.media.slice(0,4).map((Ht,dt)=>{const Qt=dt===3&&Ie.media.length>4,yt=Ie.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${Ie.media.length===1?"max-h-[500px]":Ie.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Oe({open:!0,images:Ie.media.map(ss=>({url:ss.media_url,type:ss.media_type==="video"?"video":"image"})),index:dt}),children:[Ht.media_type==="video"?e.jsx("video",{src:Ht.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Ht.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"})})})}),Qt&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",yt]})})]},Ht.id)})}),Ie.link_url&&e.jsxs("a",{href:Ie.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[Ie.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:Ie.link_image,alt:Ie.link_title||"Link preview",className:"w-full h-full object-cover",onError:Ht=>{Ht.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:Ie.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:Ie.link_title}),Ie.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:Ie.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(Ie.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(xo,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Ie.link_url})]})})]}),Ie.reactions.length>0&&e.jsx(qlt,{reactions:Ie.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(it(Ie.reactions)).slice(0,3).map(([Ht])=>{var dt;return e.jsx("span",{className:"text-base",children:(dt=NU.find(Qt=>Qt.type===Ht))==null?void 0:dt.emoji},Ht)})}),e.jsx("span",{children:Ie.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"flex-1",children:[Nt(Ie.reactions)?e.jsx("span",{className:"mr-1",children:(et=NU.find(Ht=>Ht.type===Nt(Ie.reactions)))==null?void 0:et.emoji}):e.jsx(Mh,{className:"h-4 w-4 mr-1"}),Nt(Ie.reactions)?(Dt=NU.find(Ht=>Ht.type===Nt(Ie.reactions)))==null?void 0:Dt.label:"Like"]})}),e.jsx(wo,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:NU.map(Ht=>e.jsx("button",{onClick:()=>Ke.mutate({postId:Ie.id,reactionType:Ht.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Ht.label,children:Ht.emoji},Ht.type))})})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>Y(Ht=>{const dt=new Set(Ht);return dt.has(Ie.id)?dt.delete(Ie.id):dt.add(Ie.id),dt}),children:[e.jsx(tc,{className:"h-4 w-4 mr-1"}),(()=>{const Ht=Ft(Ie.comments);return Ht>0?`Comment (${Ht})`:"Comment"})()]})]}),Q.has(Ie.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[Ie.comments.map(Ht=>e.jsx(Vlt,{comment:Ht,postId:Ie.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:at(Ie)},Ht.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:a||void 0}),e.jsx(bn,{className:"text-xs",children:lt(((Jt=s.email)==null?void 0:Jt.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Whe,{placeholder:"Write a comment... (use @ to mention)",value:ne[Ie.id]||"",onChange:Ht=>de(dt=>({...dt,[Ie.id]:Ht})),onMentionsChange:Ht=>ae(dt=>({...dt,[Ie.id]:Ht})),mentionFormat:"plain",onKeyDown:Ht=>{var dt;Ht.defaultPrevented||Ht.key==="Enter"&&!Ht.shiftKey&&((dt=ne[Ie.id])!=null&&dt.trim())&&(Ht.preventDefault(),Ce.mutate({postId:Ie.id,content:ne[Ie.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{var Ht;(Ht=ne[Ie.id])!=null&&Ht.trim()&&Ce.mutate({postId:Ie.id,content:ne[Ie.id]})},disabled:!((cs=ne[Ie.id])!=null&&cs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Zr,{className:"h-4 w-4"})})]})]})]})]})},Ie.id)}),ze&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(G,{variant:"outline",onClick:()=>Te(),disabled:ye,children:ye?"Loading…":"Load more posts"})})]}),e.jsx(vs,{open:!!F,onOpenChange:()=>$(null),children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Edit Post"})}),e.jsx(ur,{value:X,onChange:Ie=>K(Ie.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>$(null),children:"Cancel"}),e.jsx(G,{onClick:()=>{F&&rt.mutate({postId:F.id,content:X})},disabled:!X.trim(),children:"Save Changes"})]})]})}),e.jsx(HJt,{images:be.images,initialIndex:be.index,open:be.open,onOpenChange:Ie=>Oe(et=>({...et,open:Ie}))})]})]})})},YJt=50*1024*1024;function Hlt({value:s,onChange:t,disabled:r}){const{user:n}=As(),a=k.useRef(null),[i,l]=k.useState(!1),o=async d=>{if(!d||!n)return;const h=[];l(!0);try{for(const m of Array.from(d)){if(!m.type.startsWith("image/")&&!m.type.startsWith("video/")){ue.error(`${m.name}: only images and videos allowed`);continue}if(m.size>YJt){ue.error(`${m.name}: must be under 50MB`);continue}const x=m.name.split(".").pop()||"bin",g=`${n.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${x}`,{error:v}=await H.storage.from("support-attachments").upload(g,m,{contentType:m.type,upsert:!1});if(v){ue.error(`${m.name}: ${v.message}`);continue}h.push({path:g,type:m.type,name:m.name,size:m.size})}h.length&&t([...s,...h])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const h=s[d];t(s.filter((m,x)=>x!==d)),await H.storage.from("support-attachments").remove([h.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,h)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(aO,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Qb,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(h),className:"text-muted-foreground hover:text-foreground",children:e.jsx(_r,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:r||i,className:"gap-1.5",children:[i?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Xj,{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 Glt({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 H.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,h)=>{d.signedUrl&&(c[l[h]]=d.signedUrl)}),r(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?n?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(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 VE={open:{label:"Open",icon:cn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:tc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:mi,color:"bg-green-500"},closed:{label:"Closed",icon:Mc,color:"bg-muted-foreground"}},Ize={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function ZJt(){const{user:s}=As(),t=es(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),{data:c=[],isLoading:d}=gt({queryKey:["support-tickets"],queryFn:async()=>{const{data:g,error:v}=await H.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(v)throw v;return g},enabled:!!s}),{data:h=[]}=gt({queryKey:["ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:g,error:v}=await H.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(v)throw v;return g},enabled:!!r}),m=Lt({mutationFn:async({content:g,attachments:v})=>{if(!r||!s)throw new Error("Missing data");const{error:j}=await H.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:g,is_admin_reply:!1,attachments:v});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",r==null?void 0:r.id]}),i(""),o([]),ue.success("Reply sent!")},onError:()=>{ue.error("Failed to send reply")}}),x=()=>{!a.trim()&&l.length===0||m.mutate({content:a,attachments:l})};if(r){const g=VE[r.status].icon;return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",children:Ize[r.category]}),e.jsxs(Ge,{className:VE[r.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),VE[r.status].label]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(Nr,{children:["Created on ",Ss(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(ti,{className:"h-[300px] pr-4",children:h.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:h.map(v=>{var j;return e.jsxs("div",{className:`p-4 rounded-lg ${v.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:v.is_admin_reply?"Support Team":((j=v.profiles)==null?void 0:j.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(v.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content}),v.attachments&&v.attachments.length>0&&e.jsx(Glt,{attachments:v.attachments})]},v.id)})})}),r.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Type your reply...",value:a,onChange:v=>i(v.target.value),className:"min-h-[80px]"}),e.jsx(G,{onClick:x,disabled:!a.trim()&&l.length===0||m.isPending,className:"self-end",children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsx(Hlt,{value:l,onChange:o,disabled:m.isPending})]})]})]})]})]})})}return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(De,{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(Ab,{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(W2e,{trigger:e.jsxs(G,{size:"lg",className:"gap-2",children:[e.jsx(Ws,{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(Nn,{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(W2e,{trigger:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Ws,{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(Ne,{className:"border-dashed",children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(tc,{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(g=>{const v=VE[g.status].icon;return e.jsx(Ne,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(g),children:e.jsx(De,{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:g.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"outline",className:"text-xs",children:Ize[g.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(g.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Ge,{className:VE[g.status].color,children:[e.jsx(v,{className:"h-3 w-3 mr-1"}),VE[g.status].label]})]})})},g.id)})})]})})}function XJt({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(js,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(rn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule Agent Onboarding"}),e.jsx(Fr,{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 QJt({open:s,onOpenChange:t}){const{brokerageId:r}=As(),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(!1),{data:d,isLoading:h}=gt({queryKey:["brokerage-agents-for-onboarding",r],queryFn:async()=>{if(!r)return[];const{data:j,error:b}=await H.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name",{ascending:!0});if(b)throw b;return j},enabled:s&&!!r}),m=d==null?void 0:d.filter(j=>j.name.toLowerCase().includes(n.toLowerCase())||j.email.toLowerCase().includes(n.toLowerCase())),x=j=>{l(b=>b.includes(j)?b.filter(N=>N!==j):[...b,j])},g=async()=>{if(i.length===0){ue.error("Please select at least one agent");return}c(!0);try{const{data:j,error:b}=await H.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(b)throw b;ue.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(j){console.error("Error sending onboarding link:",j),ue.error(j.message||"Failed to send onboarding link")}finally{c(!1)}},v=j=>{j||(l([]),a("")),t(j)};return e.jsx(vs,{open:s,onOpenChange:v,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Zr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Send Onboarding Link"}),e.jsx(Fr,{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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents...",value:n,onChange:j=>a(j.target.value),className:"pl-10"})]}),h?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(fr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(ti,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:m==null?void 0:m.map(j=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>x(j.id),children:[e.jsx(Ei,{checked:i.includes(j.id),onCheckedChange:()=>x(j.id)}),e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{className:"text-xs",children:j.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:j.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:j.email})]})]},j.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(G,{onClick:g,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(Zr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function JJt(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"mb-8",children:[e.jsx(Ot,{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(fr,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{children:"Agent Onboarding"}),e.jsx(Nr,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(De,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(G,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(G,{variant:"outline",onClick:()=>n(!0),className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(XJt,{open:s,onOpenChange:t}),e.jsx(QJt,{open:r,onOpenChange:n})]})}function ees({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(js,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Gv,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule Launch Meeting"}),e.jsx(Fr,{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 tes(){const[s,t]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"mb-8",children:[e.jsx(Ot,{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(Gv,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Nr,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),e.jsx(De,{children:e.jsxs(G,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Gv,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(ees,{open:s,onOpenChange:t})]})}function ses(){const s=vr(),[t,r]=k.useState(""),[n,a]=k.useState(null),{data:i,isLoading:l}=gt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:j,error:b}=await H.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(b)throw b;return j}}),{data:o}=gt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:j,error:b}=await H.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(b)throw b;return j}}),{data:c}=gt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:j,error:b}=await H.from("brokerage_resource_pdfs").select("resource_id");if(b)throw b;return j}}),{data:d}=gt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:j,error:b}=await H.from("brokerage_resource_videos").select("resource_id");if(b)throw b;return j}}),{data:h}=gt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:j,error:b}=await H.from("brokerage_resource_links").select("resource_id");if(b)throw b;return j}}),m=i==null?void 0:i.filter(j=>{var S;const b=j.title.toLowerCase().includes(t.toLowerCase())||((S=j.description)==null?void 0:S.toLowerCase().includes(t.toLowerCase())),N=!n||j.category_id===n;return b&&N}),x=o==null?void 0:o.filter(j=>i==null?void 0:i.some(b=>b.category_id===j.id)),g=j=>{const b=(c==null?void 0:c.filter(T=>T.resource_id===j).length)||0,N=(d==null?void 0:d.filter(T=>T.resource_id===j).length)||0,S=(h==null?void 0:h.filter(T=>T.resource_id===j).length)||0;return{pdfCount:b,videoCount:N,linkCount:S}},v=j=>{s(`/brokerage-resources/${j}`)};return e.jsx(_s,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(JJt,{}),e.jsx(tes,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search resources...",value:t,onChange:j=>r(j.target.value),className:"pl-10"})]}),x&&x.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ge,{variant:n===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),x.map(j=>e.jsx(Ge,{variant:n===j.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(j.id),children:j.name},j.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((j,b)=>e.jsxs(Ne,{children:[e.jsx(Vs,{className:"h-40 w-full"}),e.jsx(Ot,{children:e.jsx(Vs,{className:"h-5 w-3/4"})}),e.jsxs(De,{children:[e.jsx(Vs,{className:"h-4 w-full mb-2"}),e.jsx(Vs,{className:"h-4 w-2/3"})]})]},b))}):(m==null?void 0:m.length)===0?e.jsxs(Ne,{className:"p-12 text-center",children:[e.jsx(Yu,{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(j=>{const{pdfCount:b,videoCount:N,linkCount:S}=g(j.id),T=o==null?void 0:o.find(A=>A.id===j.category_id);return e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>v(j.id),children:[j.preview_image_url?e.jsx("img",{src:j.preview_image_url,alt:j.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(Yu,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(zt,{className:"text-lg line-clamp-1",children:j.title}),T&&e.jsx(Ge,{variant:"secondary",className:"shrink-0 text-xs",children:T.name})]})}),e.jsxs(De,{children:[j.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:j.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4"}),b]}),N>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sn,{className:"h-4 w-4"}),N]}),S>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xo,{className:"h-4 w-4"}),S]})]})]})]},j.id)})})]})})}const res=()=>{const{resourceId:s}=Xi(),{data:t,isLoading:r}=gt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await H.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await H.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await H.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await H.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(_s,{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(_s,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/brokerage-resources",children:[e.jsx(wa,{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(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(sn,{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(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Documents (",t.pdfs.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.pdfs.map(a=>e.jsxs("a",{href:a.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ln,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:n(a.file_size)})]})]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Yr,{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(Yr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(_s,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yu,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function nes(){const{onlineUsers:s,totalOnline:t}=aQe();return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Ge,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Bd,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(De,{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(ti,{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(vn,{className:"h-9 w-9",children:[e.jsx(ga,{src:r.avatarUrl,alt:r.name}),e.jsx(bn,{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 ",al(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const Pze={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:fr,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:LO,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:gx,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:tO,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:Ah,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Pc,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:fr,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:zd,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:nl,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:Zi,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Manage Templates",description:"Upload and organize Canva templates",icon:pl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Od,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:i0,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:jr,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:jr,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:Vv,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:pd,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Yu,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Yu,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:Qs,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:Cu,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:A3,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:bg,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Qs,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:Cu,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:JA,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:Kv,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:li,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:Zi,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:rl,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:fr,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:Cu,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:bi,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:oM,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:Yj,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Qn,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Qs,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:ao,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:Th,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:Od,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:hi,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:Cn,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:n0,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:Th,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:fl,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:Qs,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:Hj,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:gc,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:sO,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:_o,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:ln,path:"/admin/website-interests",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Website Order Tracker",description:"Full setup requests with all build details from /get-started",icon:ln,path:"/admin/website-orders",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"MLS Fee Tracker",description:"Track MLS providers, setup fees, and monthly costs",icon:_l,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Lze(){const s=vr();return console.log("[AdminDashboard] render"),e.jsx(_s,{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(nes,{})})]}),e.jsxs(Rn,{defaultValue:"users",className:"w-full",children:[e.jsx(Dn,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Pze).map(([t,r])=>e.jsx(Xt,{value:t,className:"data-[state=active]:bg-background",children:r.label},t))}),Object.entries(Pze).map(([t,r])=>e.jsx(as,{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(Ne,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(n.path),children:[e.jsxs(Ot,{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(zt,{className:"text-base",children:n.title})]}),e.jsx(De,{className:"pt-0",children:e.jsx(Nr,{className:"text-sm",children:n.description})})]},n.path))})},t))]})]})})}const On=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:r,className:Bt("w-full caption-bottom text-sm",s),...t})}));On.displayName="Table";const Fn=k.forwardRef(({className:s,...t},r)=>e.jsx("thead",{ref:r,className:Bt("[&_tr]:border-b",s),...t}));Fn.displayName="TableHeader";const Bn=k.forwardRef(({className:s,...t},r)=>e.jsx("tbody",{ref:r,className:Bt("[&_tr:last-child]:border-0",s),...t}));Bn.displayName="TableBody";const aes=k.forwardRef(({className:s,...t},r)=>e.jsx("tfoot",{ref:r,className:Bt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));aes.displayName="TableFooter";const qs=k.forwardRef(({className:s,...t},r)=>e.jsx("tr",{ref:r,className:Bt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));qs.displayName="TableRow";const Tt=k.forwardRef(({className:s,...t},r)=>e.jsx("th",{ref:r,className:Bt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Tt.displayName="TableHead";const ft=k.forwardRef(({className:s,...t},r)=>e.jsx("td",{ref:r,className:Bt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));ft.displayName="TableCell";const ies=k.forwardRef(({className:s,...t},r)=>e.jsx("caption",{ref:r,className:Bt("mt-4 text-sm text-muted-foreground",s),...t}));ies.displayName="TableCaption";const oes=()=>{const{isAdmin:s}=As(),t=vr(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s){t("/dashboard");return}h()},[s]);const h=async()=>{try{const{data:j,error:b}=await H.from("app_tiles").select("*").order("name");if(b)throw b;n(j||[])}catch(j){console.error("Error loading apps:",j),ue.error("Failed to load apps")}finally{i(!1)}},m=async j=>{j.preventDefault();const b=new FormData(j.currentTarget),N={name:b.get("name"),description:b.get("description"),icon:b.get("icon"),app_id:b.get("app_id"),target_url:b.get("target_url"),required_tags:b.get("required_tags").split(",").map(S=>S.trim()).filter(Boolean)};try{if(c){const{error:S}=await H.from("app_tiles").update(N).eq("id",c.id);if(S)throw S;ue.success("App updated successfully")}else{const{error:S}=await H.from("app_tiles").insert([N]);if(S)throw S;ue.success("App created successfully")}o(!1),d(null),h()}catch(S){console.error("Error saving app:",S),ue.error("Failed to save app")}},x=async j=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:b}=await H.from("app_tiles").delete().eq("id",j);if(b)throw b;ue.success("App deleted successfully"),h()}catch(b){console.error("Error deleting app:",b),ue.error("Failed to delete app")}},g=j=>{d(j),o(!0)},v=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(wa,{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(Ni,{asChild:!0,children:e.jsxs(G,{onClick:v,children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(bs,{children:c?"Edit App":"Create New App"}),e.jsx(Fr,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"App Name"}),e.jsx(ke,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"app_id",children:"App ID"}),e.jsx(ke,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",name:"description",defaultValue:c==null?void 0:c.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(ke,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"target_url",children:"Target URL"}),e.jsx(ke,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(ke,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Application Tiles"}),e.jsx(Nr,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(De,{children:r.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(G,{onClick:v,children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"App ID"}),e.jsx(Tt,{children:"Target URL"}),e.jsx(Tt,{children:"Tags"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:r.map(j=>e.jsxs(qs,{children:[e.jsx(ft,{className:"text-2xl",children:j.icon}),e.jsx(ft,{className:"font-medium",children:j.name}),e.jsx(ft,{className:"font-mono text-sm",children:j.app_id}),e.jsx(ft,{className:"text-sm text-muted-foreground max-w-xs truncate",children:j.target_url}),e.jsx(ft,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:j.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(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>g(j),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(j.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},j.id))})]})})]})})]})};function rh({title:s,description:t,children:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Kn,{to:"/admin",children:e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(wa,{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 Dze=({expiresAt:s,className:t})=>{const r=new Date().getTime(),n=new Date(s).getTime(),a=Math.ceil((n-r)/(1e3*60*60*24));return a<=0?e.jsxs(Ge,{variant:"destructive",className:Bt("gap-1",t),children:[e.jsx(od,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Ge,{variant:"destructive",className:Bt("gap-1",t),children:[e.jsx(cn,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Ge,{className:Bt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(cn,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Ge,{variant:"secondary",className:Bt("gap-1",t),children:[e.jsx(cn,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},Wlt=({open:s,onOpenChange:t,brokerages:r,fixedBrokerageId:n,onSuccess:a})=>{const{toast:i}=Ea(),l=k.useRef(null),[o,c]=k.useState([]),[d,h]=k.useState(""),[m,x]=k.useState(!1),[g,v]=k.useState("upload"),[j,b]=k.useState(null),N=()=>{c([]),h(""),v("upload"),b(null),l.current&&(l.current.value="")},S=()=>{N(),t(!1)},T=z=>{const F=z.split(` `).map(Y=>Y.trim()).filter(Y=>Y);if(F.length===0)return[];const $=F[0].toLowerCase(),K=$.includes("first")||$.includes("last")||$.includes("email")||$.includes("name")||$.includes("phone")||$.includes("sms")||$.includes("consent")?F.slice(1):F,Q=[];for(const Y of K){const de=(Y.includes(" ")?Y.split(" "):Y.split(",")).map(ce=>ce.trim().replace(/^["']|["']$/g,""));if(de.length>=2){let ce="",ae="",ie="",me="",oe;if(de.length===2){const Oe=de[0].split(" ");ce=Oe[0]||"",ae=Oe.slice(1).join(" ")||"",ie=de[1]}else if(de.length===3)ce=de[0],ae=de[1],ie=de[2];else if(de.length===4)ce=de[0],ae=de[1],ie=de[2],me=de[3];else if(de.length>=5){ce=de[0],ae=de[1],ie=de[2],me=de[3];const Oe=de[4].toLowerCase();oe=Oe==="true"||Oe==="yes"||Oe==="1"||Oe==="y"}const be=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ie);Q.push({firstName:ce.trim(),lastName:ae.trim(),email:ie.trim().toLowerCase(),phone:me.trim()||void 0,smsConsent:oe,isValid:be&&ce.trim().length>0,error:be?ce.trim()?void 0:"Missing name":"Invalid email"})}}return Q},A=z=>{var X;const F=(X=z.target.files)==null?void 0:X[0];if(!F)return;const $=new FileReader;$.onload=K=>{var ne;const Q=(ne=K.target)==null?void 0:ne.result,Y=T(Q);if(Y.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(Y),v("preview")},$.readAsText(F)},P=async()=>{const z=o.filter($=>$.isValid);if(z.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const F=n||d||null;x(!0);try{const{data:{session:$}}=await H.auth.getSession(),X=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$==null?void 0:$.access_token}`},body:JSON.stringify({users:z.map(Q=>({firstName:Q.firstName,lastName:Q.lastName,email:Q.email,phone:Q.phone,smsConsent:Q.smsConsent})),brokerageId:F})}),K=await X.json();if(!X.ok)throw new Error(K.error||"Failed to import users");b(K),v("result"),K.created>0&&a(),i({title:"Import Complete",description:`${K.created} user(s) created successfully.${K.failed>0?` ${K.failed} failed.`:""}`})}catch($){console.error("Import error:",$),i({title:"Import Failed",description:$.message||"Failed to import users",variant:"destructive"})}finally{x(!1)}},D=o.filter(z=>z.isValid).length,B=o.filter(z=>!z.isValid).length;return e.jsx(vs,{open:s,onOpenChange:S,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Jb,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Fr,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),g==="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(oa,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(G,{onClick:()=>{var z;return(z=l.current)==null?void 0:z.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."})]})]}),g==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!n&&r&&r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Assign to Brokerage (optional)"}),e.jsxs(zs,{value:d||"none",onValueChange:z=>h(z==="none"?"":z),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a brokerage..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No brokerage"}),r.map(z=>e.jsx(mt,{value:z.id,children:z.name},z.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(Mn,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D," valid"]})]}),B>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Hi,{className:"h-4 w-4"}),e.jsxs("span",{children:[B," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"SMS"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Bn,{children:o.slice(0,100).map((z,F)=>e.jsxs(qs,{children:[e.jsx(ft,{children:z.firstName}),e.jsx(ft,{children:z.lastName}),e.jsx(ft,{children:z.email}),e.jsx(ft,{className:"text-muted-foreground",children:z.phone||"-"}),e.jsx(ft,{className:"text-muted-foreground",children:z.smsConsent===!0?"✓":z.smsConsent===!1?"✗":"-"}),e.jsx(ft,{children:z.isValid?e.jsx(Ge,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Ge,{variant:"destructive",children:z.error||"Invalid"})})]},F))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),g==="result"&&j&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Mn,{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:[j.created," agent(s) created and invited"]}),j.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[j.failed," failed to create"]})]}),j.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:[j.errors.slice(0,10).map((z,F)=>e.jsxs("li",{children:["• ",z]},F)),j.errors.length>10&&e.jsxs("li",{children:["...and ",j.errors.length-10," more"]})]})]})]}),e.jsxs(on,{children:[g==="upload"&&e.jsx(G,{variant:"outline",onClick:S,children:"Cancel"}),g==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:N,children:"Back"}),e.jsx(G,{onClick:P,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":""}`})]}),g==="result"&&e.jsx(G,{onClick:S,children:"Done"})]})]})})};function Al({sortKey:s,currentSortKey:t,currentDirection:r,onSort:n,children:a,className:i,...l}){const o=t===s;return e.jsx(Tt,{className:Bt("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(Fd,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Ku,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Rd,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function mz(s=null,t=null){const[r,n]=k.useState(s),[a,i]=k.useState(t),l=k.useCallback(c=>{r===c?a==="asc"?i("desc"):a==="desc"?(n(null),i(null)):i("asc"):(n(c),i("asc"))},[r,a]),o=k.useCallback((c,d)=>{if(!r||!a||!d[r])return c;const h=d[r];return[...c].sort((m,x)=>{const g=h(m),v=h(x);if(g==null&&v==null)return 0;if(g==null)return 1;if(v==null)return-1;let j;return typeof g=="string"&&typeof v=="string"?j=g.localeCompare(v,void 0,{sensitivity:"base"}):j=g-v,a==="asc"?j:-j})},[r,a]);return{sortKey:r,sortDirection:a,handleSort:l,sortData:o}}const les=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Qn},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:Zi},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:iu}];function Klt({open:s,onOpenChange:t,userId:r,userName:n}){const[a,i]=k.useState("custom"),[l,o]=k.useState(""),[c,d]=k.useState(""),h=jAt(),m=g=>{i(g.type),o(g.title),d(g.message)},x=async g=>{if(g.preventDefault(),!l.trim()){nn({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await h.mutateAsync({user_id:r,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),nn({title:"Celebration sent! 🎉",description:`${n} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{nn({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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(iu,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",n]}),e.jsx(Fr,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(he,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:les.map((g,v)=>e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>m(g),className:"text-xs",children:[e.jsx(g.icon,{className:"h-3 w-3 mr-1"}),g.title]},v))})]}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(zs,{value:a,onValueChange:g=>i(g),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-4 w-4"})," Custom"]})}),e.jsx(mt,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(mt,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(mt,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_l,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:l,onChange:g=>o(g.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"message",children:"Message (optional)"}),e.jsx(ur,{id:"message",value:c,onChange:g=>d(g.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:h.isPending,children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),h.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const Mbe={points_earned:{label:"Points Earned",icon:Zi,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Cn,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:_l,color:"bg-green-500"},custom:{label:"Custom",icon:jr,color:"bg-purple-500"}};function ces(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=gt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:h,error:m}=await H.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(m)throw m;const x=[...new Set([...h.map(j=>j.user_id),...h.map(j=>j.created_by).filter(Boolean)])],{data:g}=await H.from("profiles").select("id, name, email").in("id",x),v=new Map((g==null?void 0:g.map(j=>[j.id,j]))||[]);return h.map(j=>{var b,N,S;return{...j,user_name:((b=v.get(j.user_id))==null?void 0:b.name)||"Unknown",user_email:((N=v.get(j.user_id))==null?void 0:N.email)||"",creator_name:j.created_by?((S=v.get(j.created_by))==null?void 0:S.name)||"System":"Auto-triggered"}})}}),c=l.filter(h=>{var v,j;const m=((v=h.user_name)==null?void 0:v.toLowerCase().includes(s.toLowerCase()))||((j=h.user_email)==null?void 0:j.toLowerCase().includes(s.toLowerCase()))||h.title.toLowerCase().includes(s.toLowerCase()),x=r==="all"||h.celebration_type===r,g=a==="all"||a==="seen"&&h.seen_at||a==="unseen"&&!h.seen_at;return m&&x&&g}),d={total:l.length,seen:l.filter(h=>h.seen_at).length,unseen:l.filter(h=>!h.seen_at).length,byType:Object.keys(Mbe).reduce((h,m)=>(h[m]=l.filter(x=>x.celebration_type===m).length,h),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(iu,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Nr,{children:"View all celebrations awarded to agents"})]}),e.jsxs(De,{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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by agent name, email, or title...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),Object.entries(Mbe).map(([h,m])=>e.jsx(mt,{value:h,children:m.label},h))]})]}),e.jsxs(zs,{value:a,onValueChange:i,children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{placeholder:"Status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Status"}),e.jsx(mt,{value:"seen",children:"Seen"}),e.jsx(mt,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Points"}),e.jsx(Tt,{children:"Created By"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Bn,{children:c.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(h=>{const m=Mbe[h.celebration_type],x=m.icon;return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(x,{className:"h-3 w-3"}),m.label]})}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.user_email})]})}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.title}),h.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:h.message})]})}),e.jsx(ft,{children:h.points_amount?e.jsxs(Ge,{variant:"secondary",children:["+",h.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:h.creator_name})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(h.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(ft,{children:h.seen_at?e.jsx(Ge,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Ge,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},h.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const des=()=>{const{user:s}=As(),{toast:t}=Ea(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState("all"),[h,m]=k.useState("all"),[x,g]=k.useState("new"),[v,j]=k.useState(new Set),b=k.useCallback(async()=>{try{i(!0);const{data:Q,error:Y}=await H.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(Y)throw Y;const{data:ne,error:de}=await H.from("trial_email_exports").select("user_id");if(de)throw de;const ce=new Set((ne||[]).map(ie=>ie.user_id)),ae=(Q||[]).map(ie=>({...ie,converted_from_trial_at:ie.converted_from_trial_at??null,already_exported:ce.has(ie.id)}));ae.sort((ie,me)=>new Date(me.created_at).getTime()-new Date(ie.created_at).getTime()),n(ae)}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 N=Q=>Q.trial_started_at?"ghl":"stripe",S=Q=>Q.trial_expires_at?Q.trial_expires_at:Q.subscription_end_date?Q.subscription_end_date:null,T=Q=>Q.converted_from_trial_at!==null,A=Q=>{if(T(Q))return!1;const Y=S(Q);return Y?new Date(Y).getTime()<=Date.now():!1},P=r.filter(Q=>!(c!=="all"&&N(Q)!==c||h==="active"&&(A(Q)||T(Q))||h==="expired"&&!A(Q)||h==="converted"&&!T(Q)||x==="new"&&Q.already_exported||x==="exported"&&!Q.already_exported)),D=()=>{v.size===P.length?j(new Set):j(new Set(P.map(Q=>Q.id)))},B=Q=>{const Y=new Set(v);Y.has(Q)?Y.delete(Q):Y.add(Q),j(Y)},z=async()=>{if(v.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const Q=r.filter(oe=>v.has(oe.id)),Y="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",ne=Q.map(oe=>{const ge=(oe.name||"").split(" "),be=ge[0]||"",Oe=ge.slice(1).join(" ")||"",Me=N(oe)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Pe=T(oe)?"Converted":A(oe)?"Expired":"Active",Ee=oe.created_at?new Date(oe.created_at).toLocaleDateString():"",$e=S(oe)?new Date(S(oe)).toLocaleDateString():"";return`"${be}","${Oe}","${oe.email}","${oe.phone||""}","${Me}","${Pe}","${Ee}","${$e}"`}),de=[Y,...ne].join(` `),ce=new Blob([de],{type:"text/csv"}),ae=URL.createObjectURL(ce),ie=document.createElement("a");ie.href=ae,ie.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ie.click(),URL.revokeObjectURL(ae);const me=Q.filter(oe=>!oe.already_exported).map(oe=>({user_id:oe.id,exported_by:s.id}));if(me.length>0){const{error:oe}=await H.from("trial_email_exports").upsert(me,{onConflict:"user_id"});oe&&console.error("Error marking exports:",oe)}t({title:"Export complete",description:`Downloaded ${Q.length} trial user(s). ${me.length} newly marked as exported.`}),j(new Set),b()}catch(Q){console.error("Export error:",Q),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},F=r.filter(Q=>!Q.already_exported).length,$=r.filter(Q=>Q.already_exported).length,X=r.filter(Q=>T(Q)).length,K=r.filter(Q=>!A(Q)&&!T(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(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Total"}),e.jsx(zt,{className:"text-2xl",children:r.length})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"New (Not Exported)"}),e.jsx(zt,{className:"text-2xl text-green-600",children:F})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Active Trials"}),e.jsx(zt,{className:"text-2xl",children:K})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Converted 🎉"}),e.jsx(zt,{className:"text-2xl text-primary",children:X})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Already Exported"}),e.jsx(zt,{className:"text-2xl text-muted-foreground",children:$})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(zs,{value:x,onValueChange:Q=>g(Q),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Users"}),e.jsx(mt,{value:"new",children:"New Only"}),e.jsx(mt,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(zs,{value:c,onValueChange:Q=>d(Q),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Trial Types"}),e.jsx(mt,{value:"stripe",children:"Credit Card Trial"}),e.jsx(mt,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(zs,{value:h,onValueChange:Q=>m(Q),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Statuses"}),e.jsx(mt,{value:"active",children:"Active Trial"}),e.jsx(mt,{value:"expired",children:"Expired"}),e.jsx(mt,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(G,{onClick:z,disabled:l||v.size===0,children:[l?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Export Selected (",v.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(Ei,{checked:P.length>0&&v.size===P.length,onCheckedChange:D})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Trial Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Last Login"}),e.jsx(Tt,{children:"Expires / Renews"}),e.jsx(Tt,{children:"Exported"})]})}),e.jsx(Bn,{children:P.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):P.map(Q=>{const Y=N(Q),ne=T(Q),de=A(Q),ce=S(Q);return e.jsxs(qs,{className:`hover:bg-muted/30 ${ne?"bg-primary/5":""}`,children:[e.jsx(ft,{children:e.jsx(Ei,{checked:v.has(Q.id),onCheckedChange:()=>B(Q.id)})}),e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Q.name,ne&&e.jsx(_o,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(ft,{className:"text-muted-foreground",children:Q.email}),e.jsx(ft,{children:Y==="stripe"?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(gx,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Qs,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(ft,{children:ne?e.jsxs(Ge,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(_o,{className:"h-3 w-3"}),"Converted"]}):de?e.jsx(Ge,{variant:"destructive",children:"Expired"}):e.jsx(Ge,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(ft,{className:"text-sm",children:Q.created_at?new Date(Q.created_at).toLocaleDateString():"—"}),e.jsx(ft,{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(ft,{className:"text-sm",children:ne&&ce?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ce).toLocaleDateString()]}):ce?new Date(ce).toLocaleDateString():"—"}),e.jsx(ft,{children:Q.already_exported?e.jsx(Mn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ge,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},Q.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",P.length," of ",r.length," trial users · ",X," converted to paid"]})]})},ues=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0);return k.useEffect(()=>{(async()=>{const{data:i,error:l}=await H.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!l&&i&&t(i),n(!1)})()},[]),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yr,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"User Deletion History"})}),e.jsx(De,{children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Deleted By"})]})}),e.jsx(Bn,{children:s.map(a=>e.jsxs(qs,{children:[e.jsx(ft,{className:"whitespace-nowrap text-sm",children:Ss(new Date(a.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ft,{className:"font-medium",children:a.deleted_user_name||"—"}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:a.deleted_user_email||"—"}),e.jsx(ft,{children:a.brokerage_name||"—"}),e.jsx(ft,{children:e.jsx(Ge,{variant:a.deletion_type==="deleted"?"destructive":"secondary",children:a.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(ft,{className:"text-sm",children:a.deleted_by_name||a.deleted_by_email||"—"})]},a.id))})]})})]})},Z5=s=>{const{user:t}=As(),r=es(),n=gt({queryKey:["teams",s],queryFn:async()=>{let m=H.from("teams").select("*").order("created_at",{ascending:!1});s&&(m=m.eq("brokerage_id",s));const{data:x,error:g}=await m;if(g)throw g;return x||[]},enabled:!!t}),a=m=>gt({queryKey:["team-members",m],queryFn:async()=>{const{data:x,error:g}=await H.from("team_members").select("*").eq("team_id",m).order("role",{ascending:!0});if(g)throw g;const v=(x||[]).map(N=>N.user_id),{data:j}=await H.from("profiles").select("id, name, email, avatar_url").in("id",v),b=new Map((j||[]).map(N=>[N.id,N]));return(x||[]).map(N=>({...N,profile:b.get(N.user_id)||null}))},enabled:!!m}),i=Lt({mutationFn:async m=>{const x={name:m.name,created_by:t.id,description:m.description,contact_visibility:m.contact_visibility,lead_pond_enabled:m.lead_pond_enabled,shared_assets_enabled:m.shared_assets_enabled};m.brokerage_id&&(x.brokerage_id=m.brokerage_id);const{data:g,error:v}=await H.from("teams").insert(x).select().single();if(v)throw v;return g},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team created!")},onError:m=>{ue.error("Failed to create team: "+m.message)}}),l=Lt({mutationFn:async({id:m,...x})=>{const{data:g,error:v}=await H.from("teams").update(x).eq("id",m).select().single();if(v)throw v;return g},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team updated")},onError:m=>{ue.error("Failed to update team: "+m.message)}}),o=Lt({mutationFn:async m=>{const{error:x}=await H.from("teams").delete().eq("id",m);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team deleted")},onError:m=>{ue.error("Failed to delete team: "+m.message)}}),c=Lt({mutationFn:async m=>{const{data:x,error:g}=await H.from("team_members").insert({team_id:m.team_id,user_id:m.user_id,role:m.role||"team_member"}).select().single();if(g)throw g.message.includes("duplicate")||g.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):g;return x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member added to team")},onError:m=>{ue.error(m.message)}}),d=Lt({mutationFn:async m=>{const{error:x}=await H.from("team_members").delete().eq("id",m.member_id);if(x)throw x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member removed from team")},onError:m=>{ue.error("Failed to remove member: "+m.message)}}),h=Lt({mutationFn:async m=>{const{error:x}=await H.from("team_members").update({role:m.role}).eq("id",m.member_id);if(x)throw x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member role updated")},onError:m=>{ue.error("Failed to update role: "+m.message)}});return{teams:n.data||[],isLoading:n.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:h,useTeamMembers:a}},hes=()=>{const{user:s}=As();return gt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.rpc("get_team_contacts",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},Ylt=s=>{const{user:t}=As(),r=es(),n=gt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await H.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(N=>N.contact_id),h=[...new Set(o.map(N=>N.added_by))],m=o.filter(N=>N.claimed_by).map(N=>N.claimed_by),x=[...new Set([...h,...m])],[g,v]=await Promise.all([H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),H.from("profiles").select("id, name, avatar_url").in("id",x)]),j=new Map((g.data||[]).map(N=>[N.id,N])),b=new Map((v.data||[]).map(N=>[N.id,N]));return o.map(N=>({...N,status:N.claimed_by?"claimed":"available",contact:j.get(N.contact_id)||null,contributor:b.get(N.added_by)||null,claimer:N.claimed_by&&b.get(N.claimed_by)||null}))},enabled:!!s&&!!t}),a=Lt({mutationFn:async o=>{const{data:c,error:d}=await H.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Contact added to Lead Pond")},onError:o=>{ue.error(o.message)}}),i=Lt({mutationFn:async o=>{const{error:c}=await H.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Lead claimed!")},onError:o=>{ue.error(o.message)}}),l=Lt({mutationFn:async o=>{const{error:c}=await H.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Lead returned to pond")},onError:o=>{ue.error(o.message)}});return{leadPondItems:n.data||[],isLoading:n.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},mes=()=>{const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(n)throw n;const a=r;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ue.success("Contact transferred successfully")},onError:t=>{ue.error(t.message||"Failed to transfer contact")}})};function Zlt({open:s,onOpenChange:t,contactIds:r,contactNames:n=[],onComplete:a}){var P;const{user:i}=As(),{data:l}=Xg(),{useTeamMembers:o}=Z5(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=mes(),[h,m]=k.useState(null),[x,g]=k.useState(""),[v,j]=k.useState(!1),b=c.filter(D=>D.user_id!==(i==null?void 0:i.id)),N=async()=>{if(h){j(!0);try{for(const D of r)await d.mutateAsync({contactId:D,toUserId:h,notes:x||void 0});t(!1),m(null),g(""),a==null||a()}catch{}finally{j(!1)}}},S=b.find(D=>D.user_id===h),T=r.length>1,A=n.length>0?T?`${n.length} contacts`:n[0]:T?`${r.length} contacts`:"this contact";return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Xb,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Fr,{children:["Select a team member to transfer ",T?"these contacts":"this contact"," to. The contact will be removed from the current owner's CRM and added to the selected member's."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):b.map(D=>{var B,z,F;return e.jsxs("button",{onClick:()=>m(D.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${h===D.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:((B=D.profile)==null?void 0:B.avatar_url)||""}),e.jsx(bn,{className:"text-xs",children:(((z=D.profile)==null?void 0:z.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((F=D.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:D.role.replace("_"," ")})]})]},D.user_id)})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(ur,{id:"transfer-notes",value:x,onChange:D=>g(D.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:N,disabled:!h||v,children:[v?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Xb,{className:"h-4 w-4 mr-2"}),"Transfer",S?` to ${(P=S.profile)==null?void 0:P.name}`:""]})]})]})})}const $Te=()=>{const s=vr(),{data:t,isLoading:r}=hes(),{data:n}=Xg(),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState(null),[h,m]=k.useState(""),x=(n==null?void 0:n.role)==="team_leader",g=k.useMemo(()=>{if(!t)return[];const j=new Map;return t.forEach(b=>{j.has(b.owner_user_id)||j.set(b.owner_user_id,{id:b.owner_user_id,name:b.owner_name||"Unknown",avatar:b.owner_avatar_url})}),Array.from(j.values())},[t]),v=k.useMemo(()=>{if(!t)return[];let j=t;if(l!=="all"&&(j=j.filter(b=>b.owner_user_id===l)),a.trim()){const b=a.toLowerCase();j=j.filter(N=>{var S,T,A;return(N.first_name+" "+(N.last_name||"")).toLowerCase().includes(b)||((S=N.email)==null?void 0:S.toLowerCase().includes(b))||((T=N.phone)==null?void 0:T.includes(b))||((A=N.owner_name)==null?void 0:A.toLowerCase().includes(b))})}return j},[t,a,l]);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{className:"h-10 w-full"}),e.jsx(Vs,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold 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(Ne,{children:e.jsx(De,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:j=>i(j.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Filter by agent"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Team Members"}),g.map(j=>e.jsx(mt,{value:j.id,children:j.name},j.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[v.length," contact",v.length!==1?"s":""," from ",g.length," teammate",g.length!==1?"s":""]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(On,{className:"min-w-[800px]",children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Address"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Date Added"}),x&&e.jsx(Tt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(Bn,{children:v.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:x?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):v.map(j=>e.jsxs(qs,{className:`hover:bg-accent/50 ${x?"cursor-pointer":""}`,onClick:x?()=>s(`/mission-control/contacts/${j.id}`):void 0,children:[e.jsx(ft,{className:"font-medium",children:e.jsxs("span",{className:x?"hover:text-primary hover:underline transition-colors":"",children:[j.first_name," ",j.last_name||""]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:j.owner_avatar_url||""}),e.jsx(bn,{className:"text-[10px]",children:(j.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:j.owner_name||"Unknown"})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[j.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Qs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:j.email})]}),j.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:j.phone})]}),!j.email&&!j.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(ft,{children:j.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ja,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:j.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ft,{children:j.lead_source?e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:j.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(j.created_at),"MMM d, yyyy")})}),x&&e.jsx(ft,{children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:b=>{b.stopPropagation(),d(j.id),m(`${j.first_name} ${j.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(Xb,{className:"h-4 w-4"})})})]},j.id))})]})})}),e.jsx(Zlt,{open:!!c,onOpenChange:j=>{j||d(null)},contactIds:c?[c]:[],contactNames:h?[h]:[],onComplete:()=>d(null)})]})},UTe=({teamId:s})=>{const{user:t}=As(),{leadPondItems:r,isLoading:n,claimLead:a,returnLead:i}=Ylt(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(Vs,{className:"h-20 w-full"},c))});if(r.length===0)return e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(t0,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Lead Pond is Empty"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team members can contribute contacts here for others to claim and follow up with."})]})});const l=r.filter(c=>c.status==="available"),o=r.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:l.map(c=>{var d,h,m,x,g,v,j;return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((m=c.contact)==null?void 0:m.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qs,{className:"h-3 w-3"})," ",c.contact.email]}),((x=c.contact)==null?void 0:x.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(vn,{className:"h-4 w-4",children:[e.jsx(ga,{src:((g=c.contributor)==null?void 0:g.avatar_url)||""}),e.jsx(bn,{className:"text-[8px]",children:(((v=c.contributor)==null?void 0:v.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((j=c.contributor)==null?void 0:j.name)||"Unknown"]})]})]}),e.jsxs(G,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(lO,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},c.id)})})]}),o.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",o.length,")"]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>{var d,h,m;return e.jsx(Ne,{className:"opacity-75",children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:["Claimed by ",((m=c.claimer)==null?void 0:m.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(Wv,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},Xlt=({teamId:s})=>{const{useTeamMembers:t}=Z5(),{data:r=[]}=t(s),n=r.map(g=>g.user_id),a=new Map(r.map(g=>[g.user_id,g.profile])),{data:i=[],isLoading:l}=gt({queryKey:["team-shared-presentations",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:g,error:v}=await H.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",n).neq("status","archived").order("created_at",{ascending:!1});if(v)throw v;return g||[]},enabled:n.length>0}),{data:o=[],isLoading:c}=gt({queryKey:["team-shared-open-houses",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:g,error:v}=await H.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",n).order("event_date",{ascending:!1});if(v)throw v;return g||[]},enabled:n.length>0}),{data:d=[],isLoading:h}=gt({queryKey:["team-shared-videos",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:g,error:v}=await H.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",n).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(v)throw v;return g||[]},enabled:n.length>0});if(l||c||h)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(Vs,{className:"h-20 w-full"},g))});const x=g=>{const v=a.get(g);return{name:(v==null?void 0:v.name)||"Unknown",avatar:(v==null?void 0:v.avatar_url)||"",initials:((v==null?void 0:v.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(n0,{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(Ne,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(Cn,{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(Ne,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(sn,{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(Rn,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Xt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Xt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(as,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(Ibe,{icon:e.jsx(n0,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(g=>{const v=x(g.owner_user_id);return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(vn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ga,{src:v.avatar}),e.jsx(bn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:g.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",Ss(new Date(g.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ge,{variant:g.status==="published"?"default":"secondary",className:"text-xs capitalize",children:g.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(jn,{className:"h-3 w-3"}),g.view_count||0]})]})]})},g.id)})}),e.jsx(as,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(Ibe,{icon:e.jsx(Cn,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(g=>{const v=x(g.agent_id);return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(vn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ga,{src:v.avatar}),e.jsx(bn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:g.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",Ss(new Date(g.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[g.is_active?e.jsx(Ge,{className:"text-xs",children:"Active"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(fr,{className:"h-3 w-3"}),g.visitor_count||0]})]})]})},g.id)})}),e.jsx(as,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(Ibe,{icon:e.jsx(sn,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(g=>{const v=x(g.owner_user_id);return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(vn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ga,{src:v.avatar}),e.jsx(bn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:g.title||g.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",Ss(new Date(g.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs capitalize",children:g.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(jn,{className:"h-3 w-3"}),g.view_count||0]})]})]})},g.id)})})]})]})},Ibe=({icon:s,label:t})=>e.jsx(Ne,{children:e.jsxs(De,{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})]})}),Qlt=({team:s,brokerageAgents:t,onBack:r,onUpdate:n,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var B,z;const{useTeamMembers:h}=Z5(),{data:m=[],isLoading:x}=h(s.id),[g,v]=k.useState(!1),[j,b]=k.useState(""),[N,S]=k.useState("team_member"),{data:T}=gt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:F}=await H.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),$=new Map;return(F||[]).forEach(X=>{var K;$.set(X.user_id,((K=X.teams)==null?void 0:K.name)||"another team")}),$}}),A=new Set(m.map(F=>F.user_id)),P=t.filter(F=>!A.has(F.id)),D=async()=>{j&&(await a(j,N),b(""),S("team_member"),v(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(G,{variant:"ghost",onClick:r,className:"mb-2",children:"← Back to Teams"}),e.jsxs(Rn,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"members",children:"Members"}),e.jsxs(Xt,{value:"contacts",children:[e.jsx(k3,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Xt,{value:"lead-pond",children:[e.jsx(t0,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Xt,{value:"shared-assets",children:[e.jsx(im,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(as,{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:g,onOpenChange:v,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(nl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add Team Member"}),e.jsxs(Fr,{children:["Select an agent from your brokerage to add to ",s.name,"."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Agent"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[j&&(((B=P.find(F=>F.id===j))==null?void 0:B.name)||((z=P.find(F=>F.id===j))==null?void 0:z.email))||"Select an agent",e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search agents..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:"No agents found."}),e.jsx(Rx,{children:P.map(F=>{const $=T==null?void 0:T.get(F.id);return e.jsxs(vf,{value:F.name||F.email||F.id,disabled:!!$,onSelect:()=>b(F.id),children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",j===F.id?"opacity-100":"opacity-0")}),F.name||F.email,$&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",$,")"]})]},F.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Role"}),e.jsxs(zs,{value:N,onValueChange:S,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"team_leader",children:"Team Leader"}),e.jsx(mt,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(G,{onClick:D,disabled:!j||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),x?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(F=>e.jsx(Vs,{className:"h-16 w-full"},F))}):m.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(fr,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:m.map(F=>{var $,X,K,Q,Y;return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:(($=F.profile)==null?void 0:$.avatar_url)||""}),e.jsx(bn,{children:(((X=F.profile)==null?void 0:X.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((K=F.profile)==null?void 0:K.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Q=F.profile)==null?void 0:Q.email})]}),F.role==="team_leader"?e.jsxs(Ge,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(nm,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ge,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(zs,{value:F.role,onValueChange:ne=>l(F.id,ne),children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"team_leader",children:"Team Leader"}),e.jsx(mt,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(OO,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Remove Member?"}),e.jsxs(Uo,{children:["Remove ",((Y=F.profile)==null?void 0:Y.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>i(F.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},F.id)})})]}),e.jsx(as,{value:"contacts",className:"space-y-4",children:e.jsx($Te,{})}),s.lead_pond_enabled&&e.jsx(as,{value:"lead-pond",className:"space-y-4",children:e.jsx(UTe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(as,{value:"shared-assets",className:"space-y-4",children:e.jsx(Xlt,{teamId:s.id})}),e.jsxs(as,{value:"settings",className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-lg",children:"Team Settings"}),e.jsx(Nr,{children:"Configure how this team operates."})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Team Name"}),e.jsx(ke,{defaultValue:s.name,onBlur:F=>{F.target.value!==s.name&&n({name:F.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{defaultValue:s.description||"",onBlur:F=>{F.target.value!==(s.description||"")&&n({description:F.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Contact Visibility"}),e.jsxs(zs,{defaultValue:s.contact_visibility,onValueChange:F=>n({contact_visibility:F}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(mt,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(mt,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls whether team leaders and members can view each other's contacts."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable a shared lead pool where leaders can drop leads for members to claim."})]}),e.jsx(br,{checked:s.lead_pond_enabled,onCheckedChange:F=>n({lead_pond_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Shared Assets"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow team members to access shared presentations, guest books, and videos."})]}),e.jsx(br,{checked:s.shared_assets_enabled,onCheckedChange:F=>n({shared_assets_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Shared Video Library"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let team members browse and use each other's videos from the Video Library."})]}),e.jsx(br,{checked:s.shared_videos_enabled??!1,onCheckedChange:F=>n({shared_videos_enabled:F})})]})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsxs(G,{variant:"destructive",size:"sm",children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Team?"}),e.jsxs(Uo,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>{o(),r()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},Jlt=({open:s,onOpenChange:t,onCreateTeam:r,isCreating:n,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=k.useState(1),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState([]),A=()=>{d(1),m(""),g(""),j(""),N(""),T([])},P=F=>{F||A(),t(F)},D=async()=>{const F=v&&v!=="none"?v:o||null;await r({name:h.trim(),description:x.trim()||void 0,brokerage_id:F,leaderId:b||void 0,memberIds:S.length>0?S:void 0}),A()},B=F=>{F!==b&&T($=>$.includes(F)?$.filter(X=>X!==F):[...$,F])},z=a.filter(F=>F.id!==b);return e.jsx(vs,{open:s,onOpenChange:P,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(bs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Fr,{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:Bt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Bt("h-1.5 flex-1 rounded-full transition-colors",c===2?"bg-primary":"bg-muted")})]})]}),e.jsx("div",{className:"overflow-y-auto flex-1 pr-1",children:c===1?e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(ke,{id:"team-name",value:h,onChange:F=>m(F.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"team-desc",children:"Description"}),e.jsx(ur,{id:"team-desc",value:x,onChange:F=>g(F.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Brokerage"}),e.jsxs(zs,{value:v,onValueChange:j,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"No brokerage (independent team)"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No brokerage (independent)"}),l.map(F=>e.jsx(mt,{value:F.id,children:F.name},F.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-1.5",children:[e.jsx(nm,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(zs,{value:b,onValueChange:F=>{N(F),T($=>$.filter(X=>X!==F))},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a team leader (optional)"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No leader for now"}),a.map(F=>e.jsx(mt,{value:F.id,children:F.name||F.email||"Unknown"},F.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-1.5",children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),"Initial Members",S.length>0&&e.jsxs(Ge,{variant:"secondary",className:"ml-1 text-xs",children:[S.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:z.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(fr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):z.map(F=>{const $=S.includes(F.id);return e.jsxs("button",{type:"button",className:Bt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",$&&"bg-primary/5"),onClick:()=>B(F.id),children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:F.avatar_url||""}),e.jsx(bn,{className:"text-xs",children:(F.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:F.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:F.email})]}),e.jsx("div",{className:Bt("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",$?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:$&&e.jsx(Hn,{className:"h-3 w-3"})})]},F.id)})})]})]})}),e.jsx(on,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>d(2),disabled:!h.trim(),children:["Next",e.jsx(Ga,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",onClick:()=>d(1),children:[e.jsx(wa,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(G,{onClick:D,disabled:n,children:n?"Creating…":"Create Team"})]})})]})})},fes=()=>{const{teams:s,isLoading:t,createTeam:r,updateTeam:n,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=Z5(),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,g]=k.useState(""),{data:v}=gt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:P,error:D}=await H.from("brokerages").select("id, name").order("name");if(D)throw D;return P||[]}}),{data:j}=gt({queryKey:["admin-team-member-info",s.map(P=>P.id).join(",")],queryFn:async()=>{var F;if(s.length===0)return{};const{data:P}=await H.from("team_members").select("team_id, user_id, role").in("team_id",s.map($=>$.id));if(!P)return{};const D=P.filter($=>$.role==="team_leader").map($=>$.user_id);let B={};if(D.length>0){const{data:$}=await H.from("profiles").select("id, name").in("id",D);$&&(B=Object.fromEntries($.map(X=>[X.id,{name:X.name}])))}const z={};for(const $ of s){const X=P.filter(Q=>Q.team_id===$.id),K=X.find(Q=>Q.role==="team_leader");z[$.id]={count:X.length,leaderName:K&&((F=B[K.user_id])==null?void 0:F.name)||null}}return z},enabled:s.length>0}),b=(h==null?void 0:h.brokerage_id)||null,{data:N}=gt({queryKey:["brokerage-agents-for-teams",b],queryFn:async()=>{let P=H.from("profiles").select("id, name, email, avatar_url").order("name");b&&(P=P.eq("brokerage_id",b));const{data:D,error:B}=await P;if(B)throw B;return D||[]},enabled:!!h}),S=Object.fromEntries((v||[]).map(P=>[P.id,P.name])),T=async P=>{const D=await r.mutateAsync({name:P.name,brokerage_id:P.brokerage_id||null,description:P.description});if(P.leaderId&&P.leaderId!=="none"&&await i.mutateAsync({team_id:D.id,user_id:P.leaderId,role:"team_leader"}),P.memberIds)for(const B of P.memberIds)await i.mutateAsync({team_id:D.id,user_id:B,role:"team_member"});d(!1)};if(h)return e.jsx(Qlt,{team:h,brokerageAgents:N||[],onBack:()=>m(null),onUpdate:P=>n.mutateAsync({id:h.id,...P}).then(D=>m(D)),onAddMember:(P,D)=>i.mutateAsync({team_id:h.id,user_id:P,role:D}),onRemoveMember:P=>l.mutateAsync({team_id:h.id,member_id:P}),onUpdateRole:(P,D)=>o.mutateAsync({team_id:h.id,member_id:P,role:D}),onDeleteTeam:()=>{a.mutate(h.id),m(null)},isUpdating:n.isPending,isAddingMember:i.isPending});const A=s.filter(P=>P.name.toLowerCase().includes(x.toLowerCase())||(P.description||"").toLowerCase().includes(x.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search teams...",value:x,onChange:P=>g(P.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[A.length," of ",s.length," teams"]})]}),e.jsxs(G,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(Jlt,{open:c,onOpenChange:d,onCreateTeam:T,isCreating:r.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:v,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Team Name"}),e.jsx(Tt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Tt,{className:"font-semibold",children:"Leader"}),e.jsx(Tt,{className:"font-semibold",children:"Members"}),e.jsx(Tt,{className:"font-semibold",children:"Visibility"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(Bn,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(P=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-32"})}),e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-24"})}),e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-28"})}),e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-12"})}),e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-20"})}),e.jsx(ft,{children:e.jsx(Vs,{className:"h-4 w-16"})})]},P))}):A.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:x?"No teams match your search":"No teams found. Create one to get started."})}):A.map(P=>{const D=j==null?void 0:j[P.id];return e.jsxs(qs,{className:"hover:bg-muted/30",children:[e.jsxs(ft,{children:[e.jsx("button",{onClick:()=>m(P),className:"text-primary hover:underline font-medium",children:P.name}),P.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:P.description})]}),e.jsx(ft,{children:P.brokerage_id?e.jsx("span",{className:"text-sm",children:S[P.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(ft,{children:D!=null&&D.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(nm,{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(ft,{children:e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(fr,{className:"h-3 w-3 mr-1"}),(D==null?void 0:D.count)??0]})}),e.jsx(ft,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Zu,{className:"h-3 w-3"}),P.contact_visibility.replace("_"," ")]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(P),title:"Edit team",children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${P.name}"? This cannot be undone.`)&&a.mutate(P.id)},title:"Delete team",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})})]},P.id)})})]})})]})};function Rze(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 pes({open:s,onOpenChange:t,recipients:r}){const{toast:n}=Ea(),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(!1),[b,N]=k.useState(!1),S=k.useMemo(()=>a.find(D=>D.id===c)||null,[a,c]);k.useEffect(()=>{s&&(o(!0),(async()=>{const D=new Date().toISOString(),{data:B,error:z}=await H.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);z?n({title:"Could not load events",description:z.message,variant:"destructive"}):i(B||[]),o(!1)})())},[s,n]);const T=k.useMemo(()=>r.filter(D=>D.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D.email)),[r]),A=()=>{if(!S){n({title:"Pick an event first",variant:"destructive"});return}if(T.length===0){n({title:"No valid recipient emails",variant:"destructive"});return}N(!0)},P=async()=>{if(S){N(!1),j(!0);try{const{data:{session:D}}=await H.auth.getSession(),B=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({event_id:S.id,recipients:T.map(X=>({email:X.email,name:X.name,user_id:X.id})),custom_subject:h.trim()||void 0,custom_intro:x.trim()||void 0})}),z=await B.json().catch(()=>({}));if(!B.ok)throw new Error((z==null?void 0:z.error)||"Failed to send event invite");const F=(z==null?void 0:z.sent)??0,$=(z==null?void 0:z.failed)??0;n({title:"Invites sent",description:`Sent: ${F}${$?` · Failed: ${$}`:""}`}),t(!1),g(""),m(""),d("")}catch(D){const B=D instanceof Error?D.message:"Send failed";n({title:"Send failed",description:B,variant:"destructive"})}finally{j(!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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Fr,{children:["Send a beautiful event invitation to ",T.length," selected member",T.length===1?"":"s",".",r.length!==T.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[r.length-T.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"event-select",children:"Event"}),l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(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(zs,{value:c,onValueChange:d,children:[e.jsx(Os,{id:"event-select",children:e.jsx(Us,{placeholder:"Pick an upcoming event..."})}),e.jsx(Fs,{children:a.map(D=>e.jsx(mt,{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:[Rze(D.event_date),!D.is_published&&" · (Draft)"]})]})},D.id))})]})]}),S&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(rn,{className:"h-4 w-4 text-primary"}),S.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Rze(S.event_date)}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:S.description})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(ke,{id:"subject",placeholder:S?`You're invited: ${S.title}`:"You're invited to...",value:h,onChange:D=>m(D.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(ur,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:x,onChange:D=>g(D.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",T.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[T.slice(0,30).map(D=>e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:D.name||D.email},D.id)),T.length>30&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["+",T.length-30," more"]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsx(G,{onClick:A,disabled:v||!c||T.length===0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send to ",T.length]})})]})]})}),e.jsx(Yo,{open:b,onOpenChange:N,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Send event invite?"}),e.jsx(Uo,{children:S?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',S.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[T.length," member",T.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsxs(Eo,{onClick:P,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const xes=()=>{const s=vr(),{user:t,isAdmin:r}=As(),{startImpersonation:n,isLoading:a}=ipe(),{toast:i}=Ea(),[l,o]=k.useState([]),[c,d]=k.useState([]),[h,m]=k.useState([]),[x,g]=k.useState({}),[v,j]=k.useState(!0),[b,N]=k.useState({}),[S,T]=k.useState(!1),[A,P]=k.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[D,B]=k.useState(!1),[z,F]=k.useState(""),[$,X]=k.useState(1),[K,Q]=k.useState(50),[Y,ne]=k.useState("all"),[de,ce]=k.useState("all"),[ae,ie]=k.useState("all"),[me,oe]=k.useState("all"),[ge,be]=k.useState("all"),[Oe,Me]=k.useState(!1),[Pe,Ee]=k.useState(!1),[$e,Se]=k.useState(!1),[ze,Te]=k.useState(null),[ye,ct]=k.useState(null),[ve,rt]=k.useState(!1),[Re,Qe]=k.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ke,Ce]=k.useState(null),[nt,$t]=k.useState(!1),[lt,it]=k.useState(""),[Nt,Ft]=k.useState(!1),[at,Ie]=k.useState(!1),[et,Dt]=k.useState(null),[Jt,cs]=k.useState(""),[Ht,dt]=k.useState(!1),[Qt,yt]=k.useState(!1),[ss,Is]=k.useState(null),[fs,ar]=k.useState(!1),[Er,Tr]=k.useState(!1),[Lr,$r]=k.useState(null),[kr,Sr]=k.useState(""),[hn,zn]=k.useState(!1),[Xs,Ur]=k.useState({email:"",name:"",password:"",phone:""}),[xn,us]=k.useState(!1),[pr,Hr]=k.useState(!1),[aa,Na]=k.useState(""),[Je,Fe]=k.useState(!1),[We,He]=k.useState(!1),[bt,ut]=k.useState(""),[kt,Gt]=k.useState(new Set),[Mt,Kt]=k.useState(!1),[Es,Ls]=k.useState(!1),[gr,qr]=k.useState(null),[Xr,Yn]=k.useState(!1),[Qr,$s]=k.useState(null),[Kr,In]=k.useState([]),[Ja,yo]=k.useState([]),[ra,ki]=k.useState(!1),[Qi,Po]=k.useState({});k.useEffect(()=>{!t||!r||(za(),jo())},[t,r]);const ci=async()=>{try{const{data:It,error:Gs}=await H.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Gs)throw Gs;const hr={};for(const gn of It??[])hr[gn.brokerage_id]||(hr[gn.brokerage_id]=[]),hr[gn.brokerage_id].push(gn.user_id);g(hr)}catch(It){console.error("Error loading brokerage manager assignments:",It)}},za=async()=>{try{j(!0);const{data:It,error:Gs}=await H.functions.invoke("get-user-details");if(Gs)throw Gs;const hr=It.users||[];o(hr),m(It.brokerages||[]),await ci();const gn=hr.filter(_n=>_n.roles.includes("assistant"));if(gn.length>0){const _n=gn.map(Gn=>Gn.id),{data:Aa}=await H.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",_n);if(Aa&&Aa.length>0){const Gn=[...new Set(Aa.map(Tp=>Tp.agent_id))],{data:yi}=await H.from("profiles").select("id, name, email").in("id",Gn),Fh={};for(const Tp of Aa){const Jr=yi==null?void 0:yi.find(Wa=>Wa.id===Tp.agent_id);Jr&&(Fh[Tp.assistant_id]={agent_name:Jr.name||"",agent_email:Jr.email||""})}Po(Fh)}}}catch(It){console.error("Error loading members:",It),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{j(!1)}},jo=async()=>{try{const{data:It,error:Gs}=await H.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Gs)throw Gs;d(It||[])}catch(It){console.error("Error loading apps:",It),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Pi=async It=>{if(!Re.name.trim()||!Re.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Re.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:hr}=await H.from("profiles").update({name:Re.name.trim(),email:Re.email.trim(),brokerage_id:Re.brokerage_id||null,phone:Re.phone.trim()||null}).eq("id",It);if(hr)throw hr;i({title:"Success",description:"Member details updated successfully"}),Te(null),za()}catch(hr){console.error("Error updating member:",hr),i({title:"Error",description:hr.message||"Failed to update member",variant:"destructive"})}},Lo=async It=>{try{const{data:{session:Gs}}=await H.auth.getSession(),hr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:It})}),gn=await hr.json();if(!hr.ok)throw new Error(gn.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Gs){console.error("Error resending welcome email:",Gs),i({title:"Error",description:Gs.message||"Failed to resend welcome email",variant:"destructive"})}},rc=async(It,Gs)=>{try{const{error:hr}=await H.functions.invoke("send-password-reset",{body:{email:It,redirectTo:window.location.origin}});if(hr)throw hr;i({title:"Password Reset Sent",description:`Password reset email sent to ${Gs}`})}catch(hr){console.error("Error sending password reset:",hr),i({title:"Error",description:hr.message||"Failed to send password reset email",variant:"destructive"})}},dr=async(It,Gs)=>{if(confirm(`Are you sure you want to delete ${Gs}? This action cannot be undone.`))try{const{data:{session:hr}}=await H.auth.getSession(),gn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hr==null?void 0:hr.access_token}`},body:JSON.stringify({userId:It})}),_n=await gn.json();if(!gn.ok)throw new Error(_n.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),za()}catch(hr){console.error("Error deleting user:",hr),i({title:"Error",description:hr.message||"Failed to delete user",variant:"destructive"})}},Jn=async()=>{if(!A.email||!A.name||!A.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(A.role==="brokerage_manager"&&!A.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}T(!0);try{const{data:{session:It}}=await H.auth.getSession(),Gs=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(A)}),hr=await Gs.json();if(!Gs.ok)throw new Error(hr.error||"Failed to create user");if(A.role&&A.role!=="user"&&hr.userId){const gn=A.role==="brokerage_manager"?A.brokerage_id:void 0;await uo(hr.userId,A.role,"add",gn)}i({title:"Success",description:`User ${A.email} created successfully`}),P({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),B(!1),za()}catch(It){console.error("Error creating user:",It),i({title:"Error",description:It.message||"Failed to create user",variant:"destructive"})}finally{T(!1)}},uo=async(It,Gs,hr,gn)=>{try{const{data:{session:_n}}=await H.auth.getSession(),Aa={userId:It,role:Gs,action:hr};if(Gs==="brokerage_manager"){if(!gn){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Aa.brokerageId=gn}const Gn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_n==null?void 0:_n.access_token}`},body:JSON.stringify(Aa)}),yi=await Gn.json();if(!Gn.ok)throw new Error(yi.error||"Failed to manage user role");i({title:"Success",description:`Role ${hr==="add"?"added":"removed"} successfully`}),za()}catch(_n){console.error("Error managing user role:",_n),i({title:"Error",description:_n.message||"Failed to manage user role",variant:"destructive"})}},ll=(It,Gs)=>Gs.length===0?!0:Gs.some(hr=>It.includes(hr)),Va=async(It,Gs,hr)=>{const gn=`${It}-${Gs.id}`;Ce(gn);try{if(hr){const _n=l.find(Gn=>Gn.id===It),Aa=Gs.required_tags.filter(Gn=>_n==null?void 0:_n.tags.includes(Gn));for(const Gn of Aa){const{error:yi}=await H.from("user_tags").delete().eq("user_id",It).eq("tag",Gn);if(yi)throw yi}i({title:"Access Removed",description:`Removed access to ${Gs.name}`})}else if(Gs.required_tags.length>0){const{error:_n}=await H.from("user_tags").insert({user_id:It,tag:Gs.required_tags[0]});if(_n)throw _n;i({title:"Access Granted",description:`Granted access to ${Gs.name}`})}await za()}catch(_n){console.error("Error toggling access:",_n),i({title:"Error",description:_n.message||"Failed to update access",variant:"destructive"})}finally{Ce(null)}},Dl=async()=>{const It=lt.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(h.find(hr=>hr.name.toLowerCase()===It.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}Ft(!0);try{const{error:hr}=await H.from("brokerages").insert({name:It});if(hr)throw hr;i({title:"Success",description:`Brokerage "${It}" created successfully`}),it(""),$t(!1),za()}catch(hr){console.error("Error creating brokerage:",hr),i({title:"Error",description:hr.message||"Failed to create brokerage",variant:"destructive"})}finally{Ft(!1)}},Wm=It=>{Dt(It),cs(It.name),Ie(!0)},Lf=()=>{Dt(null),cs(""),Ie(!1)},Gx=async()=>{if(!et)return;const It=Jt.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}dt(!0);try{const{error:Gs}=await H.from("brokerages").update({name:It}).eq("id",et.id);if(Gs)throw Gs;i({title:"Success",description:"Brokerage updated successfully"}),Lf(),za()}catch(Gs){console.error("Error updating brokerage:",Gs),i({title:"Error",description:Gs.message||"Failed to update brokerage",variant:"destructive"})}finally{dt(!1)}},j0=async(It,Gs)=>{var hr;if(!Gs||typeof Gs!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const gn={userId:It,role:"brokerage_manager",action:"add",brokerageId:Gs};console.debug("[assignManagerToBrokerage] payload",gn);const{data:{session:_n}}=await H.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_n==null?void 0:_n.access_token}`},body:JSON.stringify(gn)}),Gn=await Aa.json();if(!Aa.ok&&!((hr=Gn.error)!=null&&hr.includes("duplicate")))throw new Error(Gn.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await za()}catch(gn){console.error("Error assigning manager:",gn),i({title:"Error",description:gn.message||"Failed to assign manager",variant:"destructive"})}},F_=It=>{Is(It),yt(!0)},E1=async()=>{if(ss){ar(!0);try{const It=l.filter(gn=>gn.brokerage_id===ss.id),{data:{session:Gs}}=await H.auth.getSession();for(const gn of It){const _n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:gn.id})});if(!_n.ok){const Aa=await _n.json();console.error(`Failed to delete user ${gn.email}:`,Aa.error)}}const{error:hr}=await H.from("brokerages").delete().eq("id",ss.id);if(hr)throw hr;i({title:"Success",description:`Brokerage "${ss.name}" and ${It.length} member(s) deleted`}),yt(!1),Is(null),za()}catch(It){console.error("Error deleting brokerage:",It),i({title:"Error",description:It.message||"Failed to delete brokerage",variant:"destructive"})}finally{ar(!1)}}},Do=It=>{$r(It),Sr(""),Tr(!0)},vd=()=>{$r(null),Sr(""),Tr(!1)},iy=async It=>{try{const{error:Gs}=await H.from("profiles").update({brokerage_id:null}).eq("id",It);if(Gs)throw Gs;i({title:"Success",description:"User removed from brokerage"}),za()}catch(Gs){console.error("Error removing user from brokerage:",Gs),i({title:"Error",description:Gs.message||"Failed to remove user",variant:"destructive"})}},N0=async(It,Gs)=>{try{const{error:hr}=await H.from("profiles").update({brokerage_id:Gs}).eq("id",It);if(hr)throw hr;i({title:"Success",description:"User added to brokerage"}),za()}catch(hr){console.error("Error adding user to brokerage:",hr),i({title:"Error",description:hr.message||"Failed to add user",variant:"destructive"})}},Df=async()=>{if(!Lr||!Xs.email||!Xs.name||!Xs.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}us(!0);try{const{data:{session:It}}=await H.auth.getSession(),Gs=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({...Xs,brokerage_id:Lr.id,role:"user"})}),hr=await Gs.json();if(!Gs.ok)throw new Error(hr.error||"Failed to create agent");i({title:"Success",description:`Agent ${Xs.email} created successfully`}),Ur({email:"",name:"",password:"",phone:""}),zn(!1),za()}catch(It){console.error("Error creating agent:",It),i({title:"Error",description:It.message||"Failed to create agent",variant:"destructive"})}finally{us(!1)}},bd=It=>l.filter(Gs=>Gs.brokerage_id===It),iN=It=>{const Gs=bd(It);if(!kr)return Gs;const hr=kr.toLowerCase();return Gs.filter(gn=>gn.name.toLowerCase().includes(hr)||gn.email.toLowerCase().includes(hr))},oN=It=>l.filter(Gs=>Gs.brokerage_id!==It),A1=l.filter(It=>{var hr;if(z){const gn=z.toLowerCase();if(!(It.name.toLowerCase().includes(gn)||It.email.toLowerCase().includes(gn)||((hr=It.brokerage_name)==null?void 0:hr.toLowerCase().includes(gn))))return!1}if(Y==="claimed"&&!It.claimed||Y==="unclaimed"&&It.claimed||de!=="all"&&!It.roles.includes(de))return!1;const Gs=It.is_trial||It.subscription_status==="trialing";if(ae==="trial"&&!Gs||ae==="non-trial"&&Gs||me==="none"&&It.brokerage_id||me!=="all"&&me!=="none"&&It.brokerage_id!==me)return!1;if(ge!=="all"){if(!It.created_at)return!1;const gn=parseInt(ge,10),_n=Date.now()-gn*24*60*60*1e3;if(new Date(It.created_at).getTime()<_n)return!1}return!0}),{sortKey:oy,sortDirection:ly,handleSort:cy,sortData:Np}=mz("created_at","desc"),mm=Np(A1,{name:It=>{var Gs;return((Gs=It.name)==null?void 0:Gs.toLowerCase())||""},brokerage:It=>{var Gs;return((Gs=It.brokerage_name)==null?void 0:Gs.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}),Rf=mm.length,k0=K===0,du=k0?1:Math.ceil(Rf/K),Dc=k0?0:($-1)*K,fm=k0?Rf:Dc+K,Hd=mm.slice(Dc,fm),lN=It=>{F(It),X(1)},cN=It=>{Q(It),X(1)},dy=(It,Gs)=>{It(Gs),X(1)},kp=async(It,Gs)=>{Ee(!0);try{const hr=l.find(Gn=>Gn.id===It);if(!hr)return;const gn=hr.trial_expires_at?new Date(hr.trial_expires_at):new Date,_n=new Date(gn.getTime()+Gs*24*60*60*1e3),{error:Aa}=await H.from("profiles").update({trial_expires_at:_n.toISOString()}).eq("id",It);if(Aa)throw Aa;i({title:"Trial Extended",description:`Trial extended by ${Gs} days`}),za()}catch(hr){console.error("Error extending trial:",hr),i({title:"Error",description:hr.message||"Failed to extend trial",variant:"destructive"})}finally{Ee(!1)}},Sp=async It=>{Se(!0);try{const{error:Gs}=await H.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",It);if(Gs)throw Gs;i({title:"Account Converted",description:"User has been converted to a full account"}),za(),P1()}catch(Gs){console.error("Error converting trial:",Gs),i({title:"Error",description:Gs.message||"Failed to convert account",variant:"destructive"})}finally{Se(!1)}},[M1,I1]=k.useState(!1),oT=async(It,Gs)=>{if(confirm(`Revert this user to a ${Gs}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){I1(!0);try{const hr=new Date,gn=new Date(hr.getTime()+Gs*24*60*60*1e3),{error:_n}=await H.from("profiles").update({is_trial:!0,trial_started_at:hr.toISOString(),trial_expires_at:gn.toISOString(),trial_claimed_at:hr.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(_n)throw _n;i({title:"Reverted to Trial",description:`User is now on a ${Gs}-day free trial.`}),za()}catch(hr){console.error("Error reverting to trial:",hr),i({title:"Error",description:hr.message||"Failed to revert to trial",variant:"destructive"})}finally{I1(!1)}}},Cp=async It=>{ki(!0);try{const{data:Gs}=await H.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",It);if(Gs&&Gs.length>0){const gn=Gs.map(Aa=>Aa.assistant_id),{data:_n}=await H.from("profiles").select("id, name, email").in("id",gn);In(Gs.map(Aa=>{const Gn=_n==null?void 0:_n.find(yi=>yi.id===Aa.assistant_id);return{id:Aa.id,assistant_id:Aa.assistant_id,assistant_name:(Gn==null?void 0:Gn.name)||"Unknown",assistant_email:(Gn==null?void 0:Gn.email)||"",permissions:Aa.permissions||{}}}))}else In([]);const{data:hr}=await H.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",It);if(hr&&hr.length>0){const gn=hr.map(Aa=>Aa.agent_id),{data:_n}=await H.from("profiles").select("id, name, email").in("id",gn);yo(hr.map(Aa=>{const Gn=_n==null?void 0:_n.find(yi=>yi.id===Aa.agent_id);return{id:Aa.id,agent_id:Aa.agent_id,agent_name:(Gn==null?void 0:Gn.name)||"Unknown",agent_email:(Gn==null?void 0:Gn.email)||"",permissions:Aa.permissions||{}}}))}else yo([])}catch(Gs){console.error("Error loading assistant data:",Gs)}finally{ki(!1)}},S0=It=>{ct(It),Qe({name:It.name,email:It.email,brokerage_id:It.brokerage_id||"",phone:It.phone||""}),rt(!0),Cp(It.id)},P1=()=>{ct(null),rt(!1),Qe({name:"",email:"",brokerage_id:"",phone:""})},C0=async()=>{ye&&(await Pi(ye.id),P1())},yL=It=>{Gt(Gs=>{const hr=new Set(Gs);return hr.has(It)?hr.delete(It):hr.add(It),hr})},B_=()=>{if(kt.size===Hd.length&&Hd.every(It=>kt.has(It.id))){const It=new Set(kt);Hd.forEach(Gs=>It.delete(Gs.id)),Gt(It)}else{const It=new Set(kt);Hd.forEach(Gs=>It.add(Gs.id)),Gt(It)}},Gd=()=>{Gt(new Set)},dN=async()=>{if(kt.size===0)return;Kt(!0);let It=0,Gs=0;try{const{data:{session:hr}}=await H.auth.getSession();for(const gn of kt)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hr==null?void 0:hr.access_token}`},body:JSON.stringify({userId:gn})})).ok?It++:Gs++}catch{Gs++}i({title:"Bulk Email Complete",description:`Sent ${It} emails${Gs>0?`, ${Gs} failed`:""}`}),Gd()}catch(hr){i({title:"Error",description:hr.message||"Failed to send emails",variant:"destructive"})}finally{Kt(!1)}},z_=async()=>{if(kt.size===0)return;Kt(!0);let It=0,Gs=0;try{const{data:{session:hr}}=await H.auth.getSession();for(const gn of kt)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hr==null?void 0:hr.access_token}`},body:JSON.stringify({userId:gn})})).ok?It++:Gs++}catch{Gs++}i({title:"Bulk Password Reset Complete",description:`Sent ${It} reset emails${Gs>0?`, ${Gs} failed`:""}`}),Gd()}catch(hr){i({title:"Error",description:hr.message||"Failed to send password reset emails",variant:"destructive"})}finally{Kt(!1)}},Wx=async()=>{if(kt.size===0)return;const It=l.filter(_n=>kt.has(_n.id)).map(_n=>_n.name).slice(0,5).join(", "),Gs=kt.size>5?` and ${kt.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${kt.size} users (${It}${Gs})? This action cannot be undone.`))return;Kt(!0);let hr=0,gn=0;try{const{data:{session:_n}}=await H.auth.getSession();for(const Aa of kt)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_n==null?void 0:_n.access_token}`},body:JSON.stringify({userId:Aa})})).ok?hr++:gn++}catch{gn++}i({title:"Bulk Delete Complete",description:`Deleted ${hr} users${gn>0?`, ${gn} failed`:""}`}),Gd(),za()}catch(_n){i({title:"Error",description:_n.message||"Failed to delete users",variant:"destructive"})}finally{Kt(!1)}},L1=async()=>{Ls(!0);try{const{data:{session:It}}=await H.auth.getSession(),Gs=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(!Gs.ok){const gn=await Gs.json();throw new Error(gn.error||"Failed to sync phones")}const hr=await Gs.json();i({title:"Phone Sync Complete",description:`Pulled ${hr.summary.pulledFromGHL} from GHL, pushed ${hr.summary.pushedToGHL} to GHL, ${hr.summary.alreadySynced} already synced`}),za()}catch(It){i({title:"Error",description:It.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Ls(!1)}},T0=async(It,Gs)=>{qr(It);try{const{data:{session:hr}}=await H.auth.getSession(),{data:gn}=await H.from("profiles").select("phone").eq("id",It).single(),_n=(gn==null?void 0:gn.phone)||"",Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hr==null?void 0:hr.access_token}`},body:JSON.stringify({email:Gs,action:"update",phone:_n||void 0})});if(!Aa.ok){const yi=await Aa.json();throw new Error(yi.error||"Failed to sync with GHL")}const Gn=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Gs)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:_n?`Phone ${_n} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),za()}catch(hr){i({title:"Error",description:hr.message||"Failed to sync phone",variant:"destructive"})}finally{qr(null)}},$_=async It=>{await n(It)},lT=()=>{if(kt.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const It=l.filter(yi=>kt.has(yi.id)),Gs=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],hr=It.map(yi=>[yi.name,yi.email,yi.phone||"",yi.brokerage_name||"",yi.roles.join("; "),yi.claimed?"Claimed":"Unclaimed",new Date(yi.created_at).toLocaleDateString()]),gn=[Gs.join(","),...hr.map(yi=>yi.map(Fh=>`"${(Fh||"").replace(/"/g,'""')}"`).join(","))].join(` `),_n=new Blob([gn],{type:"text/csv"}),Aa=URL.createObjectURL(_n),Gn=document.createElement("a");Gn.href=Aa,Gn.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Gn.click(),URL.revokeObjectURL(Aa),i({title:"Export complete",description:`Exported ${It.length} member(s)`})},cT=()=>{if(A1.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"],Gs=A1.map(yi=>[yi.name,yi.email,yi.phone||"",yi.brokerage_name||"",yi.roles.join("; "),yi.claimed?"Claimed":"Unclaimed",yi.created_at?new Date(yi.created_at).toLocaleDateString():""]),hr=[It.join(","),...Gs.map(yi=>yi.map(Fh=>`"${(Fh||"").replace(/"/g,'""')}"`).join(","))].join(` `),gn=new Blob([hr],{type:"text/csv"}),_n=URL.createObjectURL(gn),Aa=document.createElement("a"),Gn=ge!=="all"?`-last-${ge}days`:"";Aa.href=_n,Aa.download=`members-export${Gn}-${new Date().toISOString().split("T")[0]}.csv`,Aa.click(),URL.revokeObjectURL(_n),i({title:"Export complete",description:`Exported ${A1.length} member(s)`})};return v?e.jsx(_s,{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(_s,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Member Management",description:"Manage users, roles, and permissions"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:L1,disabled:Es,children:[Es?e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Nn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Es?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Es?"Syncing...":"Sync GHL"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>Hr(!0),children:[e.jsx(Jb,{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:D,onOpenChange:B,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(nl,{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(js,{children:[e.jsx(bs,{children:"Create New User"}),e.jsx(Fr,{children:"Add a new user to the system. They'll be able to sign in immediately."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",placeholder:"John Doe",value:A.name,onChange:It=>P({...A,name:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{id:"email",type:"email",placeholder:"john@example.com",value:A.email,onChange:It=>P({...A,email:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"password",children:"Password"}),e.jsx(ke,{id:"password",type:"password",placeholder:"Min 6 characters",value:A.password,onChange:It=>P({...A,password:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ke,{id:"phone",type:"tel",placeholder:"555-123-4567",value:A.phone,onChange:It=>P({...A,phone:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"brokerage",children:["Brokerage",A.role==="brokerage_manager"?" (required)":""]}),e.jsxs(zs,{value:A.brokerage_id||"none",onValueChange:It=>P({...A,brokerage_id:It==="none"?"":It}),children:[e.jsx(Os,{id:"brokerage",children:e.jsx(Us,{placeholder:A.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"None"}),h.map(It=>e.jsx(mt,{value:It.id,children:It.name},It.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"role",children:"Role"}),e.jsxs(zs,{value:A.role,onValueChange:It=>P({...A,role:It}),children:[e.jsx(Os,{id:"role",children:e.jsx(Us,{placeholder:"Select role"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"user",children:"User"}),e.jsx(mt,{value:"moderator",children:"Moderator"}),e.jsx(mt,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(mt,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(zs,{value:A.trial_days||"none",onValueChange:It=>P({...A,trial_days:It==="none"?"":It}),children:[e.jsx(Os,{id:"trial_days",children:e.jsx(Us,{placeholder:"No trial (full access)"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No trial (full access)"}),e.jsx(mt,{value:"7",children:"7-day trial"}),e.jsx(mt,{value:"30",children:"30-day trial"}),e.jsx(mt,{value:"60",children:"60-day trial"}),e.jsx(mt,{value:"90",children:"90-day trial"}),e.jsx(mt,{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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>B(!1),children:"Cancel"}),e.jsx(G,{onClick:Jn,disabled:S,children:S?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(Rn,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"members",children:"Members"}),e.jsx(Xt,{value:"brokerages",children:"Brokerages"}),e.jsx(Xt,{value:"teams",children:"Teams"}),e.jsx(Xt,{value:"trials",children:"Trial Users"}),e.jsx(Xt,{value:"access",children:"Access Matrix"}),e.jsx(Xt,{value:"celebrations",children:"Celebrations"}),e.jsx(Xt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search members...",value:z,onChange:It=>lN(It.target.value),className:"pl-10 h-9"})]}),e.jsxs(zs,{value:Y,onValueChange:It=>dy(ne,It),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Status"}),e.jsx(mt,{value:"claimed",children:"Active"}),e.jsx(mt,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(zs,{value:de,onValueChange:It=>dy(ce,It),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Roles"}),e.jsx(mt,{value:"admin",children:"Admin"}),e.jsx(mt,{value:"brokerage_manager",children:"Manager"}),e.jsx(mt,{value:"assistant",children:"Assistant"}),e.jsx(mt,{value:"user",children:"User"})]})]}),e.jsxs(zs,{value:ae,onValueChange:It=>dy(ie,It),children:[e.jsx(Os,{className:"w-[130px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Users"}),e.jsx(mt,{value:"trial",children:"Trial Only"}),e.jsx(mt,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(zs,{value:me,onValueChange:It=>dy(oe,It),children:[e.jsx(Os,{className:"w-[150px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Brokerages"}),e.jsx(mt,{value:"none",children:"No Brokerage"}),h.map(It=>e.jsx(mt,{value:It.id,children:It.name},It.id))]})]}),e.jsxs(zs,{value:ge,onValueChange:It=>dy(be,It),children:[e.jsx(Os,{className:"w-[150px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"Any Join Date"}),e.jsx(mt,{value:"30",children:"Joined Last 30 Days"}),e.jsx(mt,{value:"60",children:"Joined Last 60 Days"}),e.jsx(mt,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(G,{size:"sm",variant:"outline",className:"h-9",onClick:cT,title:"Export currently filtered members to CSV",children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(z||Y!=="all"||de!=="all"||ae!=="all"||me!=="all"||ge!=="all")&&e.jsxs(G,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{F(""),ne("all"),ce("all"),ie("all"),oe("all"),be("all"),X(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:k0?`Showing all ${Rf} members`:`Showing ${Dc+1}-${Math.min(fm,Rf)} of ${Rf} members`}),e.jsxs(zs,{value:K.toString(),onValueChange:It=>cN(Number(It)),children:[e.jsx(Os,{className:"h-9 w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"50",children:"50 / page"}),e.jsx(mt,{value:"100",children:"100 / page"}),e.jsx(mt,{value:"250",children:"250 / page"}),e.jsx(mt,{value:"0",children:"All"})]})]})]})]}),kt.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[Hd.length>0&&Hd.every(It=>kt.has(It.id))&&mm.length>kt.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 ",kt.size," on this page are selected."]}),e.jsxs(G,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>Gt(new Set(mm.map(It=>It.id))),children:["Select all ",mm.length," filtered members"]})]}),mm.length>0&&kt.size===mm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",mm.length," filtered members are selected."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lb,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[kt.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:dN,disabled:Mt,children:[Mt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Qs,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:z_,disabled:Mt,children:[Mt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(gp,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Password Reset"}),e.jsx("span",{className:"sm:hidden",children:"Reset"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>Me(!0),disabled:Mt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(QR,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Event Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:lT,children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs(G,{size:"sm",variant:"destructive",onClick:Wx,disabled:Mt,children:[Mt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(yr,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:Gd,disabled:Mt,children:e.jsx(_r,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[50px]",children:e.jsx(Ei,{checked:Hd.length>0&&Hd.every(It=>kt.has(It.id)),onCheckedChange:B_,"aria-label":"Select all on page"})}),e.jsx(Al,{sortKey:"name",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Name"}),e.jsx(Al,{sortKey:"brokerage",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Brokerage"}),e.jsx(Al,{sortKey:"status",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Status"}),e.jsx(Al,{sortKey:"role",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Role"}),e.jsx(Al,{sortKey:"last_login",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Last Login"}),e.jsx(Al,{sortKey:"created_at",currentSortKey:oy,currentDirection:ly,onSort:cy,children:"Member Since"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(Bn,{children:Hd.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Hd.map(It=>e.jsxs(qs,{className:`hover:bg-muted/30 ${kt.has(It.id)?"bg-primary/5":""}`,children:[e.jsx(ft,{children:e.jsx(Ei,{checked:kt.has(It.id),onCheckedChange:()=>yL(It.id),"aria-label":`Select ${It.name}`})}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>S0(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(ft,{className:"text-muted-foreground",children:It.brokerage_name||"—"}),e.jsx(ft,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Gs=It.trial_expires_at||It.subscription_end_date;if((It.is_trial||It.subscription_status==="trialing")&&Gs){const gn=Math.ceil((new Date(Gs).getTime()-Date.now())/864e5),_n=gn<=0,Aa=gn<=3;return e.jsx(Ge,{variant:"outline",className:Bt("w-fit",_n?"border-destructive text-destructive":Aa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:_n?"Trial Expired":`Trial · ${gn}d left`})}return e.jsx(Ge,{variant:It.claimed?"default":"secondary",className:It.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:It.claimed?"Active":"Pending"})})()})}),e.jsx(ft,{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")&&Qi[It.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Qi[It.id].agent_name||Qi[It.id].agent_email]})]})}),e.jsx(ft,{className:"text-muted-foreground",children:It.last_sign_in_at?new Date(It.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(ft,{className:"text-muted-foreground",children:It.created_at?new Date(It.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{$s(It),Yn(!0)},title:"Send celebration",children:e.jsx(iu,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>S0(It),title:"Edit member",children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>T0(It.id,It.email),disabled:gr===It.id,title:"Sync phone with GHL",children:gr===It.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Lo(It.id),title:"Resend welcome email",children:e.jsx(Qs,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>rc(It.email,It.name),title:"Send password reset",children:e.jsx(E3,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>$_(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(P3,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>dr(It.id,It.name),title:"Delete user",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},It.id))})]})}),du>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Page ",$," of ",du]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>X(1),disabled:$===1,children:"First"}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>X(It=>Math.max(1,It-1)),disabled:$===1,children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,du)},(It,Gs)=>{let hr;return du<=5||$<=3?hr=Gs+1:$>=du-2?hr=du-4+Gs:hr=$-2+Gs,e.jsx(G,{variant:$===hr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>X(hr),children:hr},hr)})}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>X(It=>Math.min(du,It+1)),disabled:$===du,children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>X(du),disabled:$===du,children:"Last"})]})]})]}),e.jsx(vs,{open:ve,onOpenChange:rt,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Member"}),e.jsx(Fr,{children:"Update member details, roles, and app access"})]}),ye&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-name",children:"Name"}),e.jsx(ke,{id:"edit-name",value:Re.name,onChange:It=>Qe({...Re,name:It.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-email",children:"Email"}),e.jsx(ke,{id:"edit-email",type:"email",value:Re.email,onChange:It=>Qe({...Re,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(he,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ke,{id:"edit-phone",type:"tel",value:Re.phone,onChange:It=>Qe({...Re,phone:It.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(zs,{value:Re.brokerage_id||"none",onValueChange:It=>Qe({...Re,brokerage_id:It==="none"?"":It}),children:[e.jsx(Os,{id:"edit-brokerage",children:e.jsx(Us,{placeholder:"Select brokerage"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"None"}),h.map(It=>e.jsx(mt,{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:[ye.roles.map(It=>e.jsxs(Ge,{variant:"default",className:"gap-1",children:[e.jsx(Zu,{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:()=>uo(ye.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)),ye.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(zs,{onValueChange:It=>uo(ye.id,It,"add"),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Add role..."})}),e.jsxs(Fs,{children:[!ye.roles.includes("admin")&&e.jsx(mt,{value:"admin",children:"Admin"}),!ye.roles.includes("user")&&e.jsx(mt,{value:"user",children:"User"})]})]}),!ye.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"})]}),(Kr.length>0||Ja.length>0||ye.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(fr,{className:"h-4 w-4"}),"Assistant Relationships"]}),ra?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:[Kr.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:"}),Kr.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(Ge,{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(([,Gs])=>Gs).map(([Gs])=>e.jsx(Ge,{variant:"secondary",className:"text-[10px] capitalize",children:Gs},Gs))})]},It.id))]}),Ja.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:"}),Ja.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(Ge,{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(([,Gs])=>Gs).map(([Gs])=>e.jsx(Ge,{variant:"secondary",className:"text-[10px] capitalize",children:Gs},Gs))})]},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 Gs=ll(ye.tags,It.required_tags),hr=`${ye.id}-${It.id}`,gn=Ke===hr,_n=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}),_n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:gn?e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"}):_n?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(br,{checked:Gs,onCheckedChange:()=>Va(ye.id,It,Gs)})})]},It.id)})})]}),(ye.is_trial||ye.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(cn,{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:[ye.trial_expires_at&&e.jsx(Dze,{expiresAt:ye.trial_expires_at}),!ye.trial_expires_at&&ye.subscription_status==="trialing"&&ye.subscription_end_date&&e.jsx(Dze,{expiresAt:ye.subscription_end_date})]}),(ye.trial_expires_at||ye.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(ye.trial_expires_at||ye.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>kp(ye.id,7),disabled:Pe,children:[e.jsx(Ub,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>kp(ye.id,14),disabled:Pe,children:[e.jsx(Ub,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>kp(ye.id,30),disabled:Pe,children:[e.jsx(Ub,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(G,{size:"sm",variant:"default",onClick:()=>Sp(ye.id),disabled:$e,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Yv,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),ye.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(ye.trial_started_at).toLocaleDateString(),ye.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(ye.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(ye.is_trial||ye.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(cn,{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(G,{size:"sm",variant:"outline",onClick:()=>oT(ye.id,It),disabled:M1,children:[e.jsx(Ub,{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:[ye.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(ye.email_confirmed_at).toLocaleString()]}),ye.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(ye.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(ye.created_at).toLocaleString()]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:P1,children:"Cancel"}),e.jsx(G,{onClick:C0,children:"Save Changes"})]})]})}),e.jsxs(as,{value:"access",children:[c.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(G,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Member Access Matrix"}),e.jsx(Nr,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents by name or email...",value:z,onChange:It=>{F(It.target.value),X(1)},className:"pl-9"})]})]}),e.jsxs(De,{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:[Hd.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(Gs=>{const hr=ll(It.tags,Gs.required_tags),gn=`${It.id}-${Gs.id}`,_n=Ke===gn;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:_n?e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(br,{checked:hr,onCheckedChange:()=>Va(It.id,Gs,hr),disabled:Gs.required_tags.length===0})})},Gs.id)})]},It.id)),Hd.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"})})]})]})}),du>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 ",Dc+1,"-",Math.min(fm,Rf)," of ",Rf," • Page ",$," of ",du]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>X(It=>Math.max(1,It-1)),disabled:$===1,children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>X(It=>Math.min(du,It+1)),disabled:$===du,children:e.jsx(ya,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(G,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search brokerages...",value:aa,onChange:It=>Na(It.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[h.filter(It=>It.name.toLowerCase().includes(aa.toLowerCase())).length," of ",h.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{const It=[];for(const Gn of h){const yi=x[Gn.id]??[];for(const Fh of yi){const Tp=l.find(Jr=>Jr.id===Fh);if(Tp){const Jr=(Tp.name||"").trim().split(/\s+/),Wa=Jr[0]||"",U_=Jr.slice(1).join(" ")||"";It.push({firstName:Wa,lastName:U_,email:Tp.email,brokerageName:Gn.name})}}}if(It.length===0){i({title:"No managers found to export"});return}const hr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...It.map(Gn=>[Gn.firstName,Gn.lastName,Gn.email,Gn.brokerageName].map(yi=>`"${(yi||"").replace(/"/g,'""')}"`).join(","))].join(` `),gn=new Blob([hr],{type:"text/csv"}),_n=URL.createObjectURL(gn),Aa=document.createElement("a");Aa.href=_n,Aa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Aa.click(),URL.revokeObjectURL(_n),i({title:`Exported ${It.length} managers`})},children:[e.jsx(Xa,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(vs,{open:nt,onOpenChange:$t,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Create New Brokerage"}),e.jsx(Fr,{children:"Add a new brokerage to the system."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ke,{id:"brokerage-name",placeholder:"Enter brokerage name",value:lt,onChange:It=>it(It.target.value),maxLength:100})]})}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>$t(!1),children:"Cancel"}),e.jsx(G,{onClick:Dl,disabled:Nt,children:Nt?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Tt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Tt,{className:"font-semibold",children:"Agents"}),e.jsx(Tt,{className:"w-[150px]"})]})}),e.jsx(Bn,{children:(()=>{const It=h.filter(Gs=>Gs.name.toLowerCase().includes(aa.toLowerCase()));return It.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:aa?"No brokerages match your search":"No brokerages found"})}):It.map(Gs=>{const hr=l.filter(Gn=>Gn.brokerage_id===Gs.id),_n=(x[Gs.id]??[]).map(Gn=>l.find(yi=>yi.id===Gn)).filter(Boolean),Aa=hr.length;return e.jsxs(qs,{className:"hover:bg-muted/30",children:[e.jsx(ft,{children:e.jsx("button",{onClick:()=>Wm(Gs),className:"text-primary hover:underline font-medium",children:Gs.name})}),e.jsx(ft,{children:_n.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:_n.map(Gn=>e.jsx(Ge,{variant:"secondary",className:"text-xs",children:Gn.name},Gn.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(ft,{children:[Aa," member",Aa!==1?"s":""]}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Do(Gs),children:[e.jsx(fr,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Wm(Gs),title:"Edit brokerage",children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>F_(Gs),title:"Delete brokerage",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Gs.id)})})()})]})}),e.jsx(vs,{open:at,onOpenChange:Ie,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Brokerage"}),e.jsx(Fr,{children:"Update brokerage details and manage managers"})]}),et&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(ke,{id:"edit-brokerage-name",value:Jt,onChange:It=>cs(It.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Managers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager access for this brokerage (keeps them as a member)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const Gs=(x[et.id]??[]).map(hr=>l.find(gn=>gn.id===hr)).filter(Boolean);return Gs.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Gs.map(hr=>e.jsxs(Ge,{variant:"default",className:"gap-1",children:[e.jsx(Zu,{className:"h-3 w-3"}),hr.name,e.jsx("button",{onClick:()=>uo(hr.id,"brokerage_manager","remove",et.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"})})]},hr.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(Ao,{open:Je,onOpenChange:Fe,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":Je,className:"w-full justify-between",children:["Search for a member...",e.jsx(fn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-full p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search by name or email..."}),e.jsxs(Lx,{className:"max-h-[200px]",children:[e.jsx(Dx,{children:"No members found."}),e.jsx(Rx,{children:(()=>{const It=new Set(x[et.id]??[]);return l.filter(Gs=>!It.has(Gs.id)&&(r||Gs.brokerage_id===et.id)).map(Gs=>e.jsxs(vf,{value:`${Gs.name} ${Gs.email}`,onSelect:()=>{j0(Gs.id,et.id),Fe(!1)},children:[Gs.name," (",Gs.email,")"]},Gs.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(It=>It.brokerage_id===et.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(It=>It.brokerage_id===et.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(Ge,{variant:"outline",className:"text-xs",children:"Manager"})]},It.id))})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:Lf,children:"Cancel"}),e.jsx(G,{onClick:Gx,disabled:Ht,children:Ht?"Saving...":"Save Changes"})]})]})}),e.jsx(vs,{open:Qt,onOpenChange:yt,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Fr,{children:['Are you sure you want to delete "',ss==null?void 0:ss.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 "',ss==null?void 0:ss.name,'"']}),e.jsxs("li",{children:["All ",l.filter(It=>It.brokerage_id===(ss==null?void 0:ss.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>yt(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:E1,disabled:fs,children:fs?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(vs,{open:Er,onOpenChange:Tr,children:e.jsxs(ys,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-5 w-5"}),"Manage ",Lr==null?void 0:Lr.name]}),e.jsx(Fr,{children:"Add, remove, or manage users in this brokerage"})]}),Lr&&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(fn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search members...",value:kr,onChange:It=>Sr(It.target.value),className:"pl-10 h-9"})]}),e.jsxs(vs,{open:hn,onOpenChange:zn,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(nl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add New Agent"}),e.jsxs(Fr,{children:["Create a new agent for ",Lr.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-name",children:"Name"}),e.jsx(ke,{id:"agent-name",placeholder:"John Doe",value:Xs.name,onChange:It=>Ur({...Xs,name:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-email",children:"Email"}),e.jsx(ke,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Xs.email,onChange:It=>Ur({...Xs,email:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-password",children:"Password"}),e.jsx(ke,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Xs.password,onChange:It=>Ur({...Xs,password:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(ke,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Xs.phone,onChange:It=>Ur({...Xs,phone:It.target.value})})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>zn(!1),children:"Cancel"}),e.jsx(G,{onClick:Df,disabled:xn,children:xn?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Ao,{open:We,onOpenChange:He,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":We,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(fn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search users...",value:bt,onValueChange:ut}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:"No users found."}),e.jsx(Rx,{children:oN(Lr.id).filter(It=>bt===""||It.name.toLowerCase().includes(bt.toLowerCase())||It.email.toLowerCase().includes(bt.toLowerCase())).map(It=>e.jsxs(vf,{value:`${It.name} ${It.email}`,onSelect:()=>{N0(It.id,Lr.id),He(!1),ut("")},children:[It.name," (",It.email,")"]},It.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Name"}),e.jsx(Tt,{className:"font-semibold",children:"Email"}),e.jsx(Tt,{className:"font-semibold",children:"Status"}),e.jsx(Tt,{className:"font-semibold",children:"Role"}),e.jsx(Tt,{className:"w-[120px]"})]})}),e.jsx(Bn,{children:iN(Lr.id).length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:kr?"No matching members found":"No members in this brokerage"})}):iN(Lr.id).map(It=>e.jsxs(qs,{className:"hover:bg-muted/30",children:[e.jsx(ft,{className:"font-medium",children:It.name}),e.jsx(ft,{className:"text-muted-foreground",children:It.email}),e.jsx(ft,{children:It.claimed?e.jsx(Ge,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Pending"})}),e.jsx(ft,{children:It.roles.includes("brokerage_manager")?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Zu,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!It.claimed&&e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Lo(It.id),title:"Resend welcome email",children:e.jsx(Qs,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>iy(It.id),title:"Remove from brokerage",children:e.jsx(_r,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>$_(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(P3,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>dr(It.id,It.name),title:"Delete user",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},It.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[bd(Lr.id).length," total member",bd(Lr.id).length!==1?"s":""," •",bd(Lr.id).filter(It=>It.roles.includes("brokerage_manager")).length," manager",bd(Lr.id).filter(It=>It.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(on,{children:e.jsx(G,{variant:"outline",onClick:vd,children:"Close"})})]})})]}),e.jsx(as,{value:"teams",children:e.jsx(fes,{})}),e.jsx(as,{value:"trials",children:e.jsx(des,{})}),e.jsx(as,{value:"celebrations",children:e.jsx(ces,{})}),e.jsx(as,{value:"deletions",children:e.jsx(ues,{})})]})]}),e.jsx(Wlt,{open:pr,onOpenChange:Hr,brokerages:h,onSuccess:za}),Qr&&e.jsx(Klt,{open:Xr,onOpenChange:It=>{Yn(It),It||$s(null)},userId:Qr.id,userName:Qr.name}),e.jsx(pes,{open:Oe,onOpenChange:Me,recipients:l.filter(It=>kt.has(It.id)).map(It=>({id:It.id,name:It.name,email:It.email}))})]})},ges=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState("");k.useEffect(()=>{v()},[]);const v=async()=>{const{data:P,error:D}=await H.from("invite_codes").select("*").order("created_at",{ascending:!1});D?(ue.error("Failed to load invite codes"),console.error(D)):t(P||[]),n(!1)},j=async P=>{if(P.preventDefault(),!l.trim()){ue.error("Please enter a code");return}i(!0);const{error:D}=await H.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:h?parseInt(h):null,trial_days:x?parseInt(x):null});D?D.code==="23505"?ue.error("This code already exists"):(ue.error("Failed to create invite code"),console.error(D)):(ue.success("Invite code created"),o(""),d(""),m(""),g(""),v()),i(!1)},b=async(P,D)=>{const{error:B}=await H.from("invite_codes").update({is_active:!D}).eq("id",P);B?ue.error("Failed to update code"):t(s.map(z=>z.id===P?{...z,is_active:!D}:z))},N=async P=>{const{error:D}=await H.from("invite_codes").delete().eq("id",P);D?ue.error("Failed to delete code"):(ue.success("Code deleted"),t(s.filter(B=>B.id!==P)))},S="https://dashboard.relevelup.com",T=P=>{const D=`${S}/join?code=${P}`;navigator.clipboard.writeText(D),ue.success("Link copied to clipboard")},A=`${S}/join`;return e.jsx(_s,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Create New Code"}),e.jsxs(Nr,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(De,{children:e.jsxs("form",{onSubmit:j,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"code",children:"Code"}),e.jsx(ke,{id:"code",placeholder:"WELCOME2024",value:l,onChange:P=>o(P.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(he,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ke,{id:"description",placeholder:"For marketing campaign",value:c,onChange:P=>d(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(ke,{id:"maxUses",type:"number",placeholder:"Unlimited",value:h,onChange:P=>m(P.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(ke,{id:"trialDays",type:"number",placeholder:"None",value:x,onChange:P=>g(P.target.value),className:"w-28"})]}),e.jsxs(G,{type:"submit",disabled:a,children:[a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Active Codes"})}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Uses"}),e.jsx(Tt,{children:"Trial"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Active"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(P=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-mono font-medium",children:P.code}),e.jsx(ft,{className:"text-muted-foreground",children:P.description||"—"}),e.jsxs(ft,{children:[P.uses_count,P.max_uses&&` / ${P.max_uses}`]}),e.jsx(ft,{children:P.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[P.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ft,{className:"text-muted-foreground",children:Ss(new Date(P.created_at),"MMM d, yyyy")}),e.jsx(ft,{children:e.jsx(br,{checked:P.is_active,onCheckedChange:()=>b(P.id,P.is_active)})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>T(P.code),title:"Copy invite link",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>N(P.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},P.id))})]})})]})]})})},fz=async s=>{try{const{data:t,error:r}=await H.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}},RP=async s=>{try{const{data:t,error:r}=await H.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}}},yes=async(s,t)=>await fz("new_templates")?RP({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}),ves=async(s,t)=>RP({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),bes=async(s,t)=>await fz("new_events")?RP({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),_es=async(s,t)=>await fz("new_toolbox")?RP({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),FNe=async(s,t)=>await fz("new_social_swag")?RP({title:"New Social Swag",body:`New social swag available: ${s}`,url:`/social-swag/${t}`}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),wes=async(s,t)=>await fz("new_newsletters")?RP({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),kU={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 jes(){const s=vr(),t=es(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState(kU),[c,d]=k.useState(null),[h,m]=k.useState(null),[x,g]=k.useState(!1),v=k.useRef(null),[j,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(!1),[P,D]=k.useState(null),[B,z]=k.useState(null),[F,$]=k.useState(!0),[X,K]=k.useState(""),{data:Q,isLoading:Y}=gt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ce,error:nt}=await H.from("events").select("*").order("event_date",{ascending:!0});if(nt)throw nt;return Ce}}),{data:ne}=gt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ce=[],nt=0;const $t=1e3;for(;;){const{data:it,error:Nt}=await H.from("event_registrations").select("event_id").range(nt,nt+$t-1);if(Nt)throw Nt;if(!it||it.length===0||(Ce=Ce.concat(it),it.length<$t))break;nt+=$t}const lt={};return Ce.forEach(it=>{lt[it.event_id]=(lt[it.event_id]||0)+1}),lt}}),{data:de,isLoading:ce}=gt({queryKey:["event-registrations-details",N==null?void 0:N.id],queryFn:async()=>{if(!N)return[];const{data:Ce,error:nt}=await H.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",N.id).order("registered_at",{ascending:!1});if(nt)throw nt;if(!Ce||Ce.length===0)return[];const $t=Ce.map(Nt=>Nt.user_id).filter(Boolean);let lt=[];if($t.length>0){const{data:Nt,error:Ft}=await H.from("profiles").select("id, name, email").in("id",$t);if(Ft)throw Ft;lt=Nt||[]}const it=new Map((lt==null?void 0:lt.map(Nt=>[Nt.id,Nt]))||[]);return Ce.map(Nt=>({...Nt,profiles:Nt.user_id&&it.get(Nt.user_id)||null}))},enabled:!!N}),{data:ae,isLoading:ie}=gt({queryKey:["event-attendees-details",N==null?void 0:N.id],queryFn:async()=>{if(!N)return[];const{data:Ce,error:nt}=await H.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",N.id).order("created_at",{ascending:!1});if(nt)throw nt;if(!Ce||Ce.length===0)return[];const $t=Ce.map(at=>at.user_id).filter(Boolean);let lt=[];if($t.length>0){const{data:at,error:Ie}=await H.from("profiles").select("id, name, email").in("id",$t);if(Ie)throw Ie;lt=at||[]}const{data:it}=await H.from("agent_points").select("user_id").eq("event_id",N.id),Nt=new Set((it==null?void 0:it.map(at=>at.user_id))||[]),Ft=new Map((lt==null?void 0:lt.map(at=>[at.id,at]))||[]);return Ce.map(at=>({...at,profiles:at.user_id&&Ft.get(at.user_id)||null,points_awarded:at.user_id?Nt.has(at.user_id):!1}))},enabled:!!N}),me=Ce=>{S(Ce),b(!0)},oe=Lt({mutationFn:async Ce=>{const{data:{session:nt}}=await H.auth.getSession();if(!nt)throw new Error("Not authenticated");const $t=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ce})}),lt=await $t.json();if(!$t.ok)throw new Error(lt.error||"Failed to sync");return lt},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-registrations-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ue.success(Ce.message)},onError:Ce=>{ue.error("Failed to sync: "+Ce.message)}}),ge=Lt({mutationFn:async Ce=>{const{data:{session:nt}}=await H.auth.getSession();if(!nt)throw new Error("Not authenticated");const $t=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ce})}),lt=await $t.json();if(!$t.ok)throw new Error(lt.error||"Failed to sync attendees");return lt},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-attendees-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ce!=null&&Ce.message?ue.success(Ce.message):ue.success(`Synced ${Ce.synced||0} attendees. ${Ce.points_awarded||0} points awarded!`)},onError:Ce=>{ue.error("Failed to sync attendees: "+Ce.message)}}),be=Lt({mutationFn:async()=>{const{data:Ce,error:nt}=await H.functions.invoke("zoom-retry-registrations",{body:{}});if(nt)throw nt;return Ce},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-registrations-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ue.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=>{ue.error("Retry failed: "+Ce.message)}}),Oe=Lt({mutationFn:async({eventId:Ce,testMode:nt})=>{const{data:{session:$t}}=await H.auth.getSession();if(!$t)throw new Error("Not authenticated");const lt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$t.access_token}`},body:JSON.stringify({event_id:Ce,test_mode:nt})}),it=await lt.json();if(!lt.ok)throw new Error(it.error||"Failed to send reminders");return it},onSuccess:Ce=>{Ce.test?ue.success(Ce.message||"Test email sent!"):ue.success(Ce.message||`Reminder emails sent to ${Ce.sent} registrants!`)},onError:Ce=>{ue.error("Failed to send reminders: "+Ce.message)}}),{data:Me}=gt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ce=[],nt=0;const $t=1e3;for(;;){const{data:lt,error:it}=await H.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(nt,nt+$t-1);if(it)throw it;if(!lt||lt.length===0||(Ce=[...Ce,...lt],lt.length<$t))break;nt+=$t}return Ce},enabled:T}),Pe=Lt({mutationFn:async({attendeeId:Ce,userId:nt,zoomEmail:$t,shouldSaveAlias:lt})=>{const{error:it}=await H.from("event_attendees").update({user_id:nt}).eq("id",Ce);if(it)throw it;if(lt&&$t){const{error:Ft}=await H.from("zoom_email_aliases").upsert({user_id:nt,zoom_email:$t.toLowerCase()},{onConflict:"zoom_email"});Ft&&console.error("Failed to save alias:",Ft)}const Nt=N==null?void 0:N.id;if(Nt){const{data:Ft}=await H.from("user_roles").select("id").eq("user_id",nt).eq("role","admin").single();if(!Ft){const{data:at}=await H.from("agent_points").select("id").eq("user_id",nt).eq("event_id",Nt).single();at||(await H.rpc("award_attendance_points",{p_user_id:nt,p_event_id:Nt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await H.rpc("check_and_award_badges",{p_user_id:nt}))}}return{userId:nt,zoomEmail:$t,shouldSaveAlias:lt}},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-attendees-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let nt="Attendee linked and points awarded!";Ce.shouldSaveAlias&&Ce.zoomEmail&&(nt+=` Email "${Ce.zoomEmail}" will be auto-matched in the future.`),ue.success(nt),A(!1),D(null),z(null),K("")},onError:Ce=>{ue.error("Failed to link attendee: "+Ce.message)}}),Ee=Ce=>{D(Ce),z(null),$(!0),K(""),A(!0)},$e=()=>{!P||!B||Pe.mutate({attendeeId:P.id,userId:B,zoomEmail:P.zoom_email,shouldSaveAlias:F})},Se=(Me==null?void 0:Me.filter(Ce=>{var $t,lt;if(!X)return!0;const nt=X.toLowerCase();return(($t=Ce.name)==null?void 0:$t.toLowerCase().includes(nt))||((lt=Ce.email)==null?void 0:lt.toLowerCase().includes(nt))}))||[],ze=async Ce=>{const nt=Ce.name.split(".").pop(),lt=`${`${crypto.randomUUID()}.${nt}`}`,{error:it}=await H.storage.from("event-images").upload(lt,Ce);if(it)throw it;const{data:{publicUrl:Nt}}=H.storage.from("event-images").getPublicUrl(lt);return Nt},Te=Ce=>{var $t;const nt=($t=Ce.target.files)==null?void 0:$t[0];if(nt){if(nt.size>5*1024*1024){ue.error("Image must be less than 5MB");return}d(nt),m(URL.createObjectURL(nt))}},ye=()=>{d(null),m(null),o({...l,image_url:""}),v.current&&(v.current.value="")},ct=Lt({mutationFn:async Ce=>{g(!0);let nt=Ce.image_url;c&&(nt=await ze(c)||"");const $t=new Date(Ce.event_date),[lt,it]=Ce.event_time.split(":");$t.setHours(parseInt(lt),parseInt(it));const Nt=[new Date($t)];if(Ce.is_recurring&&Ce.recurrence_end_date){let et=new Date($t);for(;Ce.recurrence_pattern==="weekly"?et=U4(et,1):Ce.recurrence_pattern==="biweekly"?et=U4(et,2):et=Cf(et,1),!(et>Ce.recurrence_end_date);)Nt.push(new Date(et))}const Ft=Nt.map(et=>({title:Ce.title,description:Ce.description||null,image_url:nt||null,video_url:Ce.video_url||null,event_date:et.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:at,error:Ie}=await H.from("events").insert(Ft).select();if(Ie)throw Ie;return at&&at.length>0&&bes(Ce.title,at[0].id),Nt.length},onSuccess:Ce=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success(Ce>1?`${Ce} recurring events created successfully`:"Event created successfully"),n(!1),o(kU),d(null),m(null),g(!1)},onError:Ce=>{ue.error("Failed to create event: "+Ce.message),g(!1)}}),ve=Lt({mutationFn:async({id:Ce,data:nt})=>{g(!0);let $t=nt.image_url;c&&($t=await ze(c)||"");const lt=new Date(nt.event_date),[it,Nt]=nt.event_time.split(":");lt.setHours(parseInt(it),parseInt(Nt));const{error:Ft}=await H.from("events").update({title:nt.title,description:nt.description||null,image_url:$t||null,video_url:nt.video_url||null,event_date:lt.toISOString(),zoom_link:nt.zoom_link,zoom_meeting_id:nt.zoom_meeting_id||null,capacity:nt.capacity?parseInt(nt.capacity):null,is_published:nt.is_published}).eq("id",Ce);if(Ft)throw Ft},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success("Event updated successfully"),n(!1),i(null),o(kU),d(null),m(null),g(!1)},onError:Ce=>{ue.error("Failed to update event: "+Ce.message),g(!1)}}),rt=Lt({mutationFn:async Ce=>{const{error:nt}=await H.from("events").delete().eq("id",Ce);if(nt)throw nt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success("Event deleted successfully")},onError:Ce=>{ue.error("Failed to delete event: "+Ce.message)}}),Re=Ce=>{var $t;const nt=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:nt,event_time:Ss(nt,"HH:mm"),zoom_link:Ce.zoom_link,zoom_meeting_id:Ce.zoom_meeting_id||"",capacity:(($t=Ce.capacity)==null?void 0:$t.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)},Qe=Ce=>{if(Ce.preventDefault(),!l.event_date){ue.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ue.error("Please select an end date for recurring events");return}a?ve.mutate({id:a.id,data:l}):ct.mutate(l)},Ke=()=>{n(!1),i(null),o(kU),d(null),m(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/dashboard"),children:e.jsx(wa,{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(Ne,{className:"mb-6",children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"All Events"}),e.jsxs(vs,{open:r,onOpenChange:Ce=>!Ce&&Ke(),children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx(Ws,{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(js,{children:e.jsx(bs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Qe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{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(he,{children:"Description"}),e.jsx(y0,{content:l.description,onChange:Ce=>o({...l,description:Ce}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Event Image"}),e.jsx("input",{type:"file",ref:v,accept:"image/*",onChange:Te,className:"hidden"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:ye,children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs(G,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ce;return(Ce=v.current)==null?void 0:Ce.click()},children:[e.jsx(oa,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Click to upload image"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Date *"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),l.event_date?Ss(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{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(he,{htmlFor:"time",children:"Time *"}),e.jsx(ke,{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(he,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(ke,{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(he,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(ke,{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(he,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(ke,{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(he,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(ke,{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(kO,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(br,{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(he,{children:"Frequency"}),e.jsxs(zs,{value:l.recurrence_pattern,onValueChange:Ce=>o({...l,recurrence_pattern:Ce}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"weekly",children:"Weekly"}),e.jsx(mt,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(mt,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Repeat Until"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Ss(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{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,nt=new Date(l.event_date);for(;nt=l.recurrence_pattern==="weekly"?U4(nt,1):l.recurrence_pattern==="biweekly"?U4(nt,2):Cf(nt,1),!(nt>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(he,{htmlFor:"is_published",children:"Published"}),e.jsx(br,{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(G,{type:"button",variant:"outline",onClick:Ke,className:"flex-1",children:"Cancel"}),e.jsx(G,{type:"submit",className:"flex-1",disabled:ct.isPending||ve.isPending||x,children:x?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(De,{children:Y?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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Date & Time"}),e.jsx(Tt,{children:"Registrations"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:Q==null?void 0:Q.map(Ce=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:Ce.title}),e.jsx(ft,{children:Ss(new Date(Ce.event_date),"PPP p")}),e.jsx(ft,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>me(Ce),children:[e.jsx(fr,{className:"h-4 w-4"}),(ne==null?void 0:ne[Ce.id])||0,Ce.capacity&&` / ${Ce.capacity}`]})}),e.jsx(ft,{children:e.jsx("span",{className:Bt("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(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(Ce.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Yr,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Re(Ce),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&rt.mutate(Ce.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},Ce.id))})]})})]}),e.jsx(vs,{open:j,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),N==null?void 0:N.title]}),e.jsx(Fr,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Oe.mutate({eventId:N.id,testMode:!0}),disabled:Oe.isPending,children:[e.jsx(Qs,{className:Bt("h-4 w-4 mr-2",Oe.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>Oe.mutate({eventId:N.id}),disabled:Oe.isPending||!(de!=null&&de.length),children:[e.jsx(Qs,{className:Bt("h-4 w-4 mr-2",Oe.isPending&&"animate-spin")}),Oe.isPending?"Sending...":"Send Reminder to All"]}),(N==null?void 0:N.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>oe.mutate(N.id),disabled:oe.isPending,children:[e.jsx(Di,{className:Bt("h-4 w-4 mr-2",oe.isPending&&"animate-spin")}),oe.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>be.mutate(),disabled:be.isPending,children:[e.jsx(Di,{className:Bt("h-4 w-4 mr-2",be.isPending&&"animate-spin")}),be.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(G,{variant:"default",size:"sm",onClick:()=>ge.mutate(N.id),disabled:ge.isPending,children:[e.jsx(Zi,{className:Bt("h-4 w-4 mr-2",ge.isPending&&"animate-spin")}),ge.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(Rn,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"registrations",className:"gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Registrations (",(de==null?void 0:de.length)||0,")"]}),e.jsxs(Xt,{value:"attendees",className:"gap-2",children:[e.jsx(Mn,{className:"h-4 w-4"}),"Attendees (",(ae==null?void 0:ae.length)||0,")"]})]}),e.jsx(as,{value:"registrations",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(de==null?void 0:de.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(N==null?void 0:N.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Registered"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Bn,{children:de==null?void 0:de.map(Ce=>{var it,Nt;const nt=((it=Ce.profiles)==null?void 0:it.name)||Ce.zoom_name||"Unknown",$t=((Nt=Ce.profiles)==null?void 0:Nt.email)||Ce.zoom_email||null,lt=!Ce.user_id;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,lt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(ft,{children:$t?e.jsxs("a",{href:`mailto:${$t}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Qs,{className:"h-3 w-3"}),$t]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ft,{className:"text-muted-foreground text-sm",children:Ss(new Date(Ce.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(ft,{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(as,{value:"attendees",className:"mt-4",children:ie?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ae==null?void 0:ae.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(N==null?void 0:N.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(ae==null?void 0:ae.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(Hi,{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 (",ae==null?void 0:ae.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:ae==null?void 0:ae.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(G,{variant:"outline",size:"sm",onClick:()=>Ee(Ce),className:"gap-1",children:[e.jsx(rl,{className:"h-3 w-3"}),"Link to Profile"]})]},Ce.id))})]}),e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Points"})]})}),e.jsx(Bn,{children:ae==null?void 0:ae.filter(Ce=>Ce.user_id).map(Ce=>{var lt,it;const nt=((lt=Ce.profiles)==null?void 0:lt.name)||Ce.zoom_name||"Unknown",$t=((it=Ce.profiles)==null?void 0:it.email)||Ce.zoom_email||null;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,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(ft,{children:$t?e.jsxs("a",{href:`mailto:${$t}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Qs,{className:"h-3 w-3"}),$t]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ft,{children:Ce.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(cn,{className:"h-3 w-3"}),Ce.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ft,{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(Zi,{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:T,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(rl,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Fr,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),P&&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:P.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:X,onChange:Ce=>K(Ce.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Se.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:Se.slice(0,20).map(Ce=>e.jsxs("button",{type:"button",onClick:()=>z(Ce.id),className:Bt("w-full p-3 text-left hover:bg-muted/50 transition-colors",B===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))})}),P.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ei,{id:"save-alias",checked:F,onCheckedChange:Ce=>$(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(G,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(G,{onClick:$e,disabled:!B||Pe.isPending,children:Pe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}function Nes({selectedKitIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=gt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:m,error:x}=await H.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(x)throw x;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(x=>x!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(_r,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(Ao,{open:a,onOpenChange:i,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(wo,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(fn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{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(Pl,{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 kes=()=>{const{user:s}=As(),{toast:t}=Ea(),r=es(),[n,a]=Lc(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[m,x]=k.useState(null),[g,v]=k.useState(0),[j,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(""),[P,D]=k.useState([]),[B,z]=k.useState(""),[F,$]=k.useState(""),[X,K]=k.useState(!1),[Q,Y]=k.useState(!1),{data:ne=[]}=gt({queryKey:["template-categories"],queryFn:async()=>{const{data:Re,error:Qe}=await H.from("template_categories").select("*").order("name");if(Qe)throw Qe;return Re}}),{data:de=[]}=gt({queryKey:["template-types"],queryFn:async()=>{const{data:Re,error:Qe}=await H.from("template_types").select("*").order("name");if(Qe)throw Qe;return Re}}),{data:ce=[],isLoading:ae}=gt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Re,error:Qe}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Qe)throw Qe;const{data:Ke,error:Ce}=await H.from("template_links").select("*").order("sort_order");if(Ce)throw Ce;const{data:nt,error:$t}=await H.from("template_guides").select("*").order("sort_order");if($t)throw $t;return Re.map(it=>({...it,links:(Ke==null?void 0:Ke.filter(Nt=>Nt.template_id===it.id))||[],guides:(nt==null?void 0:nt.filter(Nt=>Nt.template_id===it.id))||[]}))}});k.useEffect(()=>{const Re=n.get("edit");if(Re&&ce.length>0){const Qe=ce.find(Ke=>Ke.id===Re);Qe&&(Me(Qe),a({},{replace:!0}))}},[ce,n]);const ie=Lt({mutationFn:async Re=>{const{data:Qe,error:Ke}=await H.from("template_categories").insert({name:Re}).select().single();if(Ke)throw Ke;return Qe},onSuccess:Re=>{r.invalidateQueries({queryKey:["template-categories"]}),h({...d,category_id:Re.id}),z(""),K(!1),t({title:"Category added"})},onError:Re=>{t({title:"Error adding category",description:Re.message,variant:"destructive"})}}),me=Lt({mutationFn:async Re=>{const{data:Qe,error:Ke}=await H.from("template_types").insert({name:Re}).select().single();if(Ke)throw Ke;return Qe},onSuccess:Re=>{r.invalidateQueries({queryKey:["template-types"]}),h({...d,type_id:Re.id}),$(""),Y(!1),t({title:"Type added"})},onError:Re=>{t({title:"Error adding type",description:Re.message,variant:"destructive"})}}),oe=Lt({mutationFn:async Re=>{var $t;let Qe=Re.existingImageUrl;if(Re.image){const lt=Re.image.name.split(".").pop(),it=`${Date.now()}-${Math.random().toString(36).substring(7)}.${lt}`,{error:Nt}=await H.storage.from("template-previews").upload(it,Re.image);if(Nt)throw Nt;const{data:Ft}=H.storage.from("template-previews").getPublicUrl(it);Qe=Ft.publicUrl}const Ke={name:Re.template.name,description:Re.template.description||null,category_id:Re.template.category_id||null,type_id:Re.template.type_id||null,preview_image_url:Qe,video_url:Re.videoUrl||null,publish_date:Re.template.publish_date?new Date(Re.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ce=Re.templateId;if(Ce){const{error:lt}=await H.from("canva_templates").update(Ke).eq("id",Ce);if(lt)throw lt;const{error:it}=await H.from("template_links").delete().eq("template_id",Ce);if(it)throw it;const Nt=(($t=Re.existingGuides)==null?void 0:$t.map(Ie=>Ie.id).filter(Boolean))||[],Ft=Re.template.guides.map(Ie=>Ie.id).filter(Boolean),at=Nt.filter(Ie=>!Ft.includes(Ie));at.length>0&&await H.from("template_guides").delete().in("id",at)}else{const{data:lt,error:it}=await H.from("canva_templates").insert(Ke).select().single();if(it)throw it;Ce=lt.id,yes(Re.template.name,lt.id)}const nt=Re.template.links.filter(lt=>lt.title.trim()&<.canva_share_link.trim());if(nt.length>0){const lt=nt.map((Nt,Ft)=>({template_id:Ce,title:Nt.title.trim(),canva_share_link:Nt.canva_share_link.trim(),sort_order:Ft})),{error:it}=await H.from("template_links").insert(lt);if(it)throw it}for(let lt=0;lt0)){const{error:lt}=await H.from("resource_kit_templates").insert(Re.linkedKitIds.map(it=>({template_id:Ce,kit_id:it})));if(lt)throw lt}},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),Oe(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Re=>{t({title:"Error saving template",description:Re.message,variant:"destructive"})}}),ge=Lt({mutationFn:async Re=>{const{error:Qe}=await H.from("canva_templates").delete().eq("id",Re);if(Qe)throw Qe},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Re=>{t({title:"Error deleting template",description:Re.message,variant:"destructive"})}}),be=Lt({mutationFn:async({id:Re,is_featured:Qe})=>{const{error:Ke}=await H.from("canva_templates").update({is_featured:Qe}).eq("id",Re);if(Ke)throw Ke},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]})},onError:Re=>{t({title:"Error updating featured",description:Re.message,variant:"destructive"})}}),Oe=()=>{h({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),S(null),A(""),c(null),K(!1),Y(!1),z(""),$(""),x(null),v(0),b(!1),D([])},Me=async Re=>{var Ke;c(Re),h({name:Re.name,description:Re.description||"",category_id:Re.category_id||"",type_id:Re.type_id||"",publish_date:Re.publish_date?new Date(Re.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Re.links&&Re.links.length>0?Re.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:((Ke=Re.guides)==null?void 0:Ke.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:Re.video_url||""}),A(Re.preview_image_url||""),x(null);const{data:Qe}=await H.from("resource_kit_templates").select("kit_id").eq("template_id",Re.id);D((Qe||[]).map(Ce=>Ce.kit_id)),l(!0)},Pe=Re=>{var Ke;const Qe=(Ke=Re.target.files)==null?void 0:Ke[0];Qe&&(S(Qe),A(URL.createObjectURL(Qe)))},Ee=()=>{h({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},$e=Re=>{if(d.links.length<=1)return;const Qe=d.links.filter((Ke,Ce)=>Ce!==Re);h({...d,links:Qe})},Se=(Re,Qe,Ke)=>{const Ce=[...d.links];Ce[Re]={...Ce[Re],[Qe]:Ke},h({...d,links:Ce})},ze=Re=>{const Qe=Re.target.files;if(!Qe)return;const Ke=Array.from(Qe).map((Ce,nt)=>({name:Ce.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ce.type,file_size:Ce.size,sort_order:d.guides.length+nt,file:Ce}));h({...d,guides:[...d.guides,...Ke]}),Re.target.value=""},Te=Re=>{const Qe=d.guides.filter((Ke,Ce)=>Ce!==Re);h({...d,guides:Qe})},ye=(Re,Qe)=>{const Ke=[...d.guides];Ke[Re]={...Ke[Re],name:Qe},h({...d,guides:Ke})},ct=async()=>{if(!m)return null;b(!0),v(0);try{const{data:Re,error:Qe}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||m.name}});if(Qe)throw new Error(Qe.message);const{videoId:Ke,libraryId:Ce}=Re,{data:nt,error:$t}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ke}});if($t)throw new Error($t.message);const lt=new XMLHttpRequest;return await new Promise((Nt,Ft)=>{lt.upload.addEventListener("progress",at=>{if(at.lengthComputable){const Ie=Math.round(at.loaded/at.total*100);v(Ie)}}),lt.addEventListener("load",()=>{lt.status>=200&<.status<300?Nt():Ft(new Error(`Upload failed with status ${lt.status}`))}),lt.addEventListener("error",()=>Ft(new Error("Upload failed"))),lt.open("PUT",nt.uploadUrl),lt.setRequestHeader("AccessKey",nt.apiKey),lt.send(m)}),`https://player.mediadelivery.net/embed/${Ce}/${Ke}`}catch(Re){return console.error("Bunny upload error:",Re),t({title:"Video upload failed",description:Re instanceof Error?Re.message:"Unknown error",variant:"destructive"}),null}finally{b(!1)}},ve=Re=>{var Ke;const Qe=(Ke=Re.target.files)==null?void 0:Ke[0];Qe&&x(Qe),Re.target.value=""},rt=async Re=>{if(Re.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 Ke=d.video_url;if(m){const Ce=await ct();if(!Ce)return;Ke=Ce}oe.mutate({template:d,image:N,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:Ke,linkedKitIds:P})};return e.jsx(_s,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.length})})]})]}),e.jsxs(vs,{open:i,onOpenChange:Re=>{l(Re),Re||Oe()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:rt,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name *"}),e.jsx(ke,{id:"name",value:d.name,onChange:Re=>h({...d,name:Re.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:d.description,onChange:Re=>h({...d,description:Re}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Canva Links *"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Ee,className:"gap-1",children:[e.jsx(Ws,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Re,Qe)=>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(ke,{value:Re.title,onChange:Ke=>Se(Qe,"title",Ke.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(ke,{value:Re.canva_share_link,onChange:Ke=>Se(Qe,"canva_share_link",Ke.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>$e(Qe),children:e.jsx(_r,{className:"h-4 w-4"})})]},Qe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Category"}),X?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:B,onChange:Re=>z(Re.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>B.trim()&&ie.mutate(B.trim()),disabled:ie.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{K(!1),z("")},children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{value:d.category_id,onValueChange:Re=>h({...d,category_id:Re}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:ne.map(Re=>e.jsx(mt,{value:Re.id,children:Re.name},Re.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>K(!0),children:e.jsx(Ws,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Template Type"}),Q?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:F,onChange:Re=>$(Re.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>F.trim()&&me.mutate(F.trim()),disabled:me.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Y(!1),$("")},children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{value:d.type_id,onValueChange:Re=>h({...d,type_id:Re}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select type"})}),e.jsx(Fs,{children:de.map(Re=>e.jsx(mt,{value:Re.id,children:Re.name},Re.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>Y(!0),children:e.jsx(Ws,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:d.publish_date,onChange:Re=>h({...d,publish_date:Re.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[T?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:T,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(G,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{S(null),A("")},children:e.jsx(_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(fl,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ke,{type:"file",accept:"image/*",onChange:Pe,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Video (Optional)"}),d.video_url&&!m?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(sn,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>h({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):j?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... ",g,"%"]})]}),e.jsx(ri,{value:g,className:"h-2"})]}):m?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(sn,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:m.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(m.size/1024/1024).toFixed(1)," MB"]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>x(null),children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ke,{type:"file",accept:"video/*",onChange:ve,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(sn,{className:"h-8 w-8 text-muted-foreground/50"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Click to upload a video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a video to embed on the template page (Bunny.net)"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ke,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:ze,className:"hidden"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Re,Qe)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(ln,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(ke,{value:Re.name,onChange:Ke=>ye(Qe,Ke.target.value),placeholder:"Guide name",className:"flex-1"}),Re.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Re.file_size/1024).toFixed(0)," KB"]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Te(Qe),children:e.jsx(_r,{className:"h-4 w-4"})})]},Re.id||Qe))}):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(Nes,{selectedKitIds:P,onChange:D}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>{l(!1),Oe()},children:"Cancel"}),e.jsx(G,{type:"submit",disabled:oe.isPending,children:oe.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ce.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:ce.map(Re=>{var Qe,Ke,Ce,nt,$t;return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Re.preview_image_url?e.jsx("img",{src:Re.preview_image_url,alt:Re.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(fl,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(ft,{className:"font-medium",children:Re.name}),e.jsx(ft,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Ge,{variant:"secondary",children:[((Qe=Re.links)==null?void 0:Qe.length)||0," link",(((Ke=Re.links)==null?void 0:Ke.length)||0)!==1?"s":""]}),(((Ce=Re.guides)==null?void 0:Ce.length)||0)>0&&e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),(nt=Re.guides)==null?void 0:nt.length," guide",((($t=Re.guides)==null?void 0:$t.length)||0)!==1?"s":""]})]})}),e.jsx(ft,{children:Re.category?e.jsx(Ge,{variant:"secondary",children:Re.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ft,{children:Re.type?e.jsx(Ge,{variant:"outline",children:Re.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ft,{className:"text-muted-foreground",children:new Date(Re.publish_date).toLocaleDateString()}),e.jsx(ft,{className:"text-center",children:e.jsx(G,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Re.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>be.mutate({id:Re.id,is_featured:!Re.is_featured}),children:e.jsx(Qn,{className:`h-4 w-4 ${Re.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>Me(Re),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&ge.mutate(Re.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Re.id)})})]})})})]})})};function ect({selectedTemplateIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=gt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:m,error:x}=await H.from("canva_templates").select("id, name, preview_image_url").order("name");if(x)throw x;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(x=>x!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(M3,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(_r,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(Ao,{open:a,onOpenChange:i,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(M3,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(wo,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(fn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{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(M3,{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 Ses=[{value:"bunny_stream",label:"Bunny.net Stream (Upload)"},{value:"youtube",label:"YouTube"},{value:"vimeo",label:"Vimeo"},{value:"google_drive",label:"Google Drive"},{value:"amazon_s3",label:"Amazon S3"},{value:"loom",label:"Loom"},{value:"other",label:"Other"}],Ces=()=>{const{user:s}=As(),[t,r]=Lc(),{toast:n}=Ea(),a=es(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[m,x]=k.useState(null),[g,v]=k.useState(""),[j,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState([]),[P,D]=k.useState([]),[B,z]=k.useState(""),[F,$]=k.useState(!1),[X,K]=k.useState(null),[Q,Y]=k.useState(0),[ne,de]=k.useState(!1),[ce,ae]=k.useState(null),{data:ie=[]}=gt({queryKey:["academy-categories"],queryFn:async()=>{const{data:ve,error:rt}=await H.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(rt)throw rt;return ve}}),{data:me=[],isLoading:oe}=gt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:ve,error:rt}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(rt)throw rt;const{data:Re,error:Qe}=await H.from("academy_resources").select("*").order("sort_order");if(Qe)throw Qe;return ve.map(Ce=>({...Ce,resources:(Re==null?void 0:Re.filter(nt=>nt.video_id===Ce.id))||[]}))}});k.useEffect(()=>{const ve=t.get("edit");if(ve&&me.length>0){const rt=me.find(Re=>Re.id===ve);rt&&(Ee(rt),r({},{replace:!0}))}},[me,t]);const ge=Lt({mutationFn:async ve=>{const{data:rt,error:Re}=await H.from("academy_categories").insert({name:ve,sort_order:ie.length}).select().single();if(Re)throw Re;return rt},onSuccess:ve=>{a.invalidateQueries({queryKey:["academy-categories"]}),h({...d,category_id:ve.id}),z(""),$(!1),n({title:"Category added"})},onError:ve=>{n({title:"Error adding category",description:ve.message,variant:"destructive"})}}),be=Lt({mutationFn:async ve=>{let rt=ve.existingThumbnailUrl;if(ve.thumbnail){const Ke=ve.thumbnail.name.split(".").pop(),Ce=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ke}`,{error:nt}=await H.storage.from("academy-resources").upload(Ce,ve.thumbnail);if(nt)throw nt;const{data:$t}=H.storage.from("academy-resources").getPublicUrl(Ce);rt=$t.publicUrl}const Re={title:ve.video.title,description:ve.video.description||null,video_url:ve.video.video_url,video_type:ve.video.video_type,duration:ve.video.duration||null,thumbnail_url:rt,category_id:ve.video.category_id||null,publish_date:ve.video.publish_date?new Date(ve.video.publish_date).toISOString():new Date().toISOString(),is_published:ve.video.is_published,created_by:s==null?void 0:s.id};let Qe=ve.videoId;if(Qe){const{error:Ke}=await H.from("academy_videos").update(Re).eq("id",Qe);if(Ke)throw Ke}else{const{data:Ke,error:Ce}=await H.from("academy_videos").insert(Re).select().single();if(Ce)throw Ce;Qe=Ke.id,ves(ve.video.title,Ke.id)}if(ve.resourcesToDelete.length>0){const{error:Ke}=await H.from("academy_resources").delete().in("id",ve.resourcesToDelete);if(Ke)throw Ke}for(let Ke=0;Ke0){const{error:Ke}=await H.from("academy_video_templates").insert(P.map(Ce=>({video_id:Qe,template_id:Ce})));if(Ke)throw Ke}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Pe(),l(!1),n({title:o?"Video updated":"Video created"})},onError:ve=>{n({title:"Error saving video",description:ve.message,variant:"destructive"})}}),Oe=Lt({mutationFn:async ve=>{const{error:rt}=await H.from("academy_videos").delete().eq("id",ve);if(rt)throw rt},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),n({title:"Video deleted"})},onError:ve=>{n({title:"Error deleting video",description:ve.message,variant:"destructive"})}}),Me=Lt({mutationFn:async({id:ve,is_published:rt})=>{const{error:Re}=await H.from("academy_videos").update({is_published:rt}).eq("id",ve);if(Re)throw Re},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:ve=>{n({title:"Error updating video",description:ve.message,variant:"destructive"})}}),Pe=()=>{h({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),x(null),v(""),b([]),S([]),A([]),c(null),D([]),z(""),K(null),Y(0),de(!1),ae(null)},Ee=async ve=>{c(ve),h({title:ve.title,description:ve.description||"",video_url:ve.video_url,video_type:ve.video_type,duration:ve.duration||"",category_id:ve.category_id||"",publish_date:ve.publish_date?new Date(ve.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:ve.is_published}),v(ve.thumbnail_url||""),S(ve.resources||[]),b([]),A([]);const{data:rt}=await H.from("academy_video_templates").select("template_id").eq("video_id",ve.id);D((rt||[]).map(Re=>Re.template_id)),l(!0)},$e=ve=>{var Re;const rt=(Re=ve.target.files)==null?void 0:Re[0];rt&&(x(rt),v(URL.createObjectURL(rt)))},Se=ve=>{const rt=ve.target.files;if(rt){const Re=Array.from(rt).map(Qe=>({file:Qe,title:Qe.name.replace(/\.[^/.]+$/,"")}));b([...j,...Re])}ve.target.value=""},ze=ve=>{b(j.filter((rt,Re)=>Re!==ve))},Te=ve=>{A([...T,ve]),S(N.filter(rt=>rt.id!==ve))},ye=async()=>{if(!X)return null;de(!0),Y(0);try{const{data:ve,error:rt}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||X.name}});if(rt)throw new Error(rt.message);const{videoId:Re,libraryId:Qe}=ve;ae(Re);const{data:Ke,error:Ce}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Re}});if(Ce)throw new Error(Ce.message);const nt=new XMLHttpRequest;return await new Promise((lt,it)=>{nt.upload.addEventListener("progress",Nt=>{if(Nt.lengthComputable){const Ft=Math.round(Nt.loaded/Nt.total*100);Y(Ft)}}),nt.addEventListener("load",()=>{nt.status>=200&&nt.status<300?lt():it(new Error(`Upload failed with status ${nt.status}`))}),nt.addEventListener("error",()=>it(new Error("Upload failed"))),nt.open("PUT",Ke.uploadUrl),nt.setRequestHeader("AccessKey",Ke.apiKey),nt.send(X)}),`https://player.mediadelivery.net/embed/${Qe}/${Re}`}catch(ve){return console.error("Bunny upload error:",ve),n({title:"Video upload failed",description:ve instanceof Error?ve.message:"Unknown error",variant:"destructive"}),null}finally{de(!1)}},ct=async ve=>{if(ve.preventDefault(),!d.title.trim()){n({title:"Please enter a video title",variant:"destructive"});return}let rt=d.video_url;if(d.video_type==="bunny_stream"&&X&&!o){const Re=await ye();if(!Re)return;rt=Re}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"&&!X&&!d.video_url&&!o){n({title:"Please select a video file to upload",variant:"destructive"});return}be.mutate({video:{...d,video_url:rt},thumbnail:m,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:j,resourcesToDelete:T})};return e.jsx(_s,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.filter(ve=>ve.is_published).length})})]})]}),e.jsxs(vs,{open:i,onOpenChange:ve=>{l(ve),ve||Pe()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:ct,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:d.title,onChange:ve=>h({...d,title:ve.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:d.description,onChange:ve=>h({...d,description:ve}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Video Type"}),e.jsxs(zs,{value:d.video_type,onValueChange:ve=>{h({...d,video_type:ve,video_url:""}),K(null)},disabled:ne,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:Ses.map(ve=>e.jsx(mt,{value:ve.value,children:ve.label},ve.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{type:"file",accept:"video/*",onChange:ve=>{var Re;const rt=(Re=ve.target.files)==null?void 0:Re[0];rt&&K(rt)},disabled:ne}),X&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(sn,{className:"h-4 w-4"}),X.name," (",(X.size/(1024*1024)).toFixed(1)," MB)"]}),ne&&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(ri,{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(he,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(ke,{id:"video_url",value:d.video_url,onChange:ve=>h({...d,video_url:ve.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"duration",children:"Duration"}),e.jsx(ke,{id:"duration",value:d.duration,onChange:ve=>h({...d,duration:ve.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:d.publish_date,onChange:ve=>h({...d,publish_date:ve.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:B,onChange:ve=>z(ve.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>B.trim()&&ge.mutate(B.trim()),disabled:ge.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{$(!1),z("")},children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{value:d.category_id,onValueChange:ve=>h({...d,category_id:ve}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:ie.map(ve=>e.jsx(mt,{value:ve.id,children:ve.name},ve.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>$(!0),children:e.jsx(Ws,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[g&&e.jsx("img",{src:g,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ke,{type:"file",accept:"image/*",onChange:$e,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Recommended: 16:9 aspect ratio"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Resource Files"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(oa,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Se,className:"hidden"})]})})]}),(N.length>0||j.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[N.map(ve=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:ve.title}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:ve.file_type}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>Te(ve.id),className:"text-destructive hover:text-destructive",children:e.jsx(_r,{className:"h-4 w-4"})})]},ve.id)),j.map((ve,rt)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:ve.title,onChange:Re=>{const Qe=[...j];Qe[rt].title=Re.target.value,b(Qe)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>ze(rt),className:"text-destructive hover:text-destructive",children:e.jsx(_r,{className:"h-4 w-4"})})]},rt))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(ect,{selectedTemplateIds:P,onChange:D}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"is_published",checked:d.is_published,onCheckedChange:ve=>h({...d,is_published:ve})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:ne,children:"Cancel"}),e.jsx(G,{type:"submit",disabled:be.isPending||ne,children:ne?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):be.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:oe?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):me.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(sn,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(Bn,{children:me.map(ve=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.thumbnail_url?e.jsx("img",{src:ve.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(sn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ve.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:ve.video_type.replace("_"," ")})]})]})}),e.jsx(ft,{children:ve.category?e.jsx(Ge,{variant:"outline",children:ve.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ft,{children:ve.duration||"-"}),e.jsx(ft,{children:ve.resources&&ve.resources.length>0?e.jsxs(Ge,{variant:"secondary",children:[ve.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ft,{children:new Date(ve.publish_date).toLocaleDateString()}),e.jsx(ft,{children:e.jsx(br,{checked:ve.is_published,onCheckedChange:rt=>Me.mutate({id:ve.id,is_published:rt})})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Ee(ve),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Oe.mutate(ve.id),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},ve.id))})]})})})]})})};function Tes(){var be,Oe,Me;const s=es(),[t,r]=Lc(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=k.useState(null),[m,x]=k.useState(""),[g,v]=k.useState([]),[j,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState(null),{data:P,isLoading:D}=gt({queryKey:["resource-kits"],queryFn:async()=>{const{data:Pe,error:Ee}=await H.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return Pe}}),{data:B}=gt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Pe,error:Ee}=await H.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return Pe}}),{data:z}=gt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Pe,error:Ee}=await H.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return Pe}});k.useEffect(()=>{const Pe=t.get("edit");if(Pe&&P&&P.length>0&&B&&z){const Ee=P.find($e=>$e.id===Pe);Ee&&($(Ee),r({},{replace:!0}))}},[P,B,z,t]);const F=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),x(""),v([]),b([]),S([]),l(null)},$=async Pe=>{l(Pe),c({name:Pe.name,description:Pe.description||"",publish_date:Pe.publish_date.split("T")[0],is_published:Pe.is_published}),x(Pe.featured_image_url||"");const Ee=(B==null?void 0:B.filter(ze=>ze.kit_id===Pe.id))||[];v(Ee.map(ze=>({id:ze.id,name:ze.name,file_url:ze.file_url,file_type:ze.file_type,file_size:ze.file_size,sort_order:ze.sort_order})));const $e=(z==null?void 0:z.filter(ze=>ze.kit_id===Pe.id))||[];b($e.map(ze=>({id:ze.id,title:ze.title,canva_share_link:ze.canva_share_link,sort_order:ze.sort_order})));const{data:Se}=await H.from("resource_kit_templates").select("template_id").eq("kit_id",Pe.id);S((Se||[]).map(ze=>ze.template_id)),a(!0)},X=Pe=>{var $e;const Ee=($e=Pe.target.files)==null?void 0:$e[0];Ee&&(h(Ee),x(URL.createObjectURL(Ee)))},K=()=>{v([...g,{name:"",file_url:"",sort_order:g.length}])},Q=Pe=>{v(g.filter((Ee,$e)=>$e!==Pe))},Y=(Pe,Ee,$e)=>{const Se=[...g];Se[Pe]={...Se[Pe],[Ee]:$e},v(Se)},ne=()=>{b([...j,{title:"",canva_share_link:"",sort_order:j.length}])},de=Pe=>{b(j.filter((Ee,$e)=>$e!==Pe))},ce=(Pe,Ee,$e)=>{const Se=[...j];Se[Pe]={...Se[Pe],[Ee]:$e},b(Se)},ae=(Pe,Ee)=>{var Se;const $e=(Se=Ee.target.files)==null?void 0:Se[0];if($e){const ze=[...g],Te=$e.name.replace(/\.[^/.]+$/,"");ze[Pe]={...ze[Pe],file:$e,file_type:$e.type,file_size:$e.size,name:ze[Pe].name||Te},v(ze)}},ie=Lt({mutationFn:async()=>{let Pe=(i==null?void 0:i.featured_image_url)||null;if(d){const Te=d.name.split(".").pop(),ye=`${Date.now()}.${Te}`,{error:ct}=await H.storage.from("resource-kits").upload(`featured/${ye}`,d);if(ct)throw ct;const{data:ve}=H.storage.from("resource-kits").getPublicUrl(`featured/${ye}`);Pe=ve.publicUrl}const Ee={name:o.name,description:o.description||null,featured_image_url:Pe,publish_date:o.publish_date,is_published:o.is_published};let $e;const Se=!i,ze=(i==null?void 0:i.is_published)||!1;if(i){const{error:Te}=await H.from("resource_kits").update(Ee).eq("id",i.id);if(Te)throw Te;$e=i.id;const ye=(B==null?void 0:B.filter(Ke=>Ke.kit_id===i.id).map(Ke=>Ke.id))||[],ct=g.filter(Ke=>Ke.id).map(Ke=>Ke.id),ve=ye.filter(Ke=>!ct.includes(Ke));ve.length>0&&await H.from("resource_kit_files").delete().in("id",ve);const rt=(z==null?void 0:z.filter(Ke=>Ke.kit_id===i.id).map(Ke=>Ke.id))||[],Re=j.filter(Ke=>Ke.id).map(Ke=>Ke.id),Qe=rt.filter(Ke=>!Re.includes(Ke));Qe.length>0&&await H.from("resource_kit_links").delete().in("id",Qe)}else{const{data:Te,error:ye}=await H.from("resource_kits").insert(Ee).select().single();if(ye)throw ye;$e=Te.id}for(let Te=0;Te0){const{error:Te}=await H.from("resource_kit_templates").insert(N.map(ye=>({kit_id:$e,template_id:ye})));if(Te)throw Te}return{kitId:$e,kitName:o.name,isNewKit:Se,wasPublished:ze,isPublished:o.is_published}},onSuccess:Pe=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ue.success(i?"Resource kit updated":"Resource kit created"),Pe.isPublished&&(Pe.isNewKit||!Pe.wasPublished)&&_es(Pe.kitName,Pe.kitId),a(!1),F()},onError:Pe=>{ue.error("Failed to save resource kit: "+Pe.message)}}),me=Lt({mutationFn:async Pe=>{const{error:Ee}=await H.from("resource_kits").delete().eq("id",Pe);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ue.success("Resource kit deleted")},onError:Pe=>{ue.error("Failed to delete: "+Pe.message)}}),oe=Pe=>{if(Pe.preventDefault(),!o.name){ue.error("Please enter a name");return}ie.mutate()},ge=Pe=>(B==null?void 0:B.filter(Ee=>Ee.kit_id===Pe).length)||0;return e.jsx(_s,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.filter(Pe=>Pe.is_published).length)||0})})]})]}),e.jsxs(G,{onClick:()=>{F(),a(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Files"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:D?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):P==null?void 0:P.map(Pe=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Pe.featured_image_url?e.jsx("img",{src:Pe.featured_image_url,alt:Pe.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(Pl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Pe.name}),Pe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Pe.description})]})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),ge(Pe.id)]})}),e.jsx(ft,{children:Ss(new Date(Pe.publish_date),"MMM d, yyyy")}),e.jsx(ft,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Pe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Pe.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(B==null?void 0:B.filter(Se=>Se.kit_id===Pe.id))||[],$e=(z==null?void 0:z.filter(Se=>Se.kit_id===Pe.id))||[];A({...Pe,files:Ee,links:$e})},children:e.jsx(jn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>$(Pe),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&me.mutate(Pe.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},Pe.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(js,{children:e.jsx(bs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:oe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[m?e.jsx("img",{src:m,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(Pl,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ke,{type:"file",accept:"image/*",onChange:X})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name *"}),e.jsx(ke,{id:"name",value:o.name,onChange:Pe=>c({...o,name:Pe.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:o.description,onChange:Pe=>c({...o,description:Pe}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:o.publish_date,onChange:Pe=>c({...o,publish_date:Pe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(br,{checked:o.is_published,onCheckedChange:Pe=>c({...o,is_published:Pe})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Resource Files"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:K,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),g.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:g.map((Pe,Ee)=>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 ",Ee+1]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(Ee),children:e.jsx(_r,{className:"h-4 w-4"})})]}),e.jsx(ke,{placeholder:"File name (e.g., Getting Started Guide)",value:Pe.name,onChange:$e=>Y(Ee,"name",$e.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"file",onChange:$e=>ae(Ee,$e),className:"flex-1"}),Pe.file_url&&!Pe.file&&e.jsx("a",{href:Pe.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Pe.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ee))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:ne,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),j.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:j.map((Pe,Ee)=>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 ",Ee+1]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>de(Ee),children:e.jsx(_r,{className:"h-4 w-4"})})]}),e.jsx(ke,{placeholder:"Link title (e.g., Social Media Post Template)",value:Pe.title,onChange:$e=>ce(Ee,"title",$e.target.value)}),e.jsx(ke,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Pe.canva_share_link,onChange:$e=>ce(Ee,"canva_share_link",$e.target.value)})]},Ee))})]}),e.jsx(ect,{selectedTemplateIds:N,onChange:S}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:ie.isPending,children:ie.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(vs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(bs,{children:T==null?void 0:T.name})}),e.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.featured_image_url)&&e.jsx("img",{src:T.featured_image_url,alt:T.name,className:"w-full h-48 object-cover rounded-lg"}),(T==null?void 0:T.description)&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((be=T==null?void 0:T.files)==null?void 0:be.length)||0,")"]}),((Oe=T==null?void 0:T.files)==null?void 0:Oe.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=T==null?void 0:T.files)==null?void 0:Me.map(Pe=>e.jsxs("a",{href:Pe.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(ln,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Pe.name})]},Pe.id))})]}),(T==null?void 0:T.links)&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.links.map(Pe=>e.jsxs("a",{href:Pe.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(xo,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Pe.title})]},Pe.id))})]})]})]})})]})})}const Ees=()=>{const{user:s}=As(),{toast:t}=Ea(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,h]=k.useState(null),[m,x]=k.useState(""),{data:g=[],isLoading:v}=gt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:z,error:F}=await H.from("social_swag").select("*").order("publish_date",{ascending:!1});if(F)throw F;const{data:$,error:X}=await H.from("social_swag_links").select("*").order("sort_order");if(X)throw X;return z.map(Q=>({...Q,links:($==null?void 0:$.filter(Y=>Y.swag_id===Q.id))||[]}))}}),j=Lt({mutationFn:async z=>{let F=z.existingImageUrl;if(z.image){const ne=z.image.name.split(".").pop(),de=`${Date.now()}-${Math.random().toString(36).substring(7)}.${ne}`,{error:ce}=await H.storage.from("template-previews").upload(de,z.image);if(ce)throw ce;const{data:ae}=H.storage.from("template-previews").getPublicUrl(de);F=ae.publicUrl}const $={title:z.item.title,description:z.item.description||null,preview_image_url:F,publish_date:z.item.publish_date?new Date(z.item.publish_date).toISOString():new Date().toISOString(),is_published:z.item.is_published,created_by:s==null?void 0:s.id};let X=z.itemId;const K=!X,Q=(i==null?void 0:i.is_published)||!1;if(X){const{error:ne}=await H.from("social_swag").update($).eq("id",X);if(ne)throw ne;await H.from("social_swag_links").delete().eq("swag_id",X)}else{const{data:ne,error:de}=await H.from("social_swag").insert($).select().single();if(de)throw de;X=ne.id}const Y=z.item.links.filter(ne=>ne.title.trim()&&ne.canva_share_link.trim());if(Y.length>0){const ne=Y.map((ce,ae)=>({swag_id:X,title:ce.title.trim(),canva_share_link:ce.canva_share_link.trim(),sort_order:ae})),{error:de}=await H.from("social_swag_links").insert(ne);if(de)throw de}return{itemId:X,itemTitle:z.item.title,isNewItem:K,wasPublished:Q,isPublished:z.item.is_published}},onSuccess:z=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),z.isPublished&&(z.isNewItem||!z.wasPublished)&&FNe(z.itemTitle,z.itemId),a(!1),N()},onError:z=>{t({title:"Error saving item",description:z.message,variant:"destructive"})}}),b=Lt({mutationFn:async z=>{const{error:F}=await H.from("social_swag").delete().eq("id",z);if(F)throw F},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:z=>{t({title:"Error deleting item",description:z.message,variant:"destructive"})}}),N=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),h(null),x(""),l(null)},S=z=>{l(z),c({title:z.title,description:z.description||"",publish_date:z.publish_date?new Date(z.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:z.is_published,links:z.links&&z.links.length>0?z.links.map(F=>({id:F.id,title:F.title,canva_share_link:F.canva_share_link,sort_order:F.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),x(z.preview_image_url||""),a(!0)},T=z=>{var $;const F=($=z.target.files)==null?void 0:$[0];F&&(h(F),x(URL.createObjectURL(F)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},P=z=>{if(o.links.length<=1)return;const F=o.links.filter(($,X)=>X!==z);c({...o,links:F})},D=(z,F,$)=>{const X=[...o.links];X[z]={...X[z],[F]:$},c({...o,links:X})},B=z=>{if(z.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}j.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(_s,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:g.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:g.filter(z=>z.is_published).length})})]})]}),e.jsxs(vs,{open:n,onOpenChange:z=>{a(z),z||N()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:B,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:o.title,onChange:z=>c({...o,title:z.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:o.description,onChange:z=>c({...o,description:z}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:o.publish_date,onChange:z=>c({...o,publish_date:z.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(br,{id:"is_published",checked:o.is_published,onCheckedChange:z=>c({...o,is_published:z})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),x("")},children:e.jsx(_r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(fl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ke,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((z,F)=>e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",F+1]}),o.links.length>1&&e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>P(F),children:e.jsx(_r,{className:"h-3 w-3"})})]}),e.jsx(ke,{placeholder:"Link title (e.g., Instagram Post)",value:z.title,onChange:$=>D(F,"title",$.target.value)}),e.jsx(ke,{placeholder:"Canva share link",value:z.canva_share_link,onChange:$=>D(F,"canva_share_link",$.target.value)})]})},F))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:j.isPending,children:j.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:v?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):g.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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:g.map(z=>{var F;return e.jsxs(qs,{children:[e.jsx(ft,{children:z.preview_image_url?e.jsx("img",{src:z.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(fl,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(ft,{className:"font-medium",children:z.title}),e.jsxs(ft,{children:[((F=z.links)==null?void 0:F.length)||0," links"]}),e.jsx(ft,{children:new Date(z.publish_date).toLocaleDateString()}),e.jsx(ft,{children:e.jsx(Ge,{variant:z.is_published?"default":"secondary",children:z.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${z.id}`,"_blank"),children:e.jsx(jn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S(z),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&b.mutate(z.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},z.id)})})]})})})]})})};function Aes(){for(var s=arguments.length,t=new Array(s),r=0;rn=>{t.forEach(a=>a(n))},t)}const jxe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function OP(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function qTe(s){return"nodeType"in s}function _p(s){var t,r;return s?OP(s)?s:qTe(s)&&(t=(r=s.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function VTe(s){const{Document:t}=_p(s);return s instanceof t}function pz(s){return OP(s)?!1:s instanceof _p(s).HTMLElement}function tct(s){return s instanceof _p(s).SVGElement}function FP(s){return s?OP(s)?s.document:qTe(s)?VTe(s)?s:pz(s)||tct(s)?s.ownerDocument:document:document:document}const l1=jxe?k.useLayoutEffect:k.useEffect;function HTe(s){const t=k.useRef(s);return l1(()=>{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 wF(s,t){t===void 0&&(t=[s]);const r=k.useRef(s);return l1(()=>{r.current!==s&&(r.current=s)},t),r}function xz(s,t){const r=k.useRef();return k.useMemo(()=>{const n=s(r.current);return r.current=n,n},[...t])}function Khe(s){const t=HTe(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 BNe(s){const t=k.useRef();return k.useEffect(()=>{t.current=s},[s]),t.current}let Pbe={};function gz(s,t){return k.useMemo(()=>{if(t)return t;const r=Pbe[s]==null?0:Pbe[s]+1;return Pbe[s]=r,s+"-"+r},[s,t])}function sct(s){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const h=i[c];h!=null&&(i[c]=h+s*d)}return i},{...t})}}const EM=sct(1),jF=sct(-1);function Ies(s){return"clientX"in s&&"clientY"in s}function GTe(s){if(!s)return!1;const{KeyboardEvent:t}=_p(s.target);return t&&s instanceof t}function Pes(s){if(!s)return!1;const{TouchEvent:t}=_p(s.target);return t&&s instanceof t}function zNe(s){if(Pes(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:r}=s.touches[0];return{x:t,y:r}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:r}=s.changedTouches[0];return{x:t,y:r}}}return Ies(s)?{x:s.clientX,y:s.clientY}:null}const A2=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[A2.Translate.toString(s),A2.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:r,easing:n}=s;return t+" "+r+"ms "+n}}}),Oze="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Les(s){return s.matches(Oze)?s:s.querySelector(Oze)}const Des={display:"none"};function Res(s){let{id:t,value:r}=s;return wt.createElement("div",{id:t,style:Des},r)}function Oes(s){let{id:t,announcement:r,ariaLiveType:n="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return wt.createElement("div",{id:t,style:a,role:"status","aria-live":n,"aria-atomic":!0},r)}function Fes(){const[s,t]=k.useState("");return{announce:k.useCallback(n=>{n!=null&&t(n)},[]),announcement:s}}const rct=k.createContext(null);function Bes(s){const t=k.useContext(rct);k.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function zes(){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 $es={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. `},Ues={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 qes(s){let{announcements:t=Ues,container:r,hiddenTextDescribedById:n,screenReaderInstructions:a=$es}=s;const{announce:i,announcement:l}=Fes(),o=gz("DndLiveRegion"),[c,d]=k.useState(!1);if(k.useEffect(()=>{d(!0)},[]),Bes(k.useMemo(()=>({onDragStart(m){let{active:x}=m;i(t.onDragStart({active:x}))},onDragMove(m){let{active:x,over:g}=m;t.onDragMove&&i(t.onDragMove({active:x,over:g}))},onDragOver(m){let{active:x,over:g}=m;i(t.onDragOver({active:x,over:g}))},onDragEnd(m){let{active:x,over:g}=m;i(t.onDragEnd({active:x,over:g}))},onDragCancel(m){let{active:x,over:g}=m;i(t.onDragCancel({active:x,over:g}))}}),[i,t])),!c)return null;const h=wt.createElement(wt.Fragment,null,wt.createElement(Res,{id:n,value:a.draggable}),wt.createElement(Oes,{id:o,announcement:l}));return r?pf.createPortal(h,r):h}var zu;(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"})(zu||(zu={}));function Yhe(){}function CI(s,t){return k.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function Nxe(){for(var s=arguments.length,t=new Array(s),r=0;r[...t].filter(n=>n!=null),[...t])}const p0=Object.freeze({x:0,y:0});function nct(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function act(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return r-n}function Ves(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return n-r}function Fze(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 ict(s,t){if(!s||s.length===0)return null;const[r]=s;return r[t]}function Bze(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 kxe=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=Bze(t,t.left,t.top),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=nct(Bze(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(act)},Hes=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=Fze(t),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=Fze(c),h=a.reduce((x,g,v)=>x+nct(d[v],g),0),m=Number((h/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:m}})}}return i.sort(act)};function Ges(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=Ges(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Ves)};function Kes(s,t,r){return{...s,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function oct(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:p0}function Yes(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 Zes=Yes(1);function Xes(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 Qes(s,t,r){const n=Xes(t);if(!n)return s;const{scaleX:a,scaleY:i,x:l,y:o}=n,c=s.left-l-(1-a)*parseFloat(r),d=s.top-o-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),h=a?s.width/a:s.width,m=i?s.height/i:s.height;return{width:h,height:m,top:d,right:c+h,bottom:d+m,left:c}}const Jes={ignoreTransform:!1};function BP(s,t){t===void 0&&(t=Jes);let r=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:h}=_p(s).getComputedStyle(s);d&&(r=Qes(r,d,h))}const{top:n,left:a,width:i,height:l,bottom:o,right:c}=r;return{top:n,left:a,width:i,height:l,bottom:o,right:c}}function zze(s){return BP(s,{ignoreTransform:!0})}function ets(s){const t=s.innerWidth,r=s.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function tts(s,t){return t===void 0&&(t=_p(s).getComputedStyle(s)),t.position==="fixed"}function sts(s,t){t===void 0&&(t=_p(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 Sxe(s,t){const r=[];function n(a){if(t!=null&&r.length>=t||!a)return r;if(VTe(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!pz(a)||tct(a)||r.includes(a))return r;const i=_p(s).getComputedStyle(a);return a!==s&&sts(a,i)&&r.push(a),tts(a,i)?r:n(a.parentNode)}return s?n(s):r}function lct(s){const[t]=Sxe(s,1);return t??null}function Lbe(s){return!jxe||!s?null:OP(s)?s:qTe(s)?VTe(s)||s===FP(s).scrollingElement?window:pz(s)?s:null:null}function cct(s){return OP(s)?s.scrollX:s.scrollLeft}function dct(s){return OP(s)?s.scrollY:s.scrollTop}function $Ne(s){return{x:cct(s),y:dct(s)}}var _h;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(_h||(_h={}));function uct(s){return!jxe||!s?!1:s===document.scrollingElement}function hct(s){const t={x:0,y:0},r=uct(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 rts={x:.2,y:.2};function nts(s,t,r,n,a){let{top:i,left:l,right:o,bottom:c}=r;n===void 0&&(n=10),a===void 0&&(a=rts);const{isTop:d,isBottom:h,isLeft:m,isRight:x}=hct(s),g={x:0,y:0},v={x:0,y:0},j={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+j.height?(g.y=_h.Backward,v.y=n*Math.abs((t.top+j.height-i)/j.height)):!h&&c>=t.bottom-j.height&&(g.y=_h.Forward,v.y=n*Math.abs((t.bottom-j.height-c)/j.height)),!x&&o>=t.right-j.width?(g.x=_h.Forward,v.x=n*Math.abs((t.right-j.width-o)/j.width)):!m&&l<=t.left+j.width&&(g.x=_h.Backward,v.x=n*Math.abs((t.left+j.width-l)/j.width)),{direction:g,speed:v}}function ats(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 mct(s){return s.reduce((t,r)=>EM(t,$Ne(r)),p0)}function its(s){return s.reduce((t,r)=>t+cct(r),0)}function ots(s){return s.reduce((t,r)=>t+dct(r),0)}function lts(s,t){if(t===void 0&&(t=BP),!s)return;const{top:r,left:n,bottom:a,right:i}=t(s);lct(s)&&(a<=0||i<=0||r>=window.innerHeight||n>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const cts=[["x",["left","right"],its],["y",["top","bottom"],ots]];class WTe{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=Sxe(r),a=mct(n);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of cts)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(n),h=a[i]-d;return this.rect[c]+h},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class u8{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 dts(s){const{EventTarget:t}=_p(s);return s instanceof t?s:FP(s)}function Dbe(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 Sg;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Sg||(Sg={}));function $ze(s){s.preventDefault()}function uts(s){s.stopPropagation()}var To;(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"})(To||(To={}));const fct={start:[To.Space,To.Enter],cancel:[To.Esc],end:[To.Space,To.Enter,To.Tab]},hts=(s,t)=>{let{currentCoordinates:r}=t;switch(s.code){case To.Right:return{...r,x:r.x+25};case To.Left:return{...r,x:r.x-25};case To.Down:return{...r,y:r.y+25};case To.Up:return{...r,y:r.y-25}}};class Cxe{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 u8(FP(r)),this.windowListeners=new u8(_p(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Sg.Resize,this.handleCancel),this.windowListeners.add(Sg.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Sg.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,n=t.node.current;n&<s(n),r(p0)}handleKeyDown(t){if(GTe(t)){const{active:r,context:n,options:a}=this.props,{keyboardCodes:i=fct,coordinateGetter:l=hts,scrollBehavior:o="smooth"}=a,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=n.current,h=d?{x:d.left,y:d.top}:p0;this.referenceCoordinates||(this.referenceCoordinates=h);const m=l(t,{active:r,context:n.current,currentCoordinates:h});if(m){const x=jF(m,h),g={x:0,y:0},{scrollableAncestors:v}=n.current;for(const j of v){const b=t.code,{isTop:N,isRight:S,isLeft:T,isBottom:A,maxScroll:P,minScroll:D}=hct(j),B=ats(j),z={x:Math.min(b===To.Right?B.right-B.width/2:B.right,Math.max(b===To.Right?B.left:B.left+B.width/2,m.x)),y:Math.min(b===To.Down?B.bottom-B.height/2:B.bottom,Math.max(b===To.Down?B.top:B.top+B.height/2,m.y))},F=b===To.Right&&!S||b===To.Left&&!T,$=b===To.Down&&!A||b===To.Up&&!N;if(F&&z.x!==m.x){const X=j.scrollLeft+x.x,K=b===To.Right&&X<=P.x||b===To.Left&&X>=D.x;if(K&&!x.y){j.scrollTo({left:X,behavior:o});return}K?g.x=j.scrollLeft-X:g.x=b===To.Right?j.scrollLeft-P.x:j.scrollLeft-D.x,g.x&&j.scrollBy({left:-g.x,behavior:o});break}else if($&&z.y!==m.y){const X=j.scrollTop+x.y,K=b===To.Down&&X<=P.y||b===To.Up&&X>=D.y;if(K&&!x.x){j.scrollTo({top:X,behavior:o});return}K?g.y=j.scrollTop-X:g.y=b===To.Down?j.scrollTop-P.y:j.scrollTop-D.y,g.y&&j.scrollBy({top:-g.y,behavior:o});break}}this.handleMove(t,EM(jF(m,this.referenceCoordinates),g))}}}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()}}Cxe.activators=[{eventName:"onKeyDown",handler:(s,t,r)=>{let{keyboardCodes:n=fct,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 Uze(s){return!!(s&&"distance"in s)}function qze(s){return!!(s&&"delay"in s)}class KTe{constructor(t,r,n){var a;n===void 0&&(n=dts(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=FP(l),this.documentListeners=new u8(this.document),this.listeners=new u8(n),this.windowListeners=new u8(_p(l)),this.initialCoordinates=(a=zNe(i))!=null?a:p0,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(Sg.Resize,this.handleCancel),this.windowListeners.add(Sg.DragStart,$ze),this.windowListeners.add(Sg.VisibilityChange,this.handleCancel),this.windowListeners.add(Sg.ContextMenu,$ze),this.documentListeners.add(Sg.Keydown,this.handleKeydown),r){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(qze(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Uze(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(Sg.Click,uts,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Sg.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=zNe(t))!=null?r:p0,d=jF(a,c);if(!n&&o){if(Uze(o)){if(o.tolerance!=null&&Dbe(d,o.tolerance))return this.handleCancel();if(Dbe(d,o.distance))return this.handleStart()}if(qze(o)&&Dbe(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===To.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const mts={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class zP extends KTe{constructor(t){const{event:r}=t,n=FP(r.target);super(t,mts,n)}}zP.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 fts={move:{name:"mousemove"},end:{name:"mouseup"}};var UNe;(function(s){s[s.RightClick=2]="RightClick"})(UNe||(UNe={}));class pts extends KTe{constructor(t){super(t,fts,FP(t.event.target))}}pts.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return r.button===UNe.RightClick?!1:(n==null||n({event:r}),!0)}}];const Rbe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class xts extends KTe{constructor(t){super(t,Rbe)}static setup(){return window.addEventListener(Rbe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Rbe.move.name,t)};function t(){}}}xts.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 h8;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(h8||(h8={}));var Zhe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Zhe||(Zhe={}));function gts(s){let{acceleration:t,activator:r=h8.Pointer,canScroll:n,draggingRect:a,enabled:i,interval:l=5,order:o=Zhe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:h,delta:m,threshold:x}=s;const g=vts({delta:m,disabled:!i}),[v,j]=Mes(),b=k.useRef({x:0,y:0}),N=k.useRef({x:0,y:0}),S=k.useMemo(()=>{switch(r){case h8.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case h8.DraggableRect:return a}},[r,a,c]),T=k.useRef(null),A=k.useCallback(()=>{const D=T.current;if(!D)return;const B=b.current.x*N.current.x,z=b.current.y*N.current.y;D.scrollBy(B,z)},[]),P=k.useMemo(()=>o===Zhe.TreeOrder?[...d].reverse():d,[o,d]);k.useEffect(()=>{if(!i||!d.length||!S){j();return}for(const D of P){if((n==null?void 0:n(D))===!1)continue;const B=d.indexOf(D),z=h[B];if(!z)continue;const{direction:F,speed:$}=nts(D,z,S,t,x);for(const X of["x","y"])g[X][F[X]]||($[X]=0,F[X]=0);if($.x>0||$.y>0){j(),T.current=D,v(A,l),b.current=$,N.current=F;return}}b.current={x:0,y:0},N.current={x:0,y:0},j()},[t,A,n,j,i,l,JSON.stringify(S),JSON.stringify(g),v,d,P,h,JSON.stringify(x)])}const yts={x:{[_h.Backward]:!1,[_h.Forward]:!1},y:{[_h.Backward]:!1,[_h.Forward]:!1}};function vts(s){let{delta:t,disabled:r}=s;const n=BNe(t);return xz(a=>{if(r||!n||!a)return yts;const i={x:Math.sign(t.x-n.x),y:Math.sign(t.y-n.y)};return{x:{[_h.Backward]:a.x[_h.Backward]||i.x===-1,[_h.Forward]:a.x[_h.Forward]||i.x===1},y:{[_h.Backward]:a.y[_h.Backward]||i.y===-1,[_h.Forward]:a.y[_h.Forward]||i.y===1}}},[r,t,n])}function bts(s,t){const r=t!=null?s.get(t):void 0,n=r?r.node.current:null;return xz(a=>{var i;return t==null?null:(i=n??a)!=null?i:null},[n,t])}function _ts(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 NF;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(NF||(NF={}));var qNe;(function(s){s.Optimized="optimized"})(qNe||(qNe={}));const Vze=new Map;function wts(s,t){let{dragging:r,dependencies:n,config:a}=t;const[i,l]=k.useState(null),{frequency:o,measure:c,strategy:d}=a,h=k.useRef(s),m=b(),x=wF(m),g=k.useCallback(function(N){N===void 0&&(N=[]),!x.current&&l(S=>S===null?N:S.concat(N.filter(T=>!S.includes(T))))},[x]),v=k.useRef(null),j=xz(N=>{if(m&&!r)return Vze;if(!N||N===Vze||h.current!==s||i!=null){const S=new Map;for(let T of s){if(!T)continue;if(i&&i.length>0&&!i.includes(T.id)&&T.rect.current){S.set(T.id,T.rect.current);continue}const A=T.node.current,P=A?new WTe(c(A),A):null;T.rect.current=P,P&&S.set(T.id,P)}return S}return N},[s,i,r,m,c]);return k.useEffect(()=>{h.current=s},[s]),k.useEffect(()=>{m||g()},[r,m]),k.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),k.useEffect(()=>{m||typeof o!="number"||v.current!==null||(v.current=setTimeout(()=>{g(),v.current=null},o))},[o,m,g,...n]),{droppableRects:j,measureDroppableContainers:g,measuringScheduled:i!=null};function b(){switch(d){case NF.Always:return!1;case NF.BeforeDragging:return r;default:return!r}}}function pct(s,t){return xz(r=>s?r||(typeof t=="function"?t(s):s):null,[t,s])}function jts(s,t){return pct(s,t)}function Nts(s){let{callback:t,disabled:r}=s;const n=HTe(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 Txe(s){let{callback:t,disabled:r}=s;const n=HTe(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 kts(s){return new WTe(BP(s),s)}function Hze(s,t,r){t===void 0&&(t=kts);const[n,a]=k.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??r)!=null?d:null}const h=t(s);return JSON.stringify(c)===JSON.stringify(h)?c:h})}const l=Nts({callback(c){if(s)for(const d of c){const{type:h,target:m}=d;if(h==="childList"&&m instanceof HTMLElement&&m.contains(s)){i();break}}}}),o=Txe({callback:i});return l1(()=>{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 Sts(s){const t=pct(s);return oct(s,t)}const Gze=[];function Cts(s){const t=k.useRef(s),r=xz(n=>s?n&&n!==Gze&&s&&t.current&&s.parentNode===t.current.parentNode?n:Sxe(s):Gze,[s]);return k.useEffect(()=>{t.current=s},[s]),r}function Tts(s){const[t,r]=k.useState(null),n=k.useRef(s),a=k.useCallback(i=>{const l=Lbe(i.target);l&&r(o=>o?(o.set(l,$Ne(l)),new Map(o)):null)},[]);return k.useEffect(()=>{const i=n.current;if(s!==i){l(i);const o=s.map(c=>{const d=Lbe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,$Ne(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=Lbe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),k.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>EM(i,l),p0):mct(s):p0,[s,t])}function Wze(s,t){t===void 0&&(t=[]);const r=k.useRef(null);return k.useEffect(()=>{r.current=null},t),k.useEffect(()=>{const n=s!==p0;n&&!r.current&&(r.current=s),!n&&r.current&&(r.current=null)},[s]),r.current?jF(s,r.current):p0}function Ets(s){k.useEffect(()=>{if(!jxe)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 Ats(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 xct(s){return k.useMemo(()=>s?ets(s):null,[s])}const Kze=[];function Mts(s,t){t===void 0&&(t=BP);const[r]=s,n=xct(r?_p(r):null),[a,i]=k.useState(Kze);function l(){i(()=>s.length?s.map(c=>uct(c)?n:new WTe(t(c),c)):Kze)}const o=Txe({callback:l});return l1(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function Its(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return pz(t)?t:s}function Pts(s){let{measure:t}=s;const[r,n]=k.useState(null),a=k.useCallback(d=>{for(const{target:h}of d)if(pz(h)){n(m=>{const x=t(h);return m?{...m,width:x.width,height:x.height}:x});break}},[t]),i=Txe({callback:a}),l=k.useCallback(d=>{const h=Its(d);i==null||i.disconnect(),h&&(i==null||i.observe(h)),n(h?t(h):null)},[t,i]),[o,c]=Khe(l);return k.useMemo(()=>({nodeRef:o,rect:r,setRef:c}),[r,o,c])}const Lts=[{sensor:zP,options:{}},{sensor:Cxe,options:{}}],Dts={current:{}},Lde={draggable:{measure:zze},droppable:{measure:zze,strategy:NF.WhileDragging,frequency:qNe.Optimized},dragOverlay:{measure:BP}};class m8 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 Rts={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new m8,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Yhe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Lde,measureDroppableContainers:Yhe,windowRect:null,measuringScheduled:!1},Ots={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Yhe,draggableNodes:new Map,over:null,measureDroppableContainers:Yhe},Exe=k.createContext(Ots),gct=k.createContext(Rts);function Fts(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new m8}}}function Bts(s,t){switch(t.type){case zu.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case zu.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 zu.DragEnd:case zu.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case zu.RegisterDroppable:{const{element:r}=t,{id:n}=r,a=new m8(s.droppable.containers);return a.set(n,r),{...s,droppable:{...s.droppable,containers:a}}}case zu.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 m8(s.droppable.containers);return l.set(r,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case zu.UnregisterDroppable:{const{id:r,key:n}=t,a=s.droppable.containers.get(r);if(!a||n!==a.key)return s;const i=new m8(s.droppable.containers);return i.delete(r),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function zts(s){let{disabled:t}=s;const{active:r,activatorEvent:n,draggableNodes:a}=k.useContext(Exe),i=BNe(n),l=BNe(r==null?void 0:r.id);return k.useEffect(()=>{if(!t&&!n&&i&&l!=null){if(!GTe(i)||document.activeElement===i.target)return;const o=a.get(l);if(!o)return;const{activatorNode:c,node:d}=o;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const h of[c.current,d.current]){if(!h)continue;const m=Les(h);if(m){m.focus();break}}})}},[n,t,a,l,i]),null}function $ts(s,t){let{transform:r,...n}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...n}),r):r}function Uts(s){return k.useMemo(()=>({draggable:{...Lde.draggable,...s==null?void 0:s.draggable},droppable:{...Lde.droppable,...s==null?void 0:s.droppable},dragOverlay:{...Lde.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 qts(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;l1(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!n)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const h=r(d),m=oct(h,n);if(l||(m.x=0),o||(m.y=0),i.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const x=lct(d);x&&x.scrollBy({top:m.y,left:m.x})}},[t,l,o,n,r])}const yct=k.createContext({...p0,scaleX:1,scaleY:1});var aj;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(aj||(aj={}));const Axe=k.memo(function(t){var r,n,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:h=Lts,collisionDetection:m=Wes,measuring:x,modifiers:g,...v}=t;const j=k.useReducer(Bts,void 0,Fts),[b,N]=j,[S,T]=zes(),[A,P]=k.useState(aj.Uninitialized),D=A===aj.Initialized,{draggable:{active:B,nodes:z,translate:F},droppable:{containers:$}}=b,X=B!=null?z.get(B):null,K=k.useRef({initial:null,translated:null}),Q=k.useMemo(()=>{var Lr;return B!=null?{id:B,data:(Lr=X==null?void 0:X.data)!=null?Lr:Dts,rect:K}:null},[B,X]),Y=k.useRef(null),[ne,de]=k.useState(null),[ce,ae]=k.useState(null),ie=wF(v,Object.values(v)),me=gz("DndDescribedBy",l),oe=k.useMemo(()=>$.getEnabled(),[$]),ge=Uts(x),{droppableRects:be,measureDroppableContainers:Oe,measuringScheduled:Me}=wts(oe,{dragging:D,dependencies:[F.x,F.y],config:ge.droppable}),Pe=bts(z,B),Ee=k.useMemo(()=>ce?zNe(ce):null,[ce]),$e=Tr(),Se=jts(Pe,ge.draggable.measure);qts({activeNode:B!=null?z.get(B):null,config:$e.layoutShiftCompensation,initialRect:Se,measure:ge.draggable.measure});const ze=Hze(Pe,ge.draggable.measure,Se),Te=Hze(Pe?Pe.parentElement:null),ye=k.useRef({activatorEvent:null,active:null,activeNode:Pe,collisionRect:null,collisions:null,droppableRects:be,draggableNodes:z,draggingNode:null,draggingNodeRect:null,droppableContainers:$,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ct=$.getNodeFor((r=ye.current.over)==null?void 0:r.id),ve=Pts({measure:ge.dragOverlay.measure}),rt=(n=ve.nodeRef.current)!=null?n:Pe,Re=D?(a=ve.rect)!=null?a:ze:null,Qe=!!(ve.nodeRef.current&&ve.rect),Ke=Sts(Qe?null:ze),Ce=xct(rt?_p(rt):null),nt=Cts(D?ct??Pe:null),$t=Mts(nt),lt=$ts(g,{transform:{x:F.x-Ke.x,y:F.y-Ke.y,scaleX:1,scaleY:1},activatorEvent:ce,active:Q,activeNodeRect:ze,containerNodeRect:Te,draggingNodeRect:Re,over:ye.current.over,overlayNodeRect:ve.rect,scrollableAncestors:nt,scrollableAncestorRects:$t,windowRect:Ce}),it=Ee?EM(Ee,F):null,Nt=Tts(nt),Ft=Wze(Nt),at=Wze(Nt,[ze]),Ie=EM(lt,Ft),et=Re?Zes(Re,lt):null,Dt=Q&&et?m({active:Q,collisionRect:et,droppableRects:be,droppableContainers:oe,pointerCoordinates:it}):null,Jt=ict(Dt,"id"),[cs,Ht]=k.useState(null),dt=Qe?lt:EM(lt,at),Qt=Kes(dt,(i=cs==null?void 0:cs.rect)!=null?i:null,ze),yt=k.useRef(null),ss=k.useCallback((Lr,$r)=>{let{sensor:kr,options:Sr}=$r;if(Y.current==null)return;const hn=z.get(Y.current);if(!hn)return;const zn=Lr.nativeEvent,Xs=new kr({active:Y.current,activeNode:hn,event:zn,options:Sr,context:ye,onAbort(xn){if(!z.get(xn))return;const{onDragAbort:pr}=ie.current,Hr={id:xn};pr==null||pr(Hr),S({type:"onDragAbort",event:Hr})},onPending(xn,us,pr,Hr){if(!z.get(xn))return;const{onDragPending:Na}=ie.current,Je={id:xn,constraint:us,initialCoordinates:pr,offset:Hr};Na==null||Na(Je),S({type:"onDragPending",event:Je})},onStart(xn){const us=Y.current;if(us==null)return;const pr=z.get(us);if(!pr)return;const{onDragStart:Hr}=ie.current,aa={activatorEvent:zn,active:{id:us,data:pr.data,rect:K}};pf.unstable_batchedUpdates(()=>{Hr==null||Hr(aa),P(aj.Initializing),N({type:zu.DragStart,initialCoordinates:xn,active:us}),S({type:"onDragStart",event:aa}),de(yt.current),ae(zn)})},onMove(xn){N({type:zu.DragMove,coordinates:xn})},onEnd:Ur(zu.DragEnd),onCancel:Ur(zu.DragCancel)});yt.current=Xs;function Ur(xn){return async function(){const{active:pr,collisions:Hr,over:aa,scrollAdjustedTranslate:Na}=ye.current;let Je=null;if(pr&&Na){const{cancelDrop:Fe}=ie.current;Je={activatorEvent:zn,active:pr,collisions:Hr,delta:Na,over:aa},xn===zu.DragEnd&&typeof Fe=="function"&&await Promise.resolve(Fe(Je))&&(xn=zu.DragCancel)}Y.current=null,pf.unstable_batchedUpdates(()=>{N({type:xn}),P(aj.Uninitialized),Ht(null),de(null),ae(null),yt.current=null;const Fe=xn===zu.DragEnd?"onDragEnd":"onDragCancel";if(Je){const We=ie.current[Fe];We==null||We(Je),S({type:Fe,event:Je})}})}}},[z]),Is=k.useCallback((Lr,$r)=>(kr,Sr)=>{const hn=kr.nativeEvent,zn=z.get(Sr);if(Y.current!==null||!zn||hn.dndKit||hn.defaultPrevented)return;const Xs={active:zn};Lr(kr,$r.options,Xs)===!0&&(hn.dndKit={capturedBy:$r.sensor},Y.current=Sr,ss(kr,$r))},[z,ss]),fs=_ts(h,Is);Ets(h),l1(()=>{ze&&A===aj.Initializing&&P(aj.Initialized)},[ze,A]),k.useEffect(()=>{const{onDragMove:Lr}=ie.current,{active:$r,activatorEvent:kr,collisions:Sr,over:hn}=ye.current;if(!$r||!kr)return;const zn={active:$r,activatorEvent:kr,collisions:Sr,delta:{x:Ie.x,y:Ie.y},over:hn};pf.unstable_batchedUpdates(()=>{Lr==null||Lr(zn),S({type:"onDragMove",event:zn})})},[Ie.x,Ie.y]),k.useEffect(()=>{const{active:Lr,activatorEvent:$r,collisions:kr,droppableContainers:Sr,scrollAdjustedTranslate:hn}=ye.current;if(!Lr||Y.current==null||!$r||!hn)return;const{onDragOver:zn}=ie.current,Xs=Sr.get(Jt),Ur=Xs&&Xs.rect.current?{id:Xs.id,rect:Xs.rect.current,data:Xs.data,disabled:Xs.disabled}:null,xn={active:Lr,activatorEvent:$r,collisions:kr,delta:{x:hn.x,y:hn.y},over:Ur};pf.unstable_batchedUpdates(()=>{Ht(Ur),zn==null||zn(xn),S({type:"onDragOver",event:xn})})},[Jt]),l1(()=>{ye.current={activatorEvent:ce,active:Q,activeNode:Pe,collisionRect:et,collisions:Dt,droppableRects:be,draggableNodes:z,draggingNode:rt,draggingNodeRect:Re,droppableContainers:$,over:cs,scrollableAncestors:nt,scrollAdjustedTranslate:Ie},K.current={initial:Re,translated:et}},[Q,Pe,Dt,et,z,rt,Re,be,$,cs,nt,Ie]),gts({...$e,delta:F,draggingRect:et,pointerCoordinates:it,scrollableAncestors:nt,scrollableAncestorRects:$t});const ar=k.useMemo(()=>({active:Q,activeNode:Pe,activeNodeRect:ze,activatorEvent:ce,collisions:Dt,containerNodeRect:Te,dragOverlay:ve,draggableNodes:z,droppableContainers:$,droppableRects:be,over:cs,measureDroppableContainers:Oe,scrollableAncestors:nt,scrollableAncestorRects:$t,measuringConfiguration:ge,measuringScheduled:Me,windowRect:Ce}),[Q,Pe,ze,ce,Dt,Te,ve,z,$,be,cs,Oe,nt,$t,ge,Me,Ce]),Er=k.useMemo(()=>({activatorEvent:ce,activators:fs,active:Q,activeNodeRect:ze,ariaDescribedById:{draggable:me},dispatch:N,draggableNodes:z,over:cs,measureDroppableContainers:Oe}),[ce,fs,Q,ze,N,me,z,cs,Oe]);return wt.createElement(rct.Provider,{value:T},wt.createElement(Exe.Provider,{value:Er},wt.createElement(gct.Provider,{value:ar},wt.createElement(yct.Provider,{value:Qt},d)),wt.createElement(zts,{disabled:(o==null?void 0:o.restoreFocus)===!1})),wt.createElement(qes,{...o,hiddenTextDescribedById:me}));function Tr(){const Lr=(ne==null?void 0:ne.autoScrollEnabled)===!1,$r=typeof c=="object"?c.enabled===!1:c===!1,kr=D&&!Lr&&!$r;return typeof c=="object"?{...c,enabled:kr}:{enabled:kr}}}),Vts=k.createContext(null),Yze="button",Hts="Draggable";function Gts(s){let{id:t,data:r,disabled:n=!1,attributes:a}=s;const i=gz(Hts),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:h,draggableNodes:m,over:x}=k.useContext(Exe),{role:g=Yze,roleDescription:v="draggable",tabIndex:j=0}=a??{},b=(c==null?void 0:c.id)===t,N=k.useContext(b?yct:Vts),[S,T]=Khe(),[A,P]=Khe(),D=Ats(l,t),B=wF(r);l1(()=>(m.set(t,{id:t,key:i,node:S,activatorNode:A,data:B}),()=>{const F=m.get(t);F&&F.key===i&&m.delete(t)}),[m,t]);const z=k.useMemo(()=>({role:g,tabIndex:j,"aria-disabled":n,"aria-pressed":b&&g===Yze?!0:void 0,"aria-roledescription":v,"aria-describedby":h.draggable}),[n,g,j,b,v,h.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:z,isDragging:b,listeners:n?void 0:D,node:S,over:x,setNodeRef:T,setActivatorNodeRef:P,transform:N}}function Wts(){return k.useContext(gct)}const Kts="Droppable",Yts={timeout:25};function Zts(s){let{data:t,disabled:r=!1,id:n,resizeObserverConfig:a}=s;const i=gz(Kts),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=k.useContext(Exe),h=k.useRef({disabled:r}),m=k.useRef(!1),x=k.useRef(null),g=k.useRef(null),{disabled:v,updateMeasurementsFor:j,timeout:b}={...Yts,...a},N=wF(j??n),S=k.useCallback(()=>{if(!m.current){m.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{d(Array.isArray(N.current)?N.current:[N.current]),g.current=null},b)},[b]),T=Txe({callback:S,disabled:v||!l}),A=k.useCallback((z,F)=>{T&&(F&&(T.unobserve(F),m.current=!1),z&&T.observe(z))},[T]),[P,D]=Khe(A),B=wF(t);return k.useEffect(()=>{!T||!P.current||(T.disconnect(),m.current=!1,T.observe(P.current))},[P,T]),k.useEffect(()=>(o({type:zu.RegisterDroppable,element:{id:n,key:i,disabled:r,node:P,rect:x,data:B}}),()=>o({type:zu.UnregisterDroppable,key:i,id:n})),[n]),k.useEffect(()=>{r!==h.current.disabled&&(o({type:zu.SetDroppableDisabled,id:n,key:i,disabled:r}),h.current.disabled=r)},[n,i,r,o]),{active:l,rect:x,isOver:(c==null?void 0:c.id)===n,node:P,over:c,setNodeRef:D}}function Mxe(s,t,r){const n=s.slice();return n.splice(r<0?n.length+r:r,0,n.splice(t,1)[0]),n}function Xts(s,t){return s.reduce((r,n,a)=>{const i=t.get(n);return i&&(r[a]=i),r},Array(s.length))}function SU(s){return s!==null&&s>=0}function Qts(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=ess(r,l,a);if(l===a){const d=r[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...CU}:l=i?{x:o.width+c,y:0,...CU}:{x:0,y:0,...CU}};function ess(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=Mxe(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}},TU={scaleX:1,scaleY:1},tss=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,...TU}:a=l?{x:0,y:o.height+c,...TU}:{x:0,y:0,...TU}};function sss(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return n?rn.map(D=>typeof D=="object"&&"id"in D?D.id:D),[n]),v=l!=null,j=l?g.indexOf(l.id):-1,b=d?g.indexOf(d.id):-1,N=k.useRef(g),S=!Qts(g,N.current),T=b!==-1&&j===-1||S,A=Jts(i);l1(()=>{S&&v&&h(g)},[S,g,v,h]),k.useEffect(()=>{N.current=g},[g]);const P=k.useMemo(()=>({activeIndex:j,containerId:m,disabled:A,disableTransforms:T,items:g,overIndex:b,useDragOverlay:x,sortedRects:Xts(g,c),strategy:a}),[j,m,A.draggable,A.droppable,T,g,b,c,x,a]);return wt.createElement(bct.Provider,{value:P},t)}const rss=s=>{let{id:t,items:r,activeIndex:n,overIndex:a}=s;return Mxe(r,n,a).indexOf(t)},nss=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},ass={duration:200,easing:"ease"},_ct="transform",iss=A2.Transition.toString({property:_ct,duration:0,easing:"linear"}),oss={roleDescription:"sortable"};function lss(s){let{disabled:t,index:r,node:n,rect:a}=s;const[i,l]=k.useState(null),o=k.useRef(r);return l1(()=>{if(!t&&r!==o.current&&n.current){const c=a.current;if(c){const d=BP(n.current,{ignoreTransform:!0}),h={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(h.x||h.y)&&l(h)}}r!==o.current&&(o.current=r)},[t,r,n,a]),k.useEffect(()=>{i&&l(null)},[i]),i}function Pxe(s){let{animateLayoutChanges:t=nss,attributes:r,disabled:n,data:a,getNewIndex:i=rss,id:l,strategy:o,resizeObserverConfig:c,transition:d=ass}=s;const{items:h,containerId:m,activeIndex:x,disabled:g,disableTransforms:v,sortedRects:j,overIndex:b,useDragOverlay:N,strategy:S}=k.useContext(bct),T=css(n,g),A=h.indexOf(l),P=k.useMemo(()=>({sortable:{containerId:m,index:A,items:h},...a}),[m,a,A,h]),D=k.useMemo(()=>h.slice(h.indexOf(l)),[h,l]),{rect:B,node:z,isOver:F,setNodeRef:$}=Zts({id:l,data:P,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:D,...c}}),{active:X,activatorEvent:K,activeNodeRect:Q,attributes:Y,setNodeRef:ne,listeners:de,isDragging:ce,over:ae,setActivatorNodeRef:ie,transform:me}=Gts({id:l,data:P,attributes:{...oss,...r},disabled:T.draggable}),oe=Aes($,ne),ge=!!X,be=ge&&!v&&SU(x)&&SU(b),Oe=!N&&ce,Me=Oe&&be?me:null,Ee=be?Me??(o??S)({rects:j,activeNodeRect:Q,activeIndex:x,overIndex:b,index:A}):null,$e=SU(x)&&SU(b)?i({id:l,items:h,activeIndex:x,overIndex:b}):A,Se=X==null?void 0:X.id,ze=k.useRef({activeId:Se,items:h,newIndex:$e,containerId:m}),Te=h!==ze.current.items,ye=t({active:X,containerId:m,isDragging:ce,isSorting:ge,id:l,index:A,items:h,newIndex:ze.current.newIndex,previousItems:ze.current.items,previousContainerId:ze.current.containerId,transition:d,wasDragging:ze.current.activeId!=null}),ct=lss({disabled:!ye,index:A,node:z,rect:B});return k.useEffect(()=>{ge&&ze.current.newIndex!==$e&&(ze.current.newIndex=$e),m!==ze.current.containerId&&(ze.current.containerId=m),h!==ze.current.items&&(ze.current.items=h)},[ge,$e,m,h]),k.useEffect(()=>{if(Se===ze.current.activeId)return;if(Se!=null&&ze.current.activeId==null){ze.current.activeId=Se;return}const rt=setTimeout(()=>{ze.current.activeId=Se},50);return()=>clearTimeout(rt)},[Se]),{active:X,activeIndex:x,attributes:Y,data:P,rect:B,index:A,newIndex:$e,items:h,isOver:F,isSorting:ge,isDragging:ce,listeners:de,node:z,overIndex:b,over:ae,setNodeRef:oe,setActivatorNodeRef:ie,setDroppableNodeRef:$,setDraggableNodeRef:ne,transform:ct??Ee,transition:ve()};function ve(){if(ct||Te&&ze.current.newIndex===A)return iss;if(!(Oe&&!GTe(K)||!d)&&(ge||ye))return A2.Transition.toString({...d,property:_ct})}}function css(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 Xhe(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 dss=[To.Down,To.Right,To.Up,To.Left],wct=(s,t)=>{let{context:{active:r,collisionRect:n,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(dss.includes(s.code)){if(s.preventDefault(),!r||!n)return;const c=[];i.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const x=a.get(m.id);if(x)switch(s.code){case To.Down:n.topx.top&&c.push(m);break;case To.Left:n.left>x.left&&c.push(m);break;case To.Right:n.left1&&(h=d[1].id),h!=null){const m=i.get(r.id),x=i.get(h),g=x?a.get(x.id):null,v=x==null?void 0:x.node.current;if(v&&g&&m&&x){const b=Sxe(v).some((D,B)=>o[B]!==D),N=jct(m,x),S=uss(m,x),T=b||!N?{x:0,y:0}:{x:S?n.width-g.width:0,y:S?n.height-g.height:0},A={x:g.left,y:g.top};return T.x&&T.y?A:jF(A,T)}}}};function jct(s,t){return!Xhe(s)||!Xhe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function uss(s,t){return!Xhe(s)||!Xhe(t)||!jct(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>r(s),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Ge,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(rn,{className:"h-2.5 w-2.5"}),Ss(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:Bt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"h-3 w-3"}),s.post_date?Ss(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(wo,{className:"w-auto p-0",align:"start",children:[e.jsx(Nx,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:m=>n(s.id,m?Ss(m,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>n(s.id,null),children:"Clear date"})})]})]})]})]})})}const mss=()=>{const s=es(),[t,r]=k.useState("all"),[n,a]=k.useState(!1),[i,l]=k.useState(Ss(new Date,"yyyy-MM")),[o,c]=k.useState([]),[d,h]=k.useState(!1),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(!1),[P,D]=k.useState(!1),[B,z]=k.useState(Ss(new Date,"yyyy-MM")),[F,$]=k.useState(null),[X,K]=k.useState(""),[Q,Y]=k.useState(""),[ne,de]=k.useState(""),[ce,ae]=k.useState(!1),ie=Nxe(CI(zP,{activationConstraint:{distance:5}}),CI(Cxe,{coordinateGetter:wct})),{data:me=[],isLoading:oe}=gt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:it,error:Nt}=await H.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Nt)throw Nt;return it}}),{data:ge=[]}=gt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:it,error:Nt}=await H.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Nt)throw Nt;return it}}),{data:be=[]}=gt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:it,error:Nt}=await H.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Nt)throw Nt;return it}}),Oe=[...new Set(me.map(it=>it.month))].sort((it,Nt)=>Nt.localeCompare(it)),Me=t==="all"?me:me.filter(it=>it.month===t),Pe=it=>{const Nt=j3e(it,"yyyy-MM",new Date);return Ss(Nt,"MMMM yyyy")},Ee=it=>{v(it),b(it.caption),S(it.post_date)},$e=async()=>{if(g){A(!0);try{const{error:it}=await H.from("social_swag_2").update({caption:j,post_date:N}).eq("id",g.id);if(it)throw it;ue.success("Image updated"),v(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ue.error("Failed to update image")}finally{A(!1)}}},Se=async it=>{const{active:Nt,over:Ft}=it;if(!Ft||Nt.id===Ft.id)return;const at=Me,Ie=at.findIndex(Jt=>Jt.id===Nt.id),et=at.findIndex(Jt=>Jt.id===Ft.id);if(Ie===-1||et===-1)return;const Dt=Mxe(at,Ie,et);s.setQueryData(["admin-social-swag-2"],Jt=>{if(!Jt)return Jt;const cs={};return Dt.forEach((Ht,dt)=>{cs[Ht.id]=dt}),Jt.map(Ht=>cs[Ht.id]!==void 0?{...Ht,sort_order:cs[Ht.id]}:Ht).sort((Ht,dt)=>Ht.month!==dt.month?dt.month.localeCompare(Ht.month):Ht.sort_order-dt.sort_order)});try{await Promise.all(Dt.map((Jt,cs)=>H.from("social_swag_2").update({sort_order:cs}).eq("id",Jt.id)))}catch{ue.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},ze=it=>{const Ft=Array.from(it.target.files||[]).sort((at,Ie)=>at.name.localeCompare(Ie.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(at=>({file:at,preview:URL.createObjectURL(at),caption:""}));c(at=>[...at,...Ft].slice(0,16))},Te=it=>{c(Nt=>{const Ft=[...Nt];return URL.revokeObjectURL(Ft[it].preview),Ft.splice(it,1),Ft})},ye=(it,Nt)=>{c(Ft=>{const at=[...Ft];return at[it]={...at[it],caption:Nt},at})},ct=async()=>{var Nt;if(o.length===0){ue.error("Please add at least one image");return}if(o.filter(Ft=>!Ft.caption.trim()).length>0){ue.error("Please add captions to all images");return}h(!0);try{const{data:Ft}=await H.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),at=(((Nt=Ft==null?void 0:Ft[0])==null?void 0:Nt.sort_order)??-1)+1;for(let Ie=0;Ie{const Nt=it.image_url.split("/social-swag-2/");Nt[1]&&await H.storage.from("social-swag-2").remove([Nt[1]]);const{error:Ft}=await H.from("social_swag_2").delete().eq("id",it.id);if(Ft)throw Ft},onSuccess:()=>{ue.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ue.error("Failed to delete image")}),rt=Lt({mutationFn:async({id:it,postDate:Nt})=>{const{error:Ft}=await H.from("social_swag_2").update({post_date:Nt}).eq("id",it);if(Ft)throw Ft},onSuccess:()=>{ue.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ue.error("Failed to update post date")}),Re=Lt({mutationFn:async({month:it,link:Nt})=>{const{error:Ft}=await H.from("social_swag_2_months").upsert({month:it,canva_link:Nt||null},{onConflict:"month"});if(Ft)throw Ft},onSuccess:()=>{ue.success("Canva link updated"),x(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ue.error("Failed to update Canva link")}),Qe=it=>{var Nt;return((Nt=ge.find(Ft=>Ft.month===it))==null?void 0:Nt.canva_link)||""},Ke=it=>be.find(Nt=>Nt.month===it)||null,Ce=it=>{var Ft;const Nt=(Ft=it.target.files)==null?void 0:Ft[0];Nt&&($(Nt),K(URL.createObjectURL(Nt)))},nt=()=>{X&&URL.revokeObjectURL(X),$(null),K(""),Y(""),de("")},$t=async()=>{if(!F){ue.error("Please select an image");return}ae(!0);try{const it=F.name.split(".").pop(),Nt=`reels/${B}-${Date.now()}.${it}`,{error:Ft}=await H.storage.from("social-swag-2").upload(Nt,F);if(Ft)throw Ft;const{data:{publicUrl:at}}=H.storage.from("social-swag-2").getPublicUrl(Nt),{error:Ie}=await H.from("social_swag_2_reels").upsert({month:B,image_url:at,canva_link:ne||null,caption:Q||null},{onConflict:"month"});if(Ie)throw Ie;ue.success("Reel uploaded successfully!"),FNe(`${Pe(B)} Reel`,"social-swag-2"),nt(),D(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(it){console.error("Reel upload error:",it),ue.error("Failed to upload reel")}finally{ae(!1)}},lt=Lt({mutationFn:async it=>{const Nt=it.image_url.split("/social-swag-2/");Nt[1]&&await H.storage.from("social-swag-2").remove([Nt[1]]);const{error:Ft}=await H.from("social_swag_2_reels").delete().eq("id",it.id);if(Ft)throw Ft},onSuccess:()=>{ue.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ue.error("Failed to delete reel")});return e.jsxs(_s,{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(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{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(he,{children:"Month"}),e.jsx(ke,{type:"month",value:i,onChange:it=>l(it.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{children:["Images (",o.length,"/16)"]}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ze,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(oa,{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((it,Nt)=>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:it.preview,alt:`Upload ${Nt+1}`,className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Te(Nt),children:e.jsx(_r,{className:"h-3 w-3"})})]}),e.jsx(ur,{placeholder:"Caption...",value:it.caption,onChange:Ft=>ye(Nt,Ft.target.value),className:"text-xs h-20"})]},Nt))}),e.jsx(G,{onClick:ct,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(oa,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(vs,{open:P,onOpenChange:it=>{D(it),it||nt()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"gap-2",children:[e.jsx(Nh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(ys,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{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(he,{children:"Month"}),e.jsx(ke,{type:"month",value:B,onChange:it=>z(it.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Reel Preview Image"}),X?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:X,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(X),$(null),K("")},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(Nh,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select reel preview image"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Canva Download Link"}),e.jsx(ke,{value:ne,onChange:it=>de(it.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Caption"}),e.jsx(ur,{value:Q,onChange:it=>Y(it.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(G,{onClick:$t,disabled:ce||!F,className:"w-full gap-2",children:ce?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:me.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Oe.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Rn,{value:t,onValueChange:r,children:e.jsxs(Dn,{children:[e.jsx(Xt,{value:"all",children:"All"}),Oe.map(it=>e.jsx(Xt,{value:it,children:Pe(it)},it))]})}),t!=="all"&&e.jsx(Ne,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(xo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(he,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",Pe(t)]}),(m==null?void 0:m.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(ke,{value:m.link,onChange:it=>x({...m,link:it.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(G,{size:"sm",onClick:()=>Re.mutate(m),children:"Save"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>x(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Qe(t)||"No link set"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>x({month:t,link:Qe(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(Ne,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Nh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(he,{className:"text-sm text-muted-foreground",children:["Reel for ",Pe(t)]}),(()=>{const it=Ke(t);return it?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:it.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:it.caption||"No caption"}),it.canva_link&&e.jsx("a",{href:it.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(G,{variant:"destructive",size:"sm",onClick:()=>lt.mutate(it),children:e.jsx(yr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),oe?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(fl,{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(Axe,{sensors:ie,collisionDetection:kxe,onDragEnd:Se,children:e.jsx(Ixe,{items:Me.map(it=>it.id),strategy:yz,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Me.map(it=>e.jsx(hss,{item:it,onEdit:Ee,onDelete:Nt=>ve.mutate(Nt),onDateChange:(Nt,Ft)=>rt.mutate({id:Nt,postDate:Ft})},it.id))})})})]}),e.jsx(vs,{open:!!g,onOpenChange:it=>{it||v(null)},children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(bs,{children:"Edit Image"})}),g&&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:g.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Caption"}),e.jsx(ur,{value:j,onChange:it=>b(it.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("flex-1 justify-start gap-2 font-normal",!N&&"text-muted-foreground"),children:[e.jsx(rn,{className:"h-4 w-4"}),N?Ss(new Date(N+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:N?new Date(N+"T00:00:00"):void 0,onSelect:it=>S(it?Ss(it,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),N&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S(null),children:e.jsx(_r,{className:"h-4 w-4"})})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),e.jsx(G,{onClick:$e,disabled:T,className:"gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},fss=()=>{const{toast:s}=Ea(),t=es(),[r,n]=k.useState("categories"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({name:"",description:"",icon:""}),[h,m]=k.useState(!1),[x,g]=k.useState(null),[v,j]=k.useState({name:"",description:"",icon:""}),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,P]=k.useState(""),{data:D=[],isLoading:B}=gt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Se,error:ze}=await H.from("community_categories").select("*").order("sort_order");if(ze)throw ze;return Se}}),{data:z=[],isLoading:F}=gt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Se,error:ze}=await H.from("community_private_groups").select("*").order("sort_order");if(ze)throw ze;return Se}}),{data:$=[]}=gt({queryKey:["admin-group-members",S==null?void 0:S.id],queryFn:async()=>{if(!S)return[];const{data:Se,error:ze}=await H.from("community_private_group_members").select("*").eq("group_id",S.id);if(ze)throw ze;return Se},enabled:!!S}),{data:X=[]}=gt({queryKey:["admin-all-profiles"],queryFn:async()=>{let ze=[],Te=0,ye=!0;for(;ye;){const{data:ct,error:ve}=await H.from("profiles").select("id, name, email, brokerage_id").order("name").range(Te,Te+1e3-1);if(ve)throw ve;ct&&ct.length>0?(ze=[...ze,...ct],Te+=1e3,ye=ct.length===1e3):ye=!1}return ze}}),{data:K=[]}=gt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Se,error:ze}=await H.from("brokerages").select("*").order("name");if(ze)throw ze;return Se}}),Q=Lt({mutationFn:async Se=>{if(Se.id){const{error:ze}=await H.from("community_categories").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(ze)throw ze}else{const ze=Math.max(...D.map(ye=>ye.sort_order),0),{error:Te}=await H.from("community_categories").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:ze+1});if(Te)throw Te}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),Y=Lt({mutationFn:async Se=>{const{error:ze}=await H.from("community_categories").delete().eq("id",Se);if(ze)throw ze},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),ne=Lt({mutationFn:async({id:Se,direction:ze})=>{const Te=D.findIndex(ye=>ye.id===Se);if(ze==="up"&&Te>0){const ye=D[Te-1],ct=D[Te];await H.from("community_categories").update({sort_order:ct.sort_order}).eq("id",ye.id),await H.from("community_categories").update({sort_order:ye.sort_order}).eq("id",ct.id)}else if(ze==="down"&&Tet.invalidateQueries({queryKey:["admin-community-categories"]})}),de=Lt({mutationFn:async Se=>{if(Se.id){const{error:ze}=await H.from("community_private_groups").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(ze)throw ze}else{const ze=Math.max(...z.map(ye=>ye.sort_order),0),{error:Te}=await H.from("community_private_groups").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:ze+1});if(Te)throw Te}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),m(!1),g(null),j({name:"",description:"",icon:""}),s({title:x?"Private group updated!":"Private group created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),ce=Lt({mutationFn:async Se=>{const{error:ze}=await H.from("community_private_groups").delete().eq("id",Se);if(ze)throw ze},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ae=Lt({mutationFn:async({id:Se,direction:ze})=>{const Te=z.findIndex(ye=>ye.id===Se);if(ze==="up"&&Te>0){const ye=z[Te-1],ct=z[Te];await H.from("community_private_groups").update({sort_order:ct.sort_order}).eq("id",ye.id),await H.from("community_private_groups").update({sort_order:ye.sort_order}).eq("id",ct.id)}else if(ze==="down"&&Tet.invalidateQueries({queryKey:["admin-private-groups"]})}),ie=Lt({mutationFn:async({groupId:Se,userId:ze,isMember:Te})=>{if(Te){const{error:ye}=await H.from("community_private_group_members").delete().eq("group_id",Se).eq("user_id",ze);if(ye)throw ye}else{const{error:ye}=await H.from("community_private_group_members").insert({group_id:Se,user_id:ze});if(ye)throw ye}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",S==null?void 0:S.id]})}}),me=Lt({mutationFn:async({groupId:Se,brokerageId:ze,isMember:Te})=>{if(Te){const{error:ye}=await H.from("community_private_group_members").delete().eq("group_id",Se).eq("brokerage_id",ze);if(ye)throw ye}else{const{error:ye}=await H.from("community_private_group_members").insert({group_id:Se,brokerage_id:ze});if(ye)throw ye}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",S==null?void 0:S.id]})}}),oe=Se=>{o(Se),d({name:Se.name,description:Se.description||"",icon:Se.icon||""}),i(!0)},ge=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},be=Se=>{g(Se),j({name:Se.name,description:Se.description||"",icon:Se.icon||""}),m(!0)},Oe=()=>{g(null),j({name:"",description:"",icon:""}),m(!0)},Me=Se=>{T(Se),P(""),N(!0)},Pe=Se=>$.some(ze=>ze.user_id===Se),Ee=Se=>$.some(ze=>ze.brokerage_id===Se),$e=X.filter(Se=>Se.name.toLowerCase().includes(A.toLowerCase())||Se.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(_s,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(Rn,{value:r,onValueChange:n,children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"categories",children:"Public Categories"}),e.jsxs(Xt,{value:"private-groups",children:[e.jsx(Kc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(as,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs(G,{onClick:ge,children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Bn,{children:B?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):D.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):D.map((Se,ze)=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:ze===0,onClick:()=>ne.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:ze===D.length-1,onClick:()=>ne.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(ft,{className:"text-2xl",children:Se.icon||"📁"}),e.jsx(ft,{className:"font-medium",children:Se.name}),e.jsx(ft,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>oe(Se),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&Y.mutate(Se.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]}),e.jsxs(as,{value:"private-groups",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(G,{onClick:Oe,children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[120px]",children:"Members"}),e.jsx(Tt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(Bn,{children:F?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):z.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):z.map((Se,ze)=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:ze===0,onClick:()=>ae.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:ze===z.length-1,onClick:()=>ae.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(ft,{className:"text-2xl",children:Se.icon||"🔒"}),e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Se.name,Se.brokerage_id?e.jsxs(Ge,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(Kc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(ft,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(ft,{children:e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>Me(Se),children:[e.jsx(fr,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1",children:[!Se.brokerage_id&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>be(Se),children:e.jsx(Ta,{className:"h-4 w-4"})}),!Se.brokerage_id&&e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&ce.mutate(Se.id)},children:e.jsx(yr,{className:"h-4 w-4"})}),Se.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Se.id))})]})})})]})]}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{children:[e.jsx(js,{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(ke,{value:c.icon,onChange:Se=>d(ze=>({...ze,icon:Se.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ke,{value:c.name,onChange:Se=>d(ze=>({...ze,name:Se.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(ur,{value:c.description,onChange:Se=>d(ze=>({...ze,description:Se.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>Q.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(vs,{open:h,onOpenChange:m,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:x?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ke,{value:v.icon,onChange:Se=>j(ze=>({...ze,icon:Se.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ke,{value:v.name,onChange:Se=>j(ze=>({...ze,name:Se.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(ur,{value:v.description,onChange:Se=>j(ze=>({...ze,description:Se.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>de.mutate({...v,id:x==null?void 0:x.id}),disabled:!v.name.trim(),children:x?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(vs,{open:b,onOpenChange:N,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(bs,{children:["Manage Members: ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Rn,{defaultValue:"brokerages",children:[e.jsxs(Dn,{className:"w-full",children:[e.jsx(Xt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Xt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(as,{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(ti,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[K.map(Se=>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(Ei,{checked:Ee(Se.id),onCheckedChange:()=>{S&&me.mutate({groupId:S.id,brokerageId:Se.id,isMember:Ee(Se.id)})}}),e.jsx("span",{className:"font-medium",children:Se.name})]}),e.jsxs(Ge,{variant:"secondary",children:[X.filter(ze=>ze.brokerage_id===Se.id).length," agents"]})]},Se.id)),K.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(as,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search users...",value:A,onChange:Se=>P(Se.target.value),className:"pl-9"})]}),e.jsx(ti,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[$e.map(Se=>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(Ei,{checked:Pe(Se.id),onCheckedChange:()=>{S&&ie.mutate({groupId:S.id,userId:Se.id,isMember:Pe(Se.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Se.email})]})]})},Se.id)),$e.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{onClick:()=>N(!1),children:"Done"})})]})]})})]})})},Zze=s=>{switch(s){case"academy_video":return e.jsx(Ho,{className:"h-3 w-3"});case"template":return e.jsx(ln,{className:"h-3 w-3"});case"toolbox":return e.jsx(Pl,{className:"h-3 w-3"});case"newsletter":return e.jsx(Vv,{className:"h-3 w-3"});case"social_swag":return e.jsx(jr,{className:"h-3 w-3"});default:return e.jsx(Yr,{className:"h-3 w-3"})}},pss=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}},xss=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}},gss=()=>{const{toast:s}=Ea(),[t,r]=k.useState([]),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,h]=k.useState(""),[m,x]=k.useState(null),[g,v]=k.useState([]),[j,b]=k.useState([]);k.useEffect(()=>{N()},[]);const N=async()=>{try{c(!0);const{data:$,error:X}=await H.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(X)throw X;const{data:K,error:Q}=await H.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 Y=[...new Set((K==null?void 0:K.map(oe=>oe.user_id))||[])],{data:ne}=await H.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",Y),de=new Map((ne==null?void 0:ne.map(oe=>[oe.id,oe]))||[]),ce=($==null?void 0:$.map(oe=>{var ge,be,Oe,Me;return{id:oe.id,user_id:oe.user_id,app_name:oe.app_name,launched_at:oe.launched_at,user_name:((ge=oe.profiles)==null?void 0:ge.name)||"Unknown",user_email:((be=oe.profiles)==null?void 0:be.email)||"Unknown",brokerage_name:((Me=(Oe=oe.profiles)==null?void 0:Oe.brokerages)==null?void 0:Me.name)||null}}))||[],ae=(K==null?void 0:K.map(oe=>{var be;const ge=de.get(oe.user_id);return{id:oe.id,user_id:oe.user_id,resource_type:oe.resource_type,resource_id:oe.resource_id,resource_title:oe.resource_title,action_type:oe.action_type,created_at:oe.created_at,user_name:(ge==null?void 0:ge.name)||"Unknown",user_email:(ge==null?void 0:ge.email)||"Unknown",brokerage_name:((be=ge==null?void 0:ge.brokerages)==null?void 0:be.name)||null}}))||[];r(ce),a(ae);const ie=new Map;ce.forEach(oe=>{if(!ie.has(oe.user_id))ie.set(oe.user_id,{user_id:oe.user_id,user_name:oe.user_name,user_email:oe.user_email,brokerage_name:oe.brokerage_name,last_activity_type:"app",last_activity_name:oe.app_name,last_activity_at:oe.launched_at,total_app_launches:1,total_content_views:0});else{const ge=ie.get(oe.user_id);ge.total_app_launches++,new Date(oe.launched_at)>new Date(ge.last_activity_at)&&(ge.last_activity_type="app",ge.last_activity_name=oe.app_name,ge.last_activity_at=oe.launched_at)}}),ae.forEach(oe=>{if(!ie.has(oe.user_id))ie.set(oe.user_id,{user_id:oe.user_id,user_name:oe.user_name,user_email:oe.user_email,brokerage_name:oe.brokerage_name,last_activity_type:oe.resource_type,last_activity_name:oe.resource_title,last_activity_at:oe.created_at,total_app_launches:0,total_content_views:1});else{const ge=ie.get(oe.user_id);ge.total_content_views++,new Date(oe.created_at)>new Date(ge.last_activity_at)&&(ge.last_activity_type=oe.resource_type,ge.last_activity_name=oe.resource_title,ge.last_activity_at=oe.created_at)}});const me=Array.from(ie.values()).sort((oe,ge)=>new Date(ge.last_activity_at).getTime()-new Date(oe.last_activity_at).getTime());l(me)}catch($){console.error("Error loading activity:",$),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},S=$=>{x({id:$.user_id,name:$.user_name,email:$.user_email});const X=t.filter(Q=>Q.user_id===$.user_id),K=n.filter(Q=>Q.user_id===$.user_id);v(X),b(K)},T=()=>{x(null),v([]),b([])},{sortKey:A,sortDirection:P,handleSort:D,sortData:B}=mz("last_activity_at","desc"),z=i.filter($=>{var K;if(!d)return!0;const X=d.toLowerCase();return $.user_name.toLowerCase().includes(X)||$.user_email.toLowerCase().includes(X)||((K=$.brokerage_name)==null?void 0:K.toLowerCase().includes(X))}),F=B(z,{user:$=>{var X;return((X=$.user_name)==null?void 0:X.toLowerCase())||""},brokerage:$=>{var X;return((X=$.brokerage_name)==null?void 0:X.toLowerCase())||""},last_activity_at:$=>new Date($.last_activity_at).getTime(),apps:$=>$.total_app_launches,content:$=>$.total_content_views});return o?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"User Activity"}),e.jsx(Nr,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:$=>h($.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Al,{sortKey:"user",currentSortKey:A,currentDirection:P,onSort:D,children:"User"}),e.jsx(Al,{sortKey:"brokerage",currentSortKey:A,currentDirection:P,onSort:D,children:"Brokerage"}),e.jsx(Tt,{children:"Last Activity"}),e.jsx(Al,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:P,onSort:D,children:"Last Active"}),e.jsx(Al,{sortKey:"apps",currentSortKey:A,currentDirection:P,onSort:D,className:"text-right",children:"Apps"}),e.jsx(Al,{sortKey:"content",currentSortKey:A,currentDirection:P,onSort:D,className:"text-right",children:"Content"})]})}),e.jsx(Bn,{children:F.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):F.map($=>e.jsxs(qs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>S($),children:[e.jsx(ft,{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(ft,{children:$.brokerage_name?e.jsx(Ge,{variant:"outline",children:$.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ft,{children:e.jsx("div",{className:"flex items-center gap-2",children:$.last_activity_type==="app"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),$.last_activity_name]}):e.jsxs(Ge,{variant:"outline",className:"flex items-center gap-1",children:[Zze($.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:$.last_activity_name})]})})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:al(new Date($.last_activity_at),{addSuffix:!0})}),e.jsx(ft,{className:"text-right",children:e.jsx(Ge,{variant:"outline",children:$.total_app_launches})}),e.jsx(ft,{className:"text-right",children:e.jsx(Ge,{variant:"outline",children:$.total_content_views})})]},$.user_id))})]})})]})]}),e.jsx(vs,{open:!!m,onOpenChange:$=>!$&&T(),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{children:[m==null?void 0:m.name,"'s Activity"]}),e.jsx(Fr,{children:m==null?void 0:m.email})]}),e.jsxs(Rn,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"content",children:["Content (",j.length,")"]}),e.jsxs(Xt,{value:"apps",children:["App Launches (",g.length,")"]})]}),e.jsx(as,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Bn,{children:j.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):j.map($=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs(Ge,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Zze($.resource_type),pss($.resource_type)]})}),e.jsx(ft,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:$.resource_title})}),e.jsx(ft,{children:e.jsx(Ge,{variant:"secondary",children:xss($.action_type)})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:al(new Date($.created_at),{addSuffix:!0})})]},$.id))})]})})}),e.jsx(as,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Bn,{children:g.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):g.map($=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx(Ge,{variant:"secondary",children:$.app_name})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:al(new Date($.launched_at),{addSuffix:!0})})]},$.id))})]})})})]})]})})]})},yss=()=>{const{toast:s}=Ea(),[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 H.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await H.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await H.from("brokerages").select("*",{count:"exact",head:!0}),{count:h}=await H.from("activity_logs").select("*",{count:"exact",head:!0}),m=new Date;m.setDate(m.getDate()-7);const{count:x}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",m.toISOString()),g=new Date;g.setMonth(g.getMonth()-1);const{count:v}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",g.toISOString()),{data:j}=await H.from("activity_logs").select("user_id").gte("launched_at",m.toISOString()),b=new Set(j==null?void 0:j.map(N=>N.user_id)).size;r({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:h||0,launchesThisWeek:x||0,launchesThisMonth:v||0,uniqueActiveThisWeek:b})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return n?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(mi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(cn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},Xze={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Qze={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 Nct({brokerageOnly:s=!1,brokerageId:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(""),[c,d]=k.useState("all");k.useEffect(()=>{h()},[t]);const h=async()=>{i(!0);try{let D=[];if(s&&t){const{data:Y}=await H.from("profiles").select("id").eq("brokerage_id",t);if(D=(Y==null?void 0:Y.map(ne=>ne.id))||[],D.length===0){n([]),i(!1);return}}let B=H.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&D.length>0&&(B=B.or(`sender_id.in.(${D.join(",")}),recipient_id.in.(${D.join(",")})`));const{data:z,error:F}=await B;if(F)throw F;const $=new Set;z==null||z.forEach(Y=>{$.add(Y.sender_id),$.add(Y.recipient_id)});const{data:X}=await H.from("profiles").select("id, name, email").in("id",Array.from($)),K=new Map((X==null?void 0:X.map(Y=>[Y.id,Y]))||[]),Q=(z==null?void 0:z.map(Y=>({...Y,sender:K.get(Y.sender_id),recipient:K.get(Y.recipient_id)})))||[];n(Q)}catch(D){console.error("Error loading shares:",D)}finally{i(!1)}},{sortKey:m,sortDirection:x,handleSort:g,sortData:v}=mz("created_at","desc"),j=r.filter(D=>{var F,$;const B=l===""||D.resource_title.toLowerCase().includes(l.toLowerCase())||((F=D.sender)==null?void 0:F.name.toLowerCase().includes(l.toLowerCase()))||(($=D.recipient)==null?void 0:$.name.toLowerCase().includes(l.toLowerCase())),z=c==="all"||D.resource_type===c;return B&&z}),b=v(j,{resource:D=>{var B;return((B=D.resource_title)==null?void 0:B.toLowerCase())||""},type:D=>D.resource_type,sender:D=>{var B,z;return((z=(B=D.sender)==null?void 0:B.name)==null?void 0:z.toLowerCase())||""},recipient:D=>{var B,z;return((z=(B=D.recipient)==null?void 0:B.name)==null?void 0:z.toLowerCase())||""},status:D=>D.is_read?1:0,created_at:D=>new Date(D.created_at).getTime()}),N=r.length,S=new Set(r.map(D=>D.sender_id)).size,T=new Set(r.map(D=>D.recipient_id)).size,A=r.length>0?Math.round(r.filter(D=>D.is_read).length/r.length*100):0,P=r.reduce((D,B)=>(D[B.resource_type]=(D[B.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,B)=>e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Vs,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(Vs,{className:"h-8 w-16"})})]},B))}),e.jsx(Ne,{children:e.jsx(De,{className:"p-6",children:e.jsx(Vs,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Pc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:N})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:S})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:T})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(P).map(([D,B])=>e.jsxs(Ge,{variant:"secondary",className:Qze[D],children:[Xze[D],": ",B]},D)),Object.keys(P).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Share History"}),e.jsxs(Nr,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(De,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:c,onValueChange:d,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Resource type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),e.jsx(mt,{value:"event",children:"Events"}),e.jsx(mt,{value:"template",children:"Templates"}),e.jsx(mt,{value:"academy_video",children:"Academy Videos"}),e.jsx(mt,{value:"resource_kit",children:"Resource Kits"}),e.jsx(mt,{value:"newsletter",children:"Newsletters"}),e.jsx(mt,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(ti,{className:"h-[400px]",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Al,{sortKey:"resource",currentSortKey:m,currentDirection:x,onSort:g,children:"Resource"}),e.jsx(Al,{sortKey:"type",currentSortKey:m,currentDirection:x,onSort:g,children:"Type"}),e.jsx(Al,{sortKey:"sender",currentSortKey:m,currentDirection:x,onSort:g,children:"Sender"}),e.jsx(Al,{sortKey:"recipient",currentSortKey:m,currentDirection:x,onSort:g,children:"Recipient"}),e.jsx(Al,{sortKey:"status",currentSortKey:m,currentDirection:x,onSort:g,children:"Status"}),e.jsx(Al,{sortKey:"created_at",currentSortKey:m,currentDirection:x,onSort:g,children:"Date"})]})}),e.jsx(Bn,{children:b.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):b.map(D=>{var B,z;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium max-w-[200px] truncate",children:D.resource_title}),e.jsx(ft,{children:e.jsx(Ge,{variant:"secondary",className:Qze[D.resource_type],children:Xze[D.resource_type]})}),e.jsx(ft,{children:((B=D.sender)==null?void 0:B.name)||"Unknown"}),e.jsx(ft,{children:((z=D.recipient)==null?void 0:z.name)||"Unknown"}),e.jsx(ft,{children:e.jsx(Ge,{variant:D.is_read?"default":"outline",children:D.is_read?"Read":"Unread"})}),e.jsx(ft,{className:"text-muted-foreground",children:Ss(new Date(D.created_at),"MMM d, yyyy")})]},D.id)})})]})})]})]})]})}const Obe={academy_video:{label:"Academy Videos",icon:sn,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:jn},template:{label:"Templates",icon:Pb,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:tm},toolbox:{label:"Toolkit",icon:i0,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Xa},newsletter:{label:"Newsletters",icon:Qs,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:tm},social_swag:{label:"Social Swag",icon:pl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:tm},event:{label:"Events",icon:rn,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:tm}};function Jze(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function vss(s,t){return s==="toolbox"?t.downloads:t.clicks}function bss(){var D;const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(null),l=k.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=mz("total_views","desc");k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:B,error:z}=await H.rpc("get_admin_content_engagement");if(z)throw z;t(B||[])}catch(B){console.error("Error loading content engagement:",B)}finally{n(!1)}},x=B=>{i(z=>{const F=z===B?null:B;return requestAnimationFrame(()=>{var $;($=l.current)==null||$.scrollIntoView({behavior:"smooth",block:"start"})}),F})};if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((B,z)=>e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Vs,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(Vs,{className:"h-8 w-16"})})]},z))}),e.jsx(Ne,{children:e.jsx(De,{className:"py-8",children:e.jsx(Vs,{className:"h-64 w-full"})})})]});const g=s.reduce((B,z)=>B+z.total_views,0),v=s.reduce((B,z)=>B+z.total_clicks,0),j=s.reduce((B,z)=>B+z.total_downloads,0),b=s.length,N=s.reduce((B,z)=>(B[z.resource_type]||(B[z.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),B[z.resource_type].views+=z.total_views,B[z.resource_type].clicks+=z.total_clicks,B[z.resource_type].downloads+=z.total_downloads,B[z.resource_type].assets+=1,B[z.resource_type].uniqueUsers+=z.unique_users,B),{}),S=a?s.filter(B=>B.resource_type===a):s,T=h(S,{asset:B=>{var z;return((z=B.resource_title)==null?void 0:z.toLowerCase())||""},type:B=>B.resource_type,views:B=>B.total_views,actions:B=>Jze(B),unique_users:B=>B.unique_users,last_activity:B=>B.last_engaged_at?new Date(B.last_engaged_at).getTime():0}),A=a?Obe[a]||{label:a,icon:jn,actionLabel:"Actions"}:null,P=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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(tm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:j.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(tm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[g>0?Math.round((v+j)/g*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Nr,{children:"Click a category to see individual asset performance"})]}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(N).map(([B,z])=>{const F=Obe[B]||{label:B,icon:jn,color:"bg-muted text-muted-foreground",actionIcon:tm},$=F.icon,X=a===B;return e.jsxs("button",{type:"button",onClick:()=>x(B),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${X?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${F.color}`,children:e.jsx($,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:F.label}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"})," ",z.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(F.actionIcon,{className:"h-3 w-3"})," ",vss(B,z)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3 w-3"})," ",z.uniqueUsers]})]})]}),e.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[z.assets," items"]})]},B)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-sm font-medium flex items-center gap-2",children:A&&P?e.jsxs(e.Fragment,{children:[e.jsx(P,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Nr,{children:a?`${S.length} ${((D=A==null?void 0:A.label)==null?void 0:D.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(wa,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(De,{children:S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(ti,{className:"h-[400px]",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[40px]",children:"#"}),e.jsx(Al,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Al,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Al,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Al,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(Al,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Al,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(Bn,{children:T.map((B,z)=>{const F=Obe[B.resource_type]||{label:B.resource_type,color:"bg-muted text-muted-foreground"};return e.jsxs(qs,{children:[e.jsx(ft,{className:"text-muted-foreground text-xs",children:z+1}),e.jsx(ft,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:B.resource_title})}),!a&&e.jsx(ft,{children:e.jsx(Ge,{className:`text-[10px] ${F.color}`,children:F.label})}),e.jsx(ft,{className:"text-right font-medium",children:B.total_views}),e.jsx(ft,{className:"text-right font-medium",children:Jze(B)}),e.jsx(ft,{className:"text-right",children:B.unique_users}),e.jsx(ft,{className:"text-xs text-muted-foreground",children:B.last_engaged_at?al(new Date(B.last_engaged_at),{addSuffix:!0}):"—"})]},`${B.resource_type}-${B.resource_id}`)})})]})})})]})})]})}var _ss=Array.isArray,wp=_ss,wss=typeof su=="object"&&su&&su.Object===Object&&su,kct=wss,jss=kct,Nss=typeof self=="object"&&self&&self.Object===Object&&self,kss=jss||Nss||Function("return this")(),b1=kss,Sss=b1,Css=Sss.Symbol,vz=Css,e7e=vz,Sct=Object.prototype,Tss=Sct.hasOwnProperty,Ess=Sct.toString,KD=e7e?e7e.toStringTag:void 0;function Ass(s){var t=Tss.call(s,KD),r=s[KD];try{s[KD]=void 0;var n=!0}catch{}var a=Ess.call(s);return n&&(t?s[KD]=r:delete s[KD]),a}var Mss=Ass,Iss=Object.prototype,Pss=Iss.toString;function Lss(s){return Pss.call(s)}var Dss=Lss,t7e=vz,Rss=Mss,Oss=Dss,Fss="[object Null]",Bss="[object Undefined]",s7e=t7e?t7e.toStringTag:void 0;function zss(s){return s==null?s===void 0?Bss:Fss:s7e&&s7e in Object(s)?Rss(s):Oss(s)}var L_=zss;function $ss(s){return s!=null&&typeof s=="object"}var D_=$ss,Uss=L_,qss=D_,Vss="[object Symbol]";function Hss(s){return typeof s=="symbol"||qss(s)&&Uss(s)==Vss}var $P=Hss,Gss=wp,Wss=$P,Kss=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yss=/^\w*$/;function Zss(s,t){if(Gss(s))return!1;var r=typeof s;return r=="number"||r=="symbol"||r=="boolean"||s==null||Wss(s)?!0:Yss.test(s)||!Kss.test(s)||t!=null&&s in Object(t)}var YTe=Zss;function Xss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var eN=Xss;const UP=Io(eN);var Qss=L_,Jss=eN,ers="[object AsyncFunction]",trs="[object Function]",srs="[object GeneratorFunction]",rrs="[object Proxy]";function nrs(s){if(!Jss(s))return!1;var t=Qss(s);return t==trs||t==srs||t==ers||t==rrs}var ZTe=nrs;const Ti=Io(ZTe);var ars=b1,irs=ars["__core-js_shared__"],ors=irs,Fbe=ors,r7e=function(){var s=/[^.]+$/.exec(Fbe&&Fbe.keys&&Fbe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function lrs(s){return!!r7e&&r7e in s}var crs=lrs,drs=Function.prototype,urs=drs.toString;function hrs(s){if(s!=null){try{return urs.call(s)}catch{}try{return s+""}catch{}}return""}var Cct=hrs,mrs=ZTe,frs=crs,prs=eN,xrs=Cct,grs=/[\\^$.*+?()[\]{}|]/g,yrs=/^\[object .+?Constructor\]$/,vrs=Function.prototype,brs=Object.prototype,_rs=vrs.toString,wrs=brs.hasOwnProperty,jrs=RegExp("^"+_rs.call(wrs).replace(grs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Nrs(s){if(!prs(s)||frs(s))return!1;var t=mrs(s)?jrs:yrs;return t.test(xrs(s))}var krs=Nrs;function Srs(s,t){return s==null?void 0:s[t]}var Crs=Srs,Trs=krs,Ers=Crs;function Ars(s,t){var r=Ers(s,t);return Trs(r)?r:void 0}var X5=Ars,Mrs=X5,Irs=Mrs(Object,"create"),Lxe=Irs,n7e=Lxe;function Prs(){this.__data__=n7e?n7e(null):{},this.size=0}var Lrs=Prs;function Drs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Rrs=Drs,Ors=Lxe,Frs="__lodash_hash_undefined__",Brs=Object.prototype,zrs=Brs.hasOwnProperty;function $rs(s){var t=this.__data__;if(Ors){var r=t[s];return r===Frs?void 0:r}return zrs.call(t,s)?t[s]:void 0}var Urs=$rs,qrs=Lxe,Vrs=Object.prototype,Hrs=Vrs.hasOwnProperty;function Grs(s){var t=this.__data__;return qrs?t[s]!==void 0:Hrs.call(t,s)}var Wrs=Grs,Krs=Lxe,Yrs="__lodash_hash_undefined__";function Zrs(s,t){var r=this.__data__;return this.size+=this.has(s)?0:1,r[s]=Krs&&t===void 0?Yrs:t,this}var Xrs=Zrs,Qrs=Lrs,Jrs=Rrs,ens=Urs,tns=Wrs,sns=Xrs;function qP(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t-1}var vns=yns,bns=Dxe;function _ns(s,t){var r=this.__data__,n=bns(r,s);return n<0?(++this.size,r.push([s,t])):r[n][1]=t,this}var wns=_ns,jns=ans,Nns=mns,kns=xns,Sns=vns,Cns=wns;function VP(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t0?1:-1},Q4=function(t){return E5(t)&&t.indexOf("%")===t.length-1},wn=function(t){return Was(t)&&!bz(t)},Xas=function(t){return Fi(t)},Gu=function(t){return wn(t)||E5(t)},Qas=0,GP=function(t){var r=++Qas;return"".concat(t||"").concat(r)},wf=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(!wn(t)&&!E5(t))return n;var i;if(Q4(t)){var l=t.indexOf("%");i=r*parseFloat(t.slice(0,l))/100}else i=+t;return bz(i)&&(i=n),a&&i>r&&(i=r),i},pj=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},Jas=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 iis(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 HNe(s){"@babel/helpers - typeof";return HNe=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},HNe(s)}var u7e={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"},l_=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},h7e=null,zbe=null,iEe=function s(t){if(t===h7e&&Array.isArray(zbe))return zbe;var r=[];return k.Children.forEach(t,function(n){Fi(n)||(Uas.isFragment(n)?r=r.concat(s(n.props.children)):r.push(n))}),zbe=r,h7e=t,r};function Sx(s,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(a){return l_(a)}):n=[l_(t)],iEe(s).forEach(function(a){var i=kx(a,"type.displayName")||kx(a,"type.name");n.indexOf(i)!==-1&&r.push(a)}),r}function tx(s,t){var r=Sx(s,t);return r&&r[0]}var m7e=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,a=r.height;return!(!wn(n)||n<=0||!wn(a)||a<=0)},ois=["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"],lis=function(t){return t&&t.type&&E5(t.type)&&ois.indexOf(t.type)>=0},cis=function(t){return t&&HNe(t)==="object"&&"clipDot"in t},dis=function(t,r,n,a){var i,l=(i=Bbe==null?void 0:Bbe[a])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!Ti(t)&&(a&&l.includes(r)||sis.includes(r))||n&&aEe.includes(r)},oi=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(k.isValidElement(t)&&(a=t.props),!UP(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;dis((o=a)===null||o===void 0?void 0:o[l],l,r,n)&&(i[l]=a[l])}),i},GNe=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 f7e(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 pis(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 KNe(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=fis(s,mis),h=a||{width:r,height:n,x:0,y:0},m=Ui("recharts-surface",i);return wt.createElement("svg",WNe({},oi(d,!0,"svg"),{className:m,width:r,height:n,style:l,viewBox:"".concat(h.x," ").concat(h.y," ").concat(h.width," ").concat(h.height)}),wt.createElement("title",null,o),wt.createElement("desc",null,c),t)}var xis=["children","className"];function YNe(){return YNe=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 yis(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 tl=wt.forwardRef(function(s,t){var r=s.children,n=s.className,a=gis(s,xis),i=Ui("recharts-layer",n);return wt.createElement("g",YNe({className:i},oi(a,!0),{ref:t}),r)}),l0=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:_is(s,t,r)}var jis=wis,Nis="\\ud800-\\udfff",kis="\\u0300-\\u036f",Sis="\\ufe20-\\ufe2f",Cis="\\u20d0-\\u20ff",Tis=kis+Sis+Cis,Eis="\\ufe0e\\ufe0f",Ais="\\u200d",Mis=RegExp("["+Ais+Nis+Tis+Eis+"]");function Iis(s){return Mis.test(s)}var Oct=Iis;function Pis(s){return s.split("")}var Lis=Pis,Fct="\\ud800-\\udfff",Dis="\\u0300-\\u036f",Ris="\\ufe20-\\ufe2f",Ois="\\u20d0-\\u20ff",Fis=Dis+Ris+Ois,Bis="\\ufe0e\\ufe0f",zis="["+Fct+"]",ZNe="["+Fis+"]",XNe="\\ud83c[\\udffb-\\udfff]",$is="(?:"+ZNe+"|"+XNe+")",Bct="[^"+Fct+"]",zct="(?:\\ud83c[\\udde6-\\uddff]){2}",$ct="[\\ud800-\\udbff][\\udc00-\\udfff]",Uis="\\u200d",Uct=$is+"?",qct="["+Bis+"]?",qis="(?:"+Uis+"(?:"+[Bct,zct,$ct].join("|")+")"+qct+Uct+")*",Vis=qct+Uct+qis,His="(?:"+[Bct+ZNe+"?",ZNe,zct,$ct,zis].join("|")+")",Gis=RegExp(XNe+"(?="+XNe+")|"+His+Vis,"g");function Wis(s){return s.match(Gis)||[]}var Kis=Wis,Yis=Lis,Zis=Oct,Xis=Kis;function Qis(s){return Zis(s)?Xis(s):Yis(s)}var Jis=Qis,eos=jis,tos=Oct,sos=Jis,ros=Mct;function nos(s){return function(t){t=ros(t);var r=tos(t)?sos(t):void 0,n=r?r[0]:t.charAt(0),a=r?eos(r,1).join(""):t.slice(1);return n[s]()+a}}var aos=nos,ios=aos,oos=ios("toUpperCase"),los=oos;const Yxe=Io(los);function dc(s){return function(){return s}}const Vct=Math.cos,eme=Math.sin,v0=Math.sqrt,tme=Math.PI,Zxe=2*tme,QNe=Math.PI,JNe=2*QNe,E4=1e-6,cos=JNe-E4;function Hct(s){this._+=s[0];for(let t=1,r=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return Hct;const r=10**t;return function(n){this._+=n[0];for(let a=1,i=n.length;aE4)if(!(Math.abs(m*c-d*h)>E4)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let g=n-l,v=a-o,j=c*c+d*d,b=g*g+v*v,N=Math.sqrt(j),S=Math.sqrt(x),T=i*Math.tan((QNe-Math.acos((j+x-b)/(2*N*S)))/2),A=T/S,P=T/N;Math.abs(A-1)>E4&&this._append`L${t+A*h},${r+A*m}`,this._append`A${i},${i},0,0,${+(m*g>h*v)},${this._x1=t+P*c},${this._y1=r+P*d}`}}arc(t,r,n,a,i,l){if(t=+t,r=+r,n=+n,l=!!l,n<0)throw new Error(`negative radius: ${n}`);let o=n*Math.cos(a),c=n*Math.sin(a),d=t+o,h=r+c,m=1^l,x=l?a-i:i-a;this._x1===null?this._append`M${d},${h}`:(Math.abs(this._x1-d)>E4||Math.abs(this._y1-h)>E4)&&this._append`L${d},${h}`,n&&(x<0&&(x=x%JNe+JNe),x>cos?this._append`A${n},${n},0,1,${m},${t-o},${r-c}A${n},${n},0,1,${m},${this._x1=d},${this._y1=h}`:x>E4&&this._append`A${n},${n},0,${+(x>=QNe)},${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 oEe(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 uos(t)}function lEe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function Gct(s){this._context=s}Gct.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 Xxe(s){return new Gct(s)}function Wct(s){return s[0]}function Kct(s){return s[1]}function Yct(s,t){var r=dc(!0),n=null,a=Xxe,i=null,l=oEe(o);s=typeof s=="function"?s:s===void 0?Wct:dc(s),t=typeof t=="function"?t:t===void 0?Kct:dc(t);function o(c){var d,h=(c=lEe(c)).length,m,x=!1,g;for(n==null&&(i=a(g=l())),d=0;d<=h;++d)!(d=g;--v)o.point(T[v],A[v]);o.lineEnd(),o.areaEnd()}N&&(T[x]=+s(b,x,m),A[x]=+t(b,x,m),o.point(n?+n(b,x,m):T[x],r?+r(b,x,m):A[x]))}if(S)return o=null,S+""||null}function h(){return Yct().defined(a).curve(l).context(i)}return d.x=function(m){return arguments.length?(s=typeof m=="function"?m:dc(+m),n=null,d):s},d.x0=function(m){return arguments.length?(s=typeof m=="function"?m:dc(+m),d):s},d.x1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:dc(+m),d):n},d.y=function(m){return arguments.length?(t=typeof m=="function"?m:dc(+m),r=null,d):t},d.y0=function(m){return arguments.length?(t=typeof m=="function"?m:dc(+m),d):t},d.y1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:dc(+m),d):r},d.lineX0=d.lineY0=function(){return h().x(s).y(t)},d.lineY1=function(){return h().x(s).y(r)},d.lineX1=function(){return h().x(n).y(t)},d.defined=function(m){return arguments.length?(a=typeof m=="function"?m:dc(!!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 Zct{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 hos(s){return new Zct(s,!0)}function mos(s){return new Zct(s,!1)}const cEe={draw(s,t){const r=v0(t/tme);s.moveTo(r,0),s.arc(0,0,r,0,Zxe)}},fos={draw(s,t){const r=v0(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()}},Xct=v0(1/3),pos=Xct*2,xos={draw(s,t){const r=v0(t/pos),n=r*Xct;s.moveTo(0,-r),s.lineTo(n,0),s.lineTo(0,r),s.lineTo(-n,0),s.closePath()}},gos={draw(s,t){const r=v0(t),n=-r/2;s.rect(n,n,r,r)}},yos=.8908130915292852,Qct=eme(tme/10)/eme(7*tme/10),vos=eme(Zxe/10)*Qct,bos=-Vct(Zxe/10)*Qct,_os={draw(s,t){const r=v0(t*yos),n=vos*r,a=bos*r;s.moveTo(0,-r),s.lineTo(n,a);for(let i=1;i<5;++i){const l=Zxe*i/5,o=Vct(l),c=eme(l);s.lineTo(c*r,-o*r),s.lineTo(o*n-c*a,c*n+o*a)}s.closePath()}},$be=v0(3),wos={draw(s,t){const r=-v0(t/($be*3));s.moveTo(0,r*2),s.lineTo(-$be*r,-r),s.lineTo($be*r,-r),s.closePath()}},mg=-.5,fg=v0(3)/2,eke=1/v0(12),jos=(eke/2+1)*3,Nos={draw(s,t){const r=v0(t/jos),n=r/2,a=r*eke,i=n,l=r*eke+r,o=-i,c=l;s.moveTo(n,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(mg*n-fg*a,fg*n+mg*a),s.lineTo(mg*i-fg*l,fg*i+mg*l),s.lineTo(mg*o-fg*c,fg*o+mg*c),s.lineTo(mg*n+fg*a,mg*a-fg*n),s.lineTo(mg*i+fg*l,mg*l-fg*i),s.lineTo(mg*o+fg*c,mg*c-fg*o),s.closePath()}};function kos(s,t){let r=null,n=oEe(a);s=typeof s=="function"?s:dc(s||cEe),t=typeof t=="function"?t:dc(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:dc(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:dc(+i),a):t},a.context=function(i){return arguments.length?(r=i??null,a):r},a}function sme(){}function rme(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 Jct(s){this._context=s}Jct.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:rme(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:rme(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Sos(s){return new Jct(s)}function edt(s){this._context=s}edt.prototype={areaStart:sme,areaEnd:sme,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:rme(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Cos(s){return new edt(s)}function tdt(s){this._context=s}tdt.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:rme(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Tos(s){return new tdt(s)}function sdt(s){this._context=s}sdt.prototype={areaStart:sme,areaEnd:sme,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 Eos(s){return new sdt(s)}function x7e(s){return s<0?-1:1}function g7e(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(x7e(i)+x7e(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function y7e(s,t){var r=s._x1-s._x0;return r?(3*(s._y1-s._y0)/r-t)/2:t}function Ube(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 nme(s){this._context=s}nme.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:Ube(this,this._t0,y7e(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,Ube(this,y7e(this,r=g7e(this,s,t)),r);break;default:Ube(this,this._t0,r=g7e(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=r}}};function rdt(s){this._context=new ndt(s)}(rdt.prototype=Object.create(nme.prototype)).point=function(s,t){nme.prototype.point.call(this,t,s)};function ndt(s){this._context=s}ndt.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 Aos(s){return new nme(s)}function Mos(s){return new rdt(s)}function adt(s){this._context=s}adt.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=v7e(s),a=v7e(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 Pos(s){return new Qxe(s,.5)}function Los(s){return new Qxe(s,0)}function Dos(s){return new Qxe(s,1)}function TI(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 Ros(s,t){return s[t]}function Oos(s){const t=[];return t.key=s,t}function Fos(){var s=dc([]),t=tke,r=TI,n=Ros;function a(i){var l=Array.from(s.apply(this,arguments),Oos),o,c=l.length,d=-1,h;for(const m of i)for(o=0,++d;o0){for(var r,n,a=0,i=s[0].length,l;a0){for(var r=0,n=s[t[0]],a,i=n.length;r0)||!((i=(a=s[t[0]]).length)>0))){for(var r=0,n=1,a,i,l;n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Wos(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 idt={symbolCircle:cEe,symbolCross:fos,symbolDiamond:xos,symbolSquare:gos,symbolStar:_os,symbolTriangle:wos,symbolWye:Nos},Kos=Math.PI/180,Yos=function(t){var r="symbol".concat(Yxe(t));return idt[r]||cEe},Zos=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*Kos;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}},Xos=function(t,r){idt["symbol".concat(Yxe(t))]=r},dEe=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=Gos(t,Uos),d=_7e(_7e({},c),{},{type:n,size:i,sizeType:o}),h=function(){var b=Yos(n),N=kos().type(b).size(Zos(i,o,n));return N()},m=d.className,x=d.cx,g=d.cy,v=oi(d,!0);return x===+x&&g===+g&&i===+i?wt.createElement("path",ske({},v,{className:Ui("recharts-symbols",m),transform:"translate(".concat(x,", ").concat(g,")"),d:h()})):null};dEe.registerSymbol=Xos;function EI(s){"@babel/helpers - typeof";return EI=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},EI(s)}function rke(){return rke=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var S=g.inactive?d:g.color;return wt.createElement("li",rke({className:b,style:m,key:"legend-item-".concat(v)},A5(n.props,g,v)),wt.createElement(KNe,{width:l,height:l,viewBox:h,style:x},n.renderIcon(g)),wt.createElement("span",{className:"recharts-legend-item-text",style:{color:S}},j?j(N,g,v):N))})}},{key:"render",value:function(){var n=this.props,a=n.payload,i=n.layout,l=n.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return wt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(k.PureComponent);SF(uEe,"displayName","Legend");SF(uEe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var ols=Rxe;function lls(){this.__data__=new ols,this.size=0}var cls=lls;function dls(s){var t=this.__data__,r=t.delete(s);return this.size=t.size,r}var uls=dls;function hls(s){return this.__data__.get(s)}var mls=hls;function fls(s){return this.__data__.has(s)}var pls=fls,xls=Rxe,gls=QTe,yls=JTe,vls=200;function bls(s,t){var r=this.__data__;if(r instanceof xls){var n=r.__data__;if(!gls||n.lengtho))return!1;var d=i.get(s),h=i.get(t);if(d&&h)return d==t&&h==s;var m=-1,x=!0,g=r&Uls?new Fls:void 0;for(i.set(s,t),i.set(t,s);++m-1&&s%1==0&&s-1&&s%1==0&&s<=Gcs}var pEe=Wcs,Kcs=L_,Ycs=pEe,Zcs=D_,Xcs="[object Arguments]",Qcs="[object Array]",Jcs="[object Boolean]",eds="[object Date]",tds="[object Error]",sds="[object Function]",rds="[object Map]",nds="[object Number]",ads="[object Object]",ids="[object RegExp]",ods="[object Set]",lds="[object String]",cds="[object WeakMap]",dds="[object ArrayBuffer]",uds="[object DataView]",hds="[object Float32Array]",mds="[object Float64Array]",fds="[object Int8Array]",pds="[object Int16Array]",xds="[object Int32Array]",gds="[object Uint8Array]",yds="[object Uint8ClampedArray]",vds="[object Uint16Array]",bds="[object Uint32Array]",Cc={};Cc[hds]=Cc[mds]=Cc[fds]=Cc[pds]=Cc[xds]=Cc[gds]=Cc[yds]=Cc[vds]=Cc[bds]=!0;Cc[Xcs]=Cc[Qcs]=Cc[dds]=Cc[Jcs]=Cc[uds]=Cc[eds]=Cc[tds]=Cc[sds]=Cc[rds]=Cc[nds]=Cc[ads]=Cc[ids]=Cc[ods]=Cc[lds]=Cc[cds]=!1;function _ds(s){return Zcs(s)&&Ycs(s.length)&&!!Cc[Kcs(s)]}var wds=_ds;function jds(s){return function(t){return s(t)}}var gdt=jds,lme={exports:{}};lme.exports;(function(s,t){var r=kct,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})(lme,lme.exports);var Nds=lme.exports,kds=wds,Sds=gdt,T7e=Nds,E7e=T7e&&T7e.isTypedArray,Cds=E7e?Sds(E7e):kds,ydt=Cds,Tds=Mcs,Eds=mEe,Ads=wp,Mds=xdt,Ids=fEe,Pds=ydt,Lds=Object.prototype,Dds=Lds.hasOwnProperty;function Rds(s,t){var r=Ads(s),n=!r&&Eds(s),a=!r&&!n&&Mds(s),i=!r&&!n&&!a&&Pds(s),l=r||n||a||i,o=l?Tds(s.length,String):[],c=o.length;for(var d in s)(t||Dds.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Ids(d,c)))&&o.push(d);return o}var Ods=Rds,Fds=Object.prototype;function Bds(s){var t=s&&s.constructor,r=typeof t=="function"&&t.prototype||Fds;return s===r}var zds=Bds;function $ds(s,t){return function(r){return s(t(r))}}var vdt=$ds,Uds=vdt,qds=Uds(Object.keys,Object),Vds=qds,Hds=zds,Gds=Vds,Wds=Object.prototype,Kds=Wds.hasOwnProperty;function Yds(s){if(!Hds(s))return Gds(s);var t=[];for(var r in Object(s))Kds.call(s,r)&&r!="constructor"&&t.push(r);return t}var Zds=Yds,Xds=ZTe,Qds=pEe;function Jds(s){return s!=null&&Qds(s.length)&&!Xds(s)}var _z=Jds,eus=Ods,tus=Zds,sus=_z;function rus(s){return sus(s)?eus(s):tus(s)}var Jxe=rus,nus=vcs,aus=Ecs,ius=Jxe;function ous(s){return nus(s,ius,aus)}var lus=ous,A7e=lus,cus=1,dus=Object.prototype,uus=dus.hasOwnProperty;function hus(s,t,r,n,a,i){var l=r&cus,o=A7e(s),c=o.length,d=A7e(t),h=d.length;if(c!=h&&!l)return!1;for(var m=c;m--;){var x=o[m];if(!(l?x in t:uus.call(t,x)))return!1}var g=i.get(s),v=i.get(t);if(g&&v)return g==t&&v==s;var j=!0;i.set(s,t),i.set(t,s);for(var b=l;++m-1}var dms=cms;function ums(s,t,r){for(var n=-1,a=s==null?0:s.length;++n=Sms){var d=t?null:Nms(s);if(d)return kms(d);l=!1,a=jms,c=new bms}else c=t?[]:o;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Ums(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 qms(s){return s.value}function Vms(s,t){if(wt.isValidElement(s))return wt.cloneElement(s,t);if(typeof s=="function")return wt.createElement(s,t);t.ref;var r=$ms(t,Pms);return wt.createElement(uEe,r)}var G7e=1,MM=function(s){function t(){var r;Lms(this,t);for(var n=arguments.length,a=new Array(n),i=0;iG7e||Math.abs(a.height-this.lastBoundingBox.height)>G7e)&&(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?pb({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,h=a.chartHeight,m,x;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(l==="center"&&i==="vertical"){var g=this.getBBoxSnapshot();m={left:((d||0)-g.width)/2}}else m=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(o==="middle"){var v=this.getBBoxSnapshot();x={top:((h||0)-v.height)/2}}else x=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return pb(pb({},m),x)}},{key:"render",value:function(){var n=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,h=a.payload,m=pb(pb({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return wt.createElement("div",{className:"recharts-legend-wrapper",style:m,ref:function(g){n.wrapperNode=g}},Vms(i,pb(pb({},this.props),{},{payload:Sdt(h,d,qms)})))}}],[{key:"getWithHeight",value:function(n,a){var i=pb(pb({},this.defaultProps),n.props),l=i.layout;return l==="vertical"&&wn(n.props.height)?{height:n.props.height}:l==="horizontal"?{width:n.props.width||a}:null}}])}(k.PureComponent);ege(MM,"displayName","Legend");ege(MM,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var W7e=vz,Hms=mEe,Gms=wp,K7e=W7e?W7e.isConcatSpreadable:void 0;function Wms(s){return Gms(s)||Hms(s)||!!(K7e&&s&&s[K7e])}var Kms=Wms,Yms=fdt,Zms=Kms;function Edt(s,t,r,n,a){var i=-1,l=s.length;for(r||(r=Zms),a||(a=[]);++i0&&r(o)?t>1?Edt(o,t-1,r,n,a):Yms(a,o):n||(a[a.length]=o)}return a}var Adt=Edt;function Xms(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 Qms=Xms,Jms=Qms,efs=Jms(),tfs=efs,sfs=tfs,rfs=Jxe;function nfs(s,t){return s&&sfs(s,t,rfs)}var Mdt=nfs,afs=_z;function ifs(s,t){return function(r,n){if(r==null)return r;if(!afs(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 bfs=vfs,Gbe=tEe,_fs=sEe,wfs=_1,jfs=Idt,Nfs=pfs,kfs=gdt,Sfs=bfs,Cfs=YP,Tfs=wp;function Efs(s,t,r){t.length?t=Gbe(t,function(i){return Tfs(i)?function(l){return _fs(l,i.length===1?i[0]:i)}:i}):t=[Cfs];var n=-1;t=Gbe(t,kfs(wfs));var a=jfs(s,function(i,l,o){var c=Gbe(t,function(d){return d(i)});return{criteria:c,index:++n,value:i}});return Nfs(a,function(i,l){return Sfs(i,l,r)})}var Afs=Efs;function Mfs(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 Ifs=Mfs,Pfs=Ifs,Z7e=Math.max;function Lfs(s,t,r){return t=Z7e(t===void 0?s.length-1:t,0),function(){for(var n=arguments,a=-1,i=Z7e(n.length-t,0),l=Array(i);++a0){if(++t>=Vfs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Kfs=Wfs,Yfs=qfs,Zfs=Kfs,Xfs=Zfs(Yfs),Qfs=Xfs,Jfs=YP,eps=Dfs,tps=Qfs;function sps(s,t){return tps(eps(s,t,Jfs),s+"")}var rps=sps,nps=XTe,aps=_z,ips=fEe,ops=eN;function lps(s,t,r){if(!ops(r))return!1;var n=typeof t;return(n=="number"?aps(r)&&ips(t,r.length):n=="string"&&t in r)?nps(r[t],s):!1}var tge=lps,cps=Adt,dps=Afs,ups=rps,Q7e=tge,hps=ups(function(s,t){if(s==null)return[];var r=t.length;return r>1&&Q7e(s,t[0],t[1])?t=[]:r>2&&Q7e(t[0],t[1],t[2])&&(t=[t[0]]),dps(s,cps(t,1),[])}),mps=hps;const yEe=Io(mps);function CF(s){"@babel/helpers - typeof";return CF=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},CF(s)}function uke(){return uke=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(YD,"-left"),wn(r)&&t&&wn(t.x)&&r=t.y),"".concat(YD,"-top"),wn(n)&&t&&wn(t.y)&&nj?Math.max(h,c[n]):Math.max(m,c[n])}function Tps(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 Eps(s){var t=s.allowEscapeViewBox,r=s.coordinate,n=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,h,m;return l.height>0&&l.width>0&&r?(h=t9e({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),m=t9e({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=Tps({translateX:h,translateY:m,useTranslate3d:o})):d=Sps,{cssProperties:d,cssClasses:Cps({translateX:h,translateY:m,coordinate:r})}}function MI(s){"@babel/helpers - typeof";return MI=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},MI(s)}function s9e(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 r9e(s){for(var t=1;tn9e||Math.abs(n.height-this.state.lastBoundingBox.height)>n9e)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,h=a.coordinate,m=a.hasPayload,x=a.isAnimationActive,g=a.offset,v=a.position,j=a.reverseDirection,b=a.useTranslate3d,N=a.viewBox,S=a.wrapperStyle,T=Eps({allowEscapeViewBox:l,coordinate:h,offsetTopLeft:g,position:v,reverseDirection:j,tooltipBox:this.state.lastBoundingBox,useTranslate3d:b,viewBox:N}),A=T.cssClasses,P=T.cssProperties,D=r9e(r9e({transition:x&&i?"transform ".concat(o,"ms ").concat(c):void 0},P),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&m?"visible":"hidden",position:"absolute",top:0,left:0},S);return wt.createElement("div",{tabIndex:-1,className:A,style:D,ref:function(z){n.wrapperNode=z}},d)}}])}(k.PureComponent),Bps=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Q5={isSsr:Bps()};function II(s){"@babel/helpers - typeof";return II=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},II(s)}function a9e(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 i9e(s){for(var t=1;t0;return wt.createElement(Fps,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:x,active:i,coordinate:h,hasPayload:D,offset:g,position:b,reverseDirection:N,useTranslate3d:S,viewBox:T,wrapperStyle:A},Yps(d,i9e(i9e({},this.props),{},{payload:P})))}}])}(k.PureComponent);vEe(rp,"displayName","Tooltip");vEe(rp,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Q5.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 Zps=b1,Xps=function(){return Zps.Date.now()},Qps=Xps,Jps=/\s/;function exs(s){for(var t=s.length;t--&&Jps.test(s.charAt(t)););return t}var txs=exs,sxs=txs,rxs=/^\s+/;function nxs(s){return s&&s.slice(0,sxs(s)+1).replace(rxs,"")}var axs=nxs,ixs=axs,o9e=eN,oxs=$P,l9e=NaN,lxs=/^[-+]0x[0-9a-f]+$/i,cxs=/^0b[01]+$/i,dxs=/^0o[0-7]+$/i,uxs=parseInt;function hxs(s){if(typeof s=="number")return s;if(oxs(s))return l9e;if(o9e(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=o9e(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=ixs(s);var r=cxs.test(s);return r||dxs.test(s)?uxs(s.slice(2),r?2:8):lxs.test(s)?l9e:+s}var Fdt=hxs,mxs=eN,Kbe=Qps,c9e=Fdt,fxs="Expected a function",pxs=Math.max,xxs=Math.min;function gxs(s,t,r){var n,a,i,l,o,c,d=0,h=!1,m=!1,x=!0;if(typeof s!="function")throw new TypeError(fxs);t=c9e(t)||0,mxs(r)&&(h=!!r.leading,m="maxWait"in r,i=m?pxs(c9e(r.maxWait)||0,t):i,x="trailing"in r?!!r.trailing:x);function g(D){var B=n,z=a;return n=a=void 0,d=D,l=s.apply(z,B),l}function v(D){return d=D,o=setTimeout(N,t),h?g(D):l}function j(D){var B=D-c,z=D-d,F=t-B;return m?xxs(F,i-z):F}function b(D){var B=D-c,z=D-d;return c===void 0||B>=t||B<0||m&&z>=i}function N(){var D=Kbe();if(b(D))return S(D);o=setTimeout(N,j(D))}function S(D){return o=void 0,x&&n?g(D):(n=a=void 0,l)}function T(){o!==void 0&&clearTimeout(o),d=0,n=c=a=o=void 0}function A(){return o===void 0?l:S(Kbe())}function P(){var D=Kbe(),B=b(D);if(n=arguments,a=this,c=D,B){if(o===void 0)return v(c);if(m)return clearTimeout(o),o=setTimeout(N,t),g(c)}return o===void 0&&(o=setTimeout(N,t)),l}return P.cancel=T,P.flush=A,P}var yxs=gxs,vxs=yxs,bxs=eN,_xs="Expected a function";function wxs(s,t,r){var n=!0,a=!0;if(typeof s!="function")throw new TypeError(_xs);return bxs(r)&&(n="leading"in r?!!r.leading:n,a="trailing"in r?!!r.trailing:a),vxs(s,t,{leading:n,maxWait:t,trailing:a})}var jxs=wxs;const Bdt=Io(jxs);function EF(s){"@babel/helpers - typeof";return EF=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},EF(s)}function d9e(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 IU(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&(Q=Bdt(Q,j,{trailing:!0,leading:!1}));var Y=new ResizeObserver(Q),ne=P.current.getBoundingClientRect(),de=ne.width,ce=ne.height;return X(de,ce),Y.observe(P.current),function(){Y.disconnect()}},[X,j]);var K=k.useMemo(function(){var Q=F.containerWidth,Y=F.containerHeight;if(Q<0||Y<0)return null;l0(Q4(l)||Q4(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),l0(!r||r>0,"The aspect(%s) must be greater than zero.",r);var ne=Q4(l)?Q:l,de=Q4(c)?Y:c;r&&r>0&&(ne?de=ne/r:de&&(ne=de*r),x&&de>x&&(de=x)),l0(ne>0||de>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.`,ne,de,l,c,h,m,r);var ce=!Array.isArray(g)&&l_(g.type).endsWith("Chart");return wt.Children.map(g,function(ae){return wt.isValidElement(ae)?k.cloneElement(ae,IU({width:ne,height:de},ce?{style:IU({height:"100%",width:"100%",maxHeight:de,maxWidth:ne},ae.props.style)}:{})):ae})},[r,g,c,x,m,h,F,l]);return wt.createElement("div",{id:b?"".concat(b):void 0,className:Ui("recharts-responsive-container",N),style:IU(IU({},A),{},{width:l,height:c,minWidth:h,minHeight:m,maxHeight:x}),ref:P},K)}),wz=function(t){return null};wz.displayName="Cell";function AF(s){"@babel/helpers - typeof";return AF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},AF(s)}function h9e(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 pke(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Q5.isSsr)return{width:0,height:0};var n=Oxs(r),a=JSON.stringify({text:t,copyStyle:n});if(HE.widthCache[a])return HE.widthCache[a];try{var i=document.getElementById(m9e);i||(i=document.createElement("span"),i.setAttribute("id",m9e),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=pke(pke({},Rxs),n);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return HE.widthCache[a]=c,++HE.cacheCount>Dxs&&(HE.cacheCount=0,HE.widthCache={}),c}catch{return{width:0,height:0}}},Fxs=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function MF(s){"@babel/helpers - typeof";return MF=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},MF(s)}function hme(s,t){return Uxs(s)||$xs(s,t)||zxs(s,t)||Bxs()}function Bxs(){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 zxs(s,t){if(s){if(typeof s=="string")return f9e(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 f9e(s,t)}}function f9e(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 sgs(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 b9e(s,t){return igs(s)||ags(s,t)||ngs(s,t)||rgs()}function rgs(){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 ngs(s,t){if(s){if(typeof s=="string")return _9e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _9e(s,t)}}function _9e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[];return ne.reduce(function(de,ce){var ae=ce.word,ie=ce.width,me=de[de.length-1];if(me&&(a==null||i||me.width+ie+nce.width?de:ce})};if(!h)return g;for(var j="…",b=function(ne){var de=m.slice(0,ne),ce=qdt({breakAll:d,style:c,children:de+j}).wordsWithComputedWidth,ae=x(ce),ie=ae.length>l||v(ae).width>Number(a);return[ie,ae]},N=0,S=m.length-1,T=0,A;N<=S&&T<=m.length-1;){var P=Math.floor((N+S)/2),D=P-1,B=b(D),z=b9e(B,2),F=z[0],$=z[1],X=b(P),K=b9e(X,1),Q=K[0];if(!F&&!Q&&(N=P+1),F&&Q&&(S=P-1),!F&&Q){A=$;break}T++}return A||g},w9e=function(t){var r=Fi(t)?[]:t.toString().split(Udt);return[{words:r}]},lgs=function(t){var r=t.width,n=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((r||n)&&!Q5.isSsr){var c,d,h=qdt({breakAll:l,children:a,style:i});if(h){var m=h.wordsWithComputedWidth,x=h.spaceWidth;c=m,d=x}else return w9e(a);return ogs({breakAll:l,children:a,maxLines:o,style:i},c,d,r,n)}return w9e(a)},j9e="#808080",M5=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,h=t.scaleToFit,m=h===void 0?!1:h,x=t.textAnchor,g=x===void 0?"start":x,v=t.verticalAnchor,j=v===void 0?"end":v,b=t.fill,N=b===void 0?j9e:b,S=v9e(t,egs),T=k.useMemo(function(){return lgs({breakAll:S.breakAll,children:S.children,maxLines:S.maxLines,scaleToFit:m,style:S.style,width:S.width})},[S.breakAll,S.children,S.maxLines,m,S.style,S.width]),A=S.dx,P=S.dy,D=S.angle,B=S.className,z=S.breakAll,F=v9e(S,tgs);if(!Gu(n)||!Gu(i))return null;var $=n+(wn(A)?A:0),X=i+(wn(P)?P:0),K;switch(j){case"start":K=Ybe("calc(".concat(d,")"));break;case"middle":K=Ybe("calc(".concat((T.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:K=Ybe("calc(".concat(T.length-1," * -").concat(o,")"));break}var Q=[];if(m){var Y=T[0].width,ne=S.width;Q.push("scale(".concat((wn(ne)?ne/Y:1)/Y,")"))}return D&&Q.push("rotate(".concat(D,", ").concat($,", ").concat(X,")")),Q.length&&(F.transform=Q.join(" ")),wt.createElement("text",xke({},oi(F,!0),{x:$,y:X,className:Ui("recharts-text",B),textAnchor:g,fill:N.includes("url")?j9e:N}),T.map(function(de,ce){var ae=de.words.join(z?"":" ");return wt.createElement("tspan",{x:$,dy:ce===0?K:o,key:"".concat(ae,"-").concat(ce)},ae)}))};function h2(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function cgs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function bEe(s){let t,r,n;s.length!==2?(t=h2,r=(o,c)=>h2(s(o),c),n=(o,c)=>s(o)-c):(t=s===h2||s===cgs?s:dgs,r=s,n=s);function a(o,c,d=0,h=o.length){if(d>>1;r(o[m],c)<0?d=m+1:h=m}while(d>>1;r(o[m],c)<=0?d=m+1:h=m}while(dd&&n(o[m-1],c)>-n(o[m],c)?m-1:m}return{left:a,center:l,right:i}}function dgs(){return 0}function Vdt(s){return s===null?NaN:+s}function*ugs(s,t){for(let r of s)r!=null&&(r=+r)>=r&&(yield r)}const hgs=bEe(h2),jz=hgs.right;bEe(Vdt).center;class N9e extends Map{constructor(t,r=pgs){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(k9e(this,t))}has(t){return super.has(k9e(this,t))}set(t,r){return super.set(mgs(this,t),r)}delete(t){return super.delete(fgs(this,t))}}function k9e({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):r}function mgs({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):(s.set(n,r),r)}function fgs({_intern:s,_key:t},r){const n=t(r);return s.has(n)&&(r=s.get(n),s.delete(n)),r}function pgs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function xgs(s=h2){if(s===h2)return Hdt;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 Hdt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const ggs=Math.sqrt(50),ygs=Math.sqrt(10),vgs=Math.sqrt(2);function mme(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>=ggs?10:i>=ygs?5:i>=vgs?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 C9e(s,t){let r;for(const n of s)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function Gdt(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?Hdt:xgs(a);n>r;){if(n-r>600){const c=n-r+1,d=t-r+1,h=Math.log(c),m=.5*Math.exp(2*h/3),x=.5*Math.sqrt(h*m*(c-m)/c)*(d-c/2<0?-1:1),g=Math.max(r,Math.floor(t-d*m/c+x)),v=Math.min(n,Math.floor(t+(c-d)*m/c+x));Gdt(s,t,g,v,a)}const i=s[t];let l=r,o=n;for(ZD(s,r,t),a(s[n],i)>0&&ZD(s,r,n);l0;)--o}a(s[r],i)===0?ZD(s,r,o):(++o,ZD(s,o,n)),o<=t&&(r=o+1),t<=o&&(n=o-1)}return s}function ZD(s,t,r){const n=s[t];s[t]=s[r],s[r]=n}function bgs(s,t,r){if(s=Float64Array.from(ugs(s)),!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return C9e(s);if(t>=1)return S9e(s);var n,a=(n-1)*t,i=Math.floor(a),l=S9e(Gdt(s,i).subarray(0,i+1)),o=C9e(s.subarray(i+1));return l+(o-l)*(a-i)}}function _gs(s,t,r=Vdt){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 wgs(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?LU(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?LU(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=Ngs.exec(s))?new cp(t[1],t[2],t[3],1):(t=kgs.exec(s))?new cp(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Sgs.exec(s))?LU(t[1],t[2],t[3],t[4]):(t=Cgs.exec(s))?LU(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Tgs.exec(s))?L9e(t[1],t[2]/100,t[3]/100,1):(t=Egs.exec(s))?L9e(t[1],t[2]/100,t[3]/100,t[4]):T9e.hasOwnProperty(s)?M9e(T9e[s]):s==="transparent"?new cp(NaN,NaN,NaN,0):null}function M9e(s){return new cp(s>>16&255,s>>8&255,s&255,1)}function LU(s,t,r,n){return n<=0&&(s=t=r=NaN),new cp(s,t,r,n)}function Igs(s){return s instanceof Nz||(s=DF(s)),s?(s=s.rgb(),new cp(s.r,s.g,s.b,s.opacity)):new cp}function _ke(s,t,r,n){return arguments.length===1?Igs(s):new cp(s,t,r,n??1)}function cp(s,t,r,n){this.r=+s,this.g=+t,this.b=+r,this.opacity=+n}wEe(cp,_ke,Kdt(Nz,{brighter(s){return s=s==null?fme:Math.pow(fme,s),new cp(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?PF:Math.pow(PF,s),new cp(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new cp(t5(this.r),t5(this.g),t5(this.b),pme(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:I9e,formatHex:I9e,formatHex8:Pgs,formatRgb:P9e,toString:P9e}));function I9e(){return`#${J4(this.r)}${J4(this.g)}${J4(this.b)}`}function Pgs(){return`#${J4(this.r)}${J4(this.g)}${J4(this.b)}${J4((isNaN(this.opacity)?1:this.opacity)*255)}`}function P9e(){const s=pme(this.opacity);return`${s===1?"rgb(":"rgba("}${t5(this.r)}, ${t5(this.g)}, ${t5(this.b)}${s===1?")":`, ${s})`}`}function pme(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function t5(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function J4(s){return s=t5(s),(s<16?"0":"")+s.toString(16)}function L9e(s,t,r,n){return n<=0?s=t=r=NaN:r<=0||r>=1?s=t=NaN:t<=0&&(s=NaN),new Ky(s,t,r,n)}function Ydt(s){if(s instanceof Ky)return new Ky(s.h,s.s,s.l,s.opacity);if(s instanceof Nz||(s=DF(s)),!s)return new Ky;if(s instanceof Ky)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 Ky(l,o,c,s.opacity)}function Lgs(s,t,r,n){return arguments.length===1?Ydt(s):new Ky(s,t,r,n??1)}function Ky(s,t,r,n){this.h=+s,this.s=+t,this.l=+r,this.opacity=+n}wEe(Ky,Lgs,Kdt(Nz,{brighter(s){return s=s==null?fme:Math.pow(fme,s),new Ky(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?PF:Math.pow(PF,s),new Ky(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 cp(Zbe(s>=240?s-240:s+120,a,n),Zbe(s,a,n),Zbe(s<120?s+240:s-120,a,n),this.opacity)},clamp(){return new Ky(D9e(this.h),DU(this.s),DU(this.l),pme(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=pme(this.opacity);return`${s===1?"hsl(":"hsla("}${D9e(this.h)}, ${DU(this.s)*100}%, ${DU(this.l)*100}%${s===1?")":`, ${s})`}`}}));function D9e(s){return s=(s||0)%360,s<0?s+360:s}function DU(s){return Math.max(0,Math.min(1,s||0))}function Zbe(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 jEe=s=>()=>s;function Dgs(s,t){return function(r){return s+r*t}}function Rgs(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 Ogs(s){return(s=+s)==1?Zdt:function(t,r){return r-t?Rgs(t,r,s):jEe(isNaN(t)?r:t)}}function Zdt(s,t){var r=t-s;return r?Dgs(s,r):jEe(isNaN(s)?t:s)}const R9e=function s(t){var r=Ogs(t);function n(a,i){var l=r((a=_ke(a)).r,(i=_ke(i)).r),o=r(a.g,i.g),c=r(a.b,i.b),d=Zdt(a.opacity,i.opacity);return function(h){return a.r=l(h),a.g=o(h),a.b=c(h),a.opacity=d(h),a+""}}return n.gamma=s,n}(1);function Fgs(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:xme(n,a)})),r=Xbe.lastIndex;return rt&&(r=s,s=t,t=r),function(n){return Math.max(s,Math.min(t,n))}}function Ygs(s,t,r){var n=s[0],a=s[1],i=t[0],l=t[1];return a2?Zgs:Ygs,c=d=null,m}function m(x){return x==null||isNaN(x=+x)?i:(c||(c=o(s.map(n),t,r)))(n(l(x)))}return m.invert=function(x){return l(a((d||(d=o(t,s.map(n),xme)))(x)))},m.domain=function(x){return arguments.length?(s=Array.from(x,gme),h()):s.slice()},m.range=function(x){return arguments.length?(t=Array.from(x),h()):t.slice()},m.rangeRound=function(x){return t=Array.from(x),r=NEe,h()},m.clamp=function(x){return arguments.length?(l=x?!0:jf,h()):l!==jf},m.interpolate=function(x){return arguments.length?(r=x,h()):r},m.unknown=function(x){return arguments.length?(i=x,m):i},function(x,g){return n=x,a=g,h()}}function kEe(){return sge()(jf,jf)}function Xgs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function yme(s,t){if(!isFinite(s)||s===0)return null;var r=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"),n=s.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+s.slice(r+1)]}function PI(s){return s=yme(Math.abs(s)),s?s[1]:NaN}function Qgs(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 Jgs(s){return function(t){return t.replace(/[0-9]/g,function(r){return s[+r]})}}var eys=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function RF(s){if(!(t=eys.exec(s)))throw new Error("invalid format: "+s);var t;return new SEe({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]})}RF.prototype=SEe.prototype;function SEe(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+""}SEe.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 tys(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 vme;function sys(s,t){var r=yme(s,t);if(!r)return vme=void 0,s.toPrecision(t);var n=r[0],a=r[1],i=a-(vme=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")+yme(s,Math.max(0,t+i-1))[0]}function F9e(s,t){var r=yme(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 B9e={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Xgs,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)=>F9e(s*100,t),r:F9e,s:sys,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function z9e(s){return s}var $9e=Array.prototype.map,U9e=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function rys(s){var t=s.grouping===void 0||s.thousands===void 0?z9e:Qgs($9e.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?z9e:Jgs($9e.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,x){m=RF(m);var g=m.fill,v=m.align,j=m.sign,b=m.symbol,N=m.zero,S=m.width,T=m.comma,A=m.precision,P=m.trim,D=m.type;D==="n"?(T=!0,D="g"):B9e[D]||(A===void 0&&(A=12),P=!0,D="g"),(N||g==="0"&&v==="=")&&(N=!0,g="0",v="=");var B=(x&&x.prefix!==void 0?x.prefix:"")+(b==="$"?r:b==="#"&&/[boxX]/.test(D)?"0"+D.toLowerCase():""),z=(b==="$"?n:/[%p]/.test(D)?l:"")+(x&&x.suffix!==void 0?x.suffix:""),F=B9e[D],$=/[defgprs%]/.test(D);A=A===void 0?6:/[gprs]/.test(D)?Math.max(1,Math.min(21,A)):Math.max(0,Math.min(20,A));function X(K){var Q=B,Y=z,ne,de,ce;if(D==="c")Y=F(K)+Y,K="";else{K=+K;var ae=K<0||1/K<0;if(K=isNaN(K)?c:F(Math.abs(K),A),P&&(K=tys(K)),ae&&+K==0&&j!=="+"&&(ae=!1),Q=(ae?j==="("?j:o:j==="-"||j==="("?"":j)+Q,Y=(D==="s"&&!isNaN(K)&&vme!==void 0?U9e[8+vme/3]:"")+Y+(ae&&j==="("?")":""),$){for(ne=-1,de=K.length;++nece||ce>57){Y=(ce===46?a+K.slice(ne+1):K.slice(ne))+Y,K=K.slice(0,ne);break}}}T&&!N&&(K=t(K,1/0));var ie=Q.length+K.length+Y.length,me=ie>1)+Q+K+Y+me.slice(ie);break;default:K=me+Q+K+Y;break}return i(K)}return X.toString=function(){return m+""},X}function h(m,x){var g=Math.max(-8,Math.min(8,Math.floor(PI(x)/3)))*3,v=Math.pow(10,-g),j=d((m=RF(m),m.type="f",m),{suffix:U9e[8+g/3]});return function(b){return j(v*b)}}return{format:d,formatPrefix:h}}var RU,CEe,Xdt;nys({thousands:",",grouping:[3],currency:["$",""]});function nys(s){return RU=rys(s),CEe=RU.format,Xdt=RU.formatPrefix,RU}function ays(s){return Math.max(0,-PI(Math.abs(s)))}function iys(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(PI(t)/3)))*3-PI(Math.abs(s)))}function oys(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,PI(t)-PI(s))+1}function Qdt(s,t,r,n){var a=vke(s,t,r),i;switch(n=RF(n??",f"),n.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return n.precision==null&&!isNaN(i=iys(a,l))&&(n.precision=i),Xdt(n,l)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=oys(a,Math.max(Math.abs(s),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=ays(a))&&(n.precision=i-(n.type==="%")*2);break}}return CEe(n)}function tN(s){var t=s.domain;return s.ticks=function(r){var n=t();return gke(n[0],n[n.length-1],r??10)},s.tickFormat=function(r,n){var a=t();return Qdt(a[0],a[a.length-1],r??10,n)},s.nice=function(r){r==null&&(r=10);var n=t(),a=0,i=n.length-1,l=n[a],o=n[i],c,d,h=10;for(o0;){if(d=yke(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 bme(){var s=kEe();return s.copy=function(){return kz(s,bme())},sy.apply(s,arguments),tN(s)}function Jdt(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,gme),r):s.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return Jdt(s).unknown(t)},s=arguments.length?Array.from(s,gme):[0,1],tN(r)}function eut(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 hys(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 H9e(s){return(t,r)=>-s(-t,r)}function TEe(s){const t=s(q9e,V9e),r=t.domain;let n=10,a,i;function l(){return a=hys(n),i=uys(n),r()[0]<0?(a=H9e(a),i=H9e(i),s(lys,cys)):s(q9e,V9e),t}return t.base=function(o){return arguments.length?(n=+o,l()):n},t.domain=function(o){return arguments.length?(r(o),l()):r()},t.ticks=o=>{const c=r();let d=c[0],h=c[c.length-1];const m=h0){for(;x<=g;++x)for(v=1;vh)break;N.push(j)}}else for(;x<=g;++x)for(v=n-1;v>=1;--v)if(j=x>0?v/i(-x):v*i(x),!(jh)break;N.push(j)}N.length*2{if(o==null&&(o=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=RF(c)).precision==null&&(c.trim=!0),c=CEe(c)),o===1/0)return c;const d=Math.max(1,n*o/t.ticks().length);return h=>{let m=h/i(Math.round(a(h)));return m*nr(eut(r(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function tut(){const s=TEe(sge()).domain([1,10]);return s.copy=()=>kz(s,tut()).base(s.base()),sy.apply(s,arguments),s}function G9e(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function W9e(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function EEe(s){var t=1,r=s(G9e(t),W9e(t));return r.constant=function(n){return arguments.length?s(G9e(t=+n),W9e(t)):t},tN(r)}function sut(){var s=EEe(sge());return s.copy=function(){return kz(s,sut()).constant(s.constant())},sy.apply(s,arguments)}function K9e(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function mys(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function fys(s){return s<0?-s*s:s*s}function AEe(s){var t=s(jf,jf),r=1;function n(){return r===1?s(jf,jf):r===.5?s(mys,fys):s(K9e(r),K9e(1/r))}return t.exponent=function(a){return arguments.length?(r=+a,n()):r},tN(t)}function MEe(){var s=AEe(sge());return s.copy=function(){return kz(s,MEe()).exponent(s.exponent())},sy.apply(s,arguments),s}function pys(){return MEe.apply(null,arguments).exponent(.5)}function Y9e(s){return Math.sign(s)*s*s}function xys(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function rut(){var s=kEe(),t=[0,1],r=!1,n;function a(i){var l=xys(s(i));return isNaN(l)?n:r?Math.round(l):l}return a.invert=function(i){return s.invert(Y9e(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,gme)).map(Y9e)),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 rut(s.domain(),t).round(r).clamp(s.clamp()).unknown(n)},sy.apply(a,arguments),tN(a)}function nut(){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 aut().domain([s,t]).range(a).unknown(i)},sy.apply(tN(l),arguments)}function iut(){var s=[.5],t=[0,1],r,n=1;function a(i){return i!=null&&i<=i?t[jz(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 iut().domain(s).range(t).unknown(r)},sy.apply(a,arguments)}const Qbe=new Date,Jbe=new Date;function nh(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(dnh(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)=>(Qbe.setTime(+i),Jbe.setTime(+l),s(Qbe),s(Jbe),Math.floor(r(Qbe,Jbe))),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 _me=nh(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);_me.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?nh(t=>{t.setTime(Math.floor(t/s)*s)},(t,r)=>{t.setTime(+t+r*s)},(t,r)=>(r-t)/s):_me);_me.range;const Wb=1e3,Rg=Wb*60,Kb=Rg*60,b_=Kb*24,IEe=b_*7,Z9e=b_*30,e_e=b_*365,e3=nh(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*Wb)},(s,t)=>(t-s)/Wb,s=>s.getUTCSeconds());e3.range;const PEe=nh(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*Wb)},(s,t)=>{s.setTime(+s+t*Rg)},(s,t)=>(t-s)/Rg,s=>s.getMinutes());PEe.range;const LEe=nh(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Rg)},(s,t)=>(t-s)/Rg,s=>s.getUTCMinutes());LEe.range;const DEe=nh(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*Wb-s.getMinutes()*Rg)},(s,t)=>{s.setTime(+s+t*Kb)},(s,t)=>(t-s)/Kb,s=>s.getHours());DEe.range;const REe=nh(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*Kb)},(s,t)=>(t-s)/Kb,s=>s.getUTCHours());REe.range;const Sz=nh(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Rg)/b_,s=>s.getDate()-1);Sz.range;const rge=nh(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/b_,s=>s.getUTCDate()-1);rge.range;const out=nh(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/b_,s=>Math.floor(s/b_));out.range;function J5(s){return nh(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())*Rg)/IEe)}const nge=J5(0),wme=J5(1),gys=J5(2),yys=J5(3),LI=J5(4),vys=J5(5),bys=J5(6);nge.range;wme.range;gys.range;yys.range;LI.range;vys.range;bys.range;function eT(s){return nh(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)/IEe)}const age=eT(0),jme=eT(1),_ys=eT(2),wys=eT(3),DI=eT(4),jys=eT(5),Nys=eT(6);age.range;jme.range;_ys.range;wys.range;DI.range;jys.range;Nys.range;const OEe=nh(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());OEe.range;const FEe=nh(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());FEe.range;const __=nh(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());__.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:nh(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)});__.range;const w_=nh(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());w_.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:nh(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)});w_.range;function lut(s,t,r,n,a,i){const l=[[e3,1,Wb],[e3,5,5*Wb],[e3,15,15*Wb],[e3,30,30*Wb],[i,1,Rg],[i,5,5*Rg],[i,15,15*Rg],[i,30,30*Rg],[a,1,Kb],[a,3,3*Kb],[a,6,6*Kb],[a,12,12*Kb],[n,1,b_],[n,2,2*b_],[r,1,IEe],[t,1,Z9e],[t,3,3*Z9e],[s,1,e_e]];function o(d,h,m){const x=hb).right(l,x);if(g===l.length)return s.every(vke(d/e_e,h/e_e,m));if(g===0)return _me.every(Math.max(vke(d,h,m),1));const[v,j]=l[x/l[g-1][2]53)return null;"w"in ye||(ye.w=1),"Z"in ye?(ve=s_e(XD(ye.y,0,1)),rt=ve.getUTCDay(),ve=rt>4||rt===0?jme.ceil(ve):jme(ve),ve=rge.offset(ve,(ye.V-1)*7),ye.y=ve.getUTCFullYear(),ye.m=ve.getUTCMonth(),ye.d=ve.getUTCDate()+(ye.w+6)%7):(ve=t_e(XD(ye.y,0,1)),rt=ve.getDay(),ve=rt>4||rt===0?wme.ceil(ve):wme(ve),ve=Sz.offset(ve,(ye.V-1)*7),ye.y=ve.getFullYear(),ye.m=ve.getMonth(),ye.d=ve.getDate()+(ye.w+6)%7)}else("W"in ye||"U"in ye)&&("w"in ye||(ye.w="u"in ye?ye.u%7:"W"in ye?1:0),rt="Z"in ye?s_e(XD(ye.y,0,1)).getUTCDay():t_e(XD(ye.y,0,1)).getDay(),ye.m=0,ye.d="W"in ye?(ye.w+6)%7+ye.W*7-(rt+5)%7:ye.w+ye.U*7-(rt+6)%7);return"Z"in ye?(ye.H+=ye.Z/100|0,ye.M+=ye.Z%100,s_e(ye)):t_e(ye)}}function z(Se,ze,Te,ye){for(var ct=0,ve=ze.length,rt=Te.length,Re,Qe;ct=rt)return-1;if(Re=ze.charCodeAt(ct++),Re===37){if(Re=ze.charAt(ct++),Qe=P[Re in X9e?ze.charAt(ct++):Re],!Qe||(ye=Qe(Se,Te,ye))<0)return-1}else if(Re!=Te.charCodeAt(ye++))return-1}return ye}function F(Se,ze,Te){var ye=d.exec(ze.slice(Te));return ye?(Se.p=h.get(ye[0].toLowerCase()),Te+ye[0].length):-1}function $(Se,ze,Te){var ye=g.exec(ze.slice(Te));return ye?(Se.w=v.get(ye[0].toLowerCase()),Te+ye[0].length):-1}function X(Se,ze,Te){var ye=m.exec(ze.slice(Te));return ye?(Se.w=x.get(ye[0].toLowerCase()),Te+ye[0].length):-1}function K(Se,ze,Te){var ye=N.exec(ze.slice(Te));return ye?(Se.m=S.get(ye[0].toLowerCase()),Te+ye[0].length):-1}function Q(Se,ze,Te){var ye=j.exec(ze.slice(Te));return ye?(Se.m=b.get(ye[0].toLowerCase()),Te+ye[0].length):-1}function Y(Se,ze,Te){return z(Se,t,ze,Te)}function ne(Se,ze,Te){return z(Se,r,ze,Te)}function de(Se,ze,Te){return z(Se,n,ze,Te)}function ce(Se){return l[Se.getDay()]}function ae(Se){return i[Se.getDay()]}function ie(Se){return c[Se.getMonth()]}function me(Se){return o[Se.getMonth()]}function oe(Se){return a[+(Se.getHours()>=12)]}function ge(Se){return 1+~~(Se.getMonth()/3)}function be(Se){return l[Se.getUTCDay()]}function Oe(Se){return i[Se.getUTCDay()]}function Me(Se){return c[Se.getUTCMonth()]}function Pe(Se){return o[Se.getUTCMonth()]}function Ee(Se){return a[+(Se.getUTCHours()>=12)]}function $e(Se){return 1+~~(Se.getUTCMonth()/3)}return{format:function(Se){var ze=D(Se+="",T);return ze.toString=function(){return Se},ze},parse:function(Se){var ze=B(Se+="",!1);return ze.toString=function(){return Se},ze},utcFormat:function(Se){var ze=D(Se+="",A);return ze.toString=function(){return Se},ze},utcParse:function(Se){var ze=B(Se+="",!0);return ze.toString=function(){return Se},ze}}}var X9e={"-":"",_:" ",0:"0"},Rh=/^\s*\d+/,Ays=/^%/,Mys=/[\\^$*+?|[\]().{}]/g;function ol(s,t,r){var n=s<0?"-":"",a=(n?-s:s)+"",i=a.length;return n+(i[t.toLowerCase(),r]))}function Pys(s,t,r){var n=Rh.exec(t.slice(r,r+1));return n?(s.w=+n[0],r+n[0].length):-1}function Lys(s,t,r){var n=Rh.exec(t.slice(r,r+1));return n?(s.u=+n[0],r+n[0].length):-1}function Dys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.U=+n[0],r+n[0].length):-1}function Rys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.V=+n[0],r+n[0].length):-1}function Oys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.W=+n[0],r+n[0].length):-1}function Q9e(s,t,r){var n=Rh.exec(t.slice(r,r+4));return n?(s.y=+n[0],r+n[0].length):-1}function J9e(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function Fys(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 Bys(s,t,r){var n=Rh.exec(t.slice(r,r+1));return n?(s.q=n[0]*3-3,r+n[0].length):-1}function zys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.m=n[0]-1,r+n[0].length):-1}function e$e(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.d=+n[0],r+n[0].length):-1}function $ys(s,t,r){var n=Rh.exec(t.slice(r,r+3));return n?(s.m=0,s.d=+n[0],r+n[0].length):-1}function t$e(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.H=+n[0],r+n[0].length):-1}function Uys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.M=+n[0],r+n[0].length):-1}function qys(s,t,r){var n=Rh.exec(t.slice(r,r+2));return n?(s.S=+n[0],r+n[0].length):-1}function Vys(s,t,r){var n=Rh.exec(t.slice(r,r+3));return n?(s.L=+n[0],r+n[0].length):-1}function Hys(s,t,r){var n=Rh.exec(t.slice(r,r+6));return n?(s.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function Gys(s,t,r){var n=Ays.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function Wys(s,t,r){var n=Rh.exec(t.slice(r));return n?(s.Q=+n[0],r+n[0].length):-1}function Kys(s,t,r){var n=Rh.exec(t.slice(r));return n?(s.s=+n[0],r+n[0].length):-1}function s$e(s,t){return ol(s.getDate(),t,2)}function Yys(s,t){return ol(s.getHours(),t,2)}function Zys(s,t){return ol(s.getHours()%12||12,t,2)}function Xys(s,t){return ol(1+Sz.count(__(s),s),t,3)}function cut(s,t){return ol(s.getMilliseconds(),t,3)}function Qys(s,t){return cut(s,t)+"000"}function Jys(s,t){return ol(s.getMonth()+1,t,2)}function e0s(s,t){return ol(s.getMinutes(),t,2)}function t0s(s,t){return ol(s.getSeconds(),t,2)}function s0s(s){var t=s.getDay();return t===0?7:t}function r0s(s,t){return ol(nge.count(__(s)-1,s),t,2)}function dut(s){var t=s.getDay();return t>=4||t===0?LI(s):LI.ceil(s)}function n0s(s,t){return s=dut(s),ol(LI.count(__(s),s)+(__(s).getDay()===4),t,2)}function a0s(s){return s.getDay()}function i0s(s,t){return ol(wme.count(__(s)-1,s),t,2)}function o0s(s,t){return ol(s.getFullYear()%100,t,2)}function l0s(s,t){return s=dut(s),ol(s.getFullYear()%100,t,2)}function c0s(s,t){return ol(s.getFullYear()%1e4,t,4)}function d0s(s,t){var r=s.getDay();return s=r>=4||r===0?LI(s):LI.ceil(s),ol(s.getFullYear()%1e4,t,4)}function u0s(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ol(t/60|0,"0",2)+ol(t%60,"0",2)}function r$e(s,t){return ol(s.getUTCDate(),t,2)}function h0s(s,t){return ol(s.getUTCHours(),t,2)}function m0s(s,t){return ol(s.getUTCHours()%12||12,t,2)}function f0s(s,t){return ol(1+rge.count(w_(s),s),t,3)}function uut(s,t){return ol(s.getUTCMilliseconds(),t,3)}function p0s(s,t){return uut(s,t)+"000"}function x0s(s,t){return ol(s.getUTCMonth()+1,t,2)}function g0s(s,t){return ol(s.getUTCMinutes(),t,2)}function y0s(s,t){return ol(s.getUTCSeconds(),t,2)}function v0s(s){var t=s.getUTCDay();return t===0?7:t}function b0s(s,t){return ol(age.count(w_(s)-1,s),t,2)}function hut(s){var t=s.getUTCDay();return t>=4||t===0?DI(s):DI.ceil(s)}function _0s(s,t){return s=hut(s),ol(DI.count(w_(s),s)+(w_(s).getUTCDay()===4),t,2)}function w0s(s){return s.getUTCDay()}function j0s(s,t){return ol(jme.count(w_(s)-1,s),t,2)}function N0s(s,t){return ol(s.getUTCFullYear()%100,t,2)}function k0s(s,t){return s=hut(s),ol(s.getUTCFullYear()%100,t,2)}function S0s(s,t){return ol(s.getUTCFullYear()%1e4,t,4)}function C0s(s,t){var r=s.getUTCDay();return s=r>=4||r===0?DI(s):DI.ceil(s),ol(s.getUTCFullYear()%1e4,t,4)}function T0s(){return"+0000"}function n$e(){return"%"}function a$e(s){return+s}function i$e(s){return Math.floor(+s/1e3)}var GE,mut,fut;E0s({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 E0s(s){return GE=Eys(s),mut=GE.format,GE.parse,fut=GE.utcFormat,GE.utcParse,GE}function A0s(s){return new Date(s)}function M0s(s){return s instanceof Date?+s:+new Date(+s)}function BEe(s,t,r,n,a,i,l,o,c,d){var h=kEe(),m=h.invert,x=h.domain,g=d(".%L"),v=d(":%S"),j=d("%I:%M"),b=d("%I %p"),N=d("%a %d"),S=d("%b %d"),T=d("%B"),A=d("%Y");function P(D){return(c(D)t(a/(s.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(a,i)=>bgs(s,i/n))},r.copy=function(){return yut(t).domain(s)},R_.apply(r,arguments)}function oge(){var s=0,t=.5,r=1,n=1,a,i,l,o,c,d=jf,h,m=!1,x;function g(j){return isNaN(j=+j)?x:(j=.5+((j=+h(j))-i)*(n*jt}var wut=F0s,B0s=lge,z0s=wut,$0s=YP;function U0s(s){return s&&s.length?B0s(s,$0s,z0s):void 0}var q0s=U0s;const cge=Io(q0s);function V0s(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};ma.decimalPlaces=ma.dp=function(){var s=this,t=s.d.length-1,r=(t-s.e)*Ac;if(t=s.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};ma.dividedBy=ma.div=function(s){return c_(this,new this.constructor(s))};ma.dividedToIntegerBy=ma.idiv=function(s){var t=this,r=t.constructor;return Jl(c_(t,new r(s),0,1),r.precision)};ma.equals=ma.eq=function(s){return!this.cmp(s)};ma.exponent=function(){return Tu(this)};ma.greaterThan=ma.gt=function(s){return this.cmp(s)>0};ma.greaterThanOrEqualTo=ma.gte=function(s){return this.cmp(s)>=0};ma.isInteger=ma.isint=function(){return this.e>this.d.length-2};ma.isNegative=ma.isneg=function(){return this.s<0};ma.isPositive=ma.ispos=function(){return this.s>0};ma.isZero=function(){return this.s===0};ma.lessThan=ma.lt=function(s){return this.cmp(s)<0};ma.lessThanOrEqualTo=ma.lte=function(s){return this.cmp(s)<1};ma.logarithm=ma.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(hx))throw Error(Yg+"NaN");if(r.s<1)throw Error(Yg+(r.s?"NaN":"-Infinity"));return r.eq(hx)?new n(0):(Wc=!1,t=c_(OF(r,i),OF(s,i),i),Wc=!0,Jl(t,a))};ma.minus=ma.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?Cut(t,s):kut(t,(s.s=-s.s,s))};ma.modulo=ma.mod=function(s){var t,r=this,n=r.constructor,a=n.precision;if(s=new n(s),!s.s)throw Error(Yg+"NaN");return r.s?(Wc=!1,t=c_(r,s,0,1).times(s),Wc=!0,r.minus(t)):Jl(new n(r),a)};ma.naturalExponential=ma.exp=function(){return Sut(this)};ma.naturalLogarithm=ma.ln=function(){return OF(this)};ma.negated=ma.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};ma.plus=ma.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?kut(t,s):Cut(t,(s.s=-s.s,s))};ma.precision=ma.sd=function(s){var t,r,n,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(s5+s);if(t=Tu(a)+1,n=a.d.length-1,r=n*Ac+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};ma.squareRoot=ma.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(Yg+"NaN")}for(s=Tu(o),Wc=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=Iv(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=QP((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(c_(o,i,l+2)).times(.5),Iv(i.d).slice(0,l)===(t=Iv(n.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Jl(i,r+1,0),i.times(i).eq(o)){n=i;break}}else if(t!="9999")break;l+=4}return Wc=!0,Jl(n,r)};ma.times=ma.mul=function(s){var t,r,n,a,i,l,o,c,d,h=this,m=h.constructor,x=h.d,g=(s=new m(s)).d;if(!h.s||!s.s)return new m(0);for(s.s*=h.s,r=h.e+s.e,c=x.length,d=g.length,c=0;){for(t=0,a=c+n;a>n;)o=i[a]+g[n]*x[a-n-1]+t,i[a--]=o%vh|0,t=o/vh|0;i[a]=(i[a]+t)%vh|0}for(;!i[--l];)i.pop();return t?++r:i.shift(),s.d=i,s.e=r,Wc?Jl(s,m.precision):s};ma.toDecimalPlaces=ma.todp=function(s,t){var r=this,n=r.constructor;return r=new n(r),s===void 0?r:(c1(s,0,XP),t===void 0?t=n.rounding:c1(t,0,8),Jl(r,s+Tu(r)+1,t))};ma.toExponential=function(s,t){var r,n=this,a=n.constructor;return s===void 0?r=I5(n,!0):(c1(s,0,XP),t===void 0?t=a.rounding:c1(t,0,8),n=Jl(new a(n),s+1,t),r=I5(n,!0,s+1)),r};ma.toFixed=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?I5(a):(c1(s,0,XP),t===void 0?t=i.rounding:c1(t,0,8),n=Jl(new i(a),s+Tu(a)+1,t),r=I5(n.abs(),!1,s+Tu(n)+1),a.isneg()&&!a.isZero()?"-"+r:r)};ma.toInteger=ma.toint=function(){var s=this,t=s.constructor;return Jl(new t(s),Tu(s)+1,t.rounding)};ma.toNumber=function(){return+this};ma.toPower=ma.pow=function(s){var t,r,n,a,i,l,o=this,c=o.constructor,d=12,h=+(s=new c(s));if(!s.s)return new c(hx);if(o=new c(o),!o.s){if(s.s<1)throw Error(Yg+"Infinity");return o}if(o.eq(hx))return o;if(n=c.precision,s.eq(hx))return Jl(o,n);if(t=s.e,r=s.d.length-1,l=t>=r,i=o.s,l){if((r=h<0?-h:h)<=Nut){for(a=new c(hx),t=Math.ceil(n/Ac+4),Wc=!1;r%2&&(a=a.times(o),c$e(a.d,t)),r=QP(r/2),r!==0;)o=o.times(o),c$e(o.d,t);return Wc=!0,s.s<0?new c(hx).div(a):Jl(a,n)}}else if(i<0)throw Error(Yg+"NaN");return i=i<0&&s.d[Math.max(t,r)]&1?-1:1,o.s=1,Wc=!1,a=s.times(OF(o,n+d)),Wc=!0,a=Sut(a),a.s=i,a};ma.toPrecision=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?(r=Tu(a),n=I5(a,r<=i.toExpNeg||r>=i.toExpPos)):(c1(s,1,XP),t===void 0?t=i.rounding:c1(t,0,8),a=Jl(new i(a),s,t),r=Tu(a),n=I5(a,s<=r||r<=i.toExpNeg,s)),n};ma.toSignificantDigits=ma.tosd=function(s,t){var r=this,n=r.constructor;return s===void 0?(s=n.precision,t=n.rounding):(c1(s,1,XP),t===void 0?t=n.rounding:c1(t,0,8)),Jl(new n(r),s,t)};ma.toString=ma.valueOf=ma.val=ma.toJSON=ma[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Tu(s),r=s.constructor;return I5(s,t<=r.toExpNeg||t>=r.toExpPos)};function kut(s,t){var r,n,a,i,l,o,c,d,h=s.constructor,m=h.precision;if(!s.s||!t.s)return t.s||(t=new h(s)),Wc?Jl(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/Ac),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)/vh|0,c[i]%=vh;for(r&&(c.unshift(r),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Wc?Jl(t,m):t}function c1(s,t,r){if(s!==~~s||sr)throw Error(s5+s)}function Iv(s){var t,r,n,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function r(n,a,i){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,l){var o,c,d,h,m,x,g,v,j,b,N,S,T,A,P,D,B,z,F=n.constructor,$=n.s==a.s?1:-1,X=n.d,K=a.d;if(!n.s)return new F(n);if(!a.s)throw Error(Yg+"Division by zero");for(c=n.e-a.e,B=K.length,P=X.length,g=new F($),v=g.d=[],d=0;K[d]==(X[d]||0);)++d;if(K[d]>(X[d]||0)&&--c,i==null?S=i=F.precision:l?S=i+(Tu(n)-Tu(a))+1:S=i,S<0)return new F(0);if(S=S/Ac+2|0,d=0,B==1)for(h=0,K=K[0],S++;(d1&&(K=s(K,h),X=s(X,h),B=K.length,P=X.length),A=B,j=X.slice(0,B),b=j.length;b=vh/2&&++D;do h=0,o=t(K,j,B,b),o<0?(N=j[0],B!=b&&(N=N*vh+(j[1]||0)),h=N/D|0,h>1?(h>=vh&&(h=vh-1),m=s(K,h),x=m.length,b=j.length,o=t(m,j,x,b),o==1&&(h--,r(m,B16)throw Error(UEe+Tu(s));if(!s.s)return new h(hx);for(Wc=!1,o=m,l=new h(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(n=Math.log(M4(2,d))/Math.LN10*2+5|0,o+=n,r=a=i=new h(hx),h.precision=o;;){if(a=Jl(a.times(s),o),r=r.times(++c),l=i.plus(c_(a,r,o)),Iv(l.d).slice(0,o)===Iv(i.d).slice(0,o)){for(;d--;)i=Jl(i.times(i),o);return h.precision=m,t==null?(Wc=!0,Jl(i,m)):i}i=l}}function Tu(s){for(var t=s.e*Ac,r=s.d[0];r>=10;r/=10)t++;return t}function r_e(s,t,r){if(t>s.LN10.sd())throw Wc=!0,r&&(s.precision=r),Error(Yg+"LN10 precision limit exceeded");return Jl(new s(s.LN10),t)}function ij(s){for(var t="";s--;)t+="0";return t}function OF(s,t){var r,n,a,i,l,o,c,d,h,m=1,x=10,g=s,v=g.d,j=g.constructor,b=j.precision;if(g.s<1)throw Error(Yg+(g.s?"NaN":"-Infinity"));if(g.eq(hx))return new j(0);if(t==null?(Wc=!1,d=b):d=t,g.eq(10))return t==null&&(Wc=!0),r_e(j,d);if(d+=x,j.precision=d,r=Iv(v),n=r.charAt(0),i=Tu(g),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)g=g.times(s),r=Iv(g.d),n=r.charAt(0),m++;i=Tu(g),n>1?(g=new j("0."+r),i++):g=new j(n+"."+r.slice(1))}else return c=r_e(j,d+2,b).times(i+""),g=OF(new j(n+"."+r.slice(1)),d-x).plus(c),j.precision=b,t==null?(Wc=!0,Jl(g,b)):g;for(o=l=g=c_(g.minus(hx),g.plus(hx),d),h=Jl(g.times(g),d),a=3;;){if(l=Jl(l.times(h),d),c=o.plus(c_(l,new j(a),d)),Iv(c.d).slice(0,d)===Iv(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(r_e(j,d+2,b).times(i+""))),o=c_(o,new j(m),d),j.precision=b,t==null?(Wc=!0,Jl(o,b)):o;o=c,a+=2}}function l$e(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=QP(r/Ac),s.d=[],n=(r+1)%Ac,r<0&&(n+=Ac),nNme||s.e<-Nme))throw Error(UEe+r)}else s.s=0,s.e=0,s.d=[0];return s}function Jl(s,t,r){var n,a,i,l,o,c,d,h,m=s.d;for(l=1,i=m[0];i>=10;i/=10)l++;if(n=t-l,n<0)n+=Ac,a=t,d=m[h=0];else{if(h=Math.ceil((n+1)/Ac),i=m.length,h>=i)return s;for(d=i=m[h],l=1;i>=10;i/=10)l++;n%=Ac,a=n-Ac+l}if(r!==void 0&&(i=M4(10,l-a-1),o=d/i%10|0,c=t<0||m[h+1]!==void 0||d%i,c=r<4?(o||c)&&(r==0||r==(s.s<0?3:2)):o>5||o==5&&(r==4||c||r==6&&(n>0?a>0?d/M4(10,l-a):0:m[h-1])%10&1||r==(s.s<0?8:7))),t<1||!m[0])return c?(i=Tu(s),m.length=1,t=t-i-1,m[0]=M4(10,(Ac-t%Ac)%Ac),s.e=QP(-t/Ac)||0):(m.length=1,m[0]=s.e=s.s=0),s;if(n==0?(m.length=h,i=1,h--):(m.length=h+1,i=M4(10,Ac-n),m[h]=a>0?(d/M4(10,l-a)%M4(10,a)|0)*i:0),c)for(;;)if(h==0){(m[0]+=i)==vh&&(m[0]=1,++s.e);break}else{if(m[h]+=i,m[h]!=vh)break;m[h--]=0,i=1}for(n=m.length;m[--n]===0;)m.pop();if(Wc&&(s.e>Nme||s.e<-Nme))throw Error(UEe+Tu(s));return s}function Cut(s,t){var r,n,a,i,l,o,c,d,h,m,x=s.constructor,g=x.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new x(s),Wc?Jl(t,g):t;if(c=s.d,m=t.d,n=t.e,d=s.e,c=c.slice(),l=d-n,l){for(h=l<0,h?(r=c,l=-l,o=m.length):(r=m,n=d,o=c.length),a=Math.max(Math.ceil(g/Ac),o)+2,l>a&&(l=a,r.length=1),r.reverse(),a=l;a--;)r.push(0);r.reverse()}else{for(a=c.length,o=m.length,h=a0;--a)c[o++]=0;for(a=m.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+ij(n):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+ij(-a-1)+i,r&&(n=r-l)>0&&(i+=ij(n))):a>=l?(i+=ij(a+1-l),r&&(n=r-a-1)>0&&(i=i+"."+ij(n))):((n=a+1)0&&(a+1===l&&(i+="."),i+=ij(n))),s.s<0?"-"+i:i}function c$e(s,t){if(s.length>t)return s.length=t,!0}function Tut(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(s5+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 l$e(l,i.toString())}else if(typeof i!="string")throw Error(s5+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,uvs.test(i))l$e(l,i);else throw Error(s5+i)}if(a.prototype=ma,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=Tut,a.config=a.set=hvs,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(s5+r+": "+n);if((n=s[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(s5+r+": "+n);return this}var qEe=Tut(dvs);hx=new qEe(1);const Bl=qEe;function mvs(s){return gvs(s)||xvs(s)||pvs(s)||fvs()}function fvs(){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 pvs(s,t){if(s){if(typeof s=="string")return Nke(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 Nke(s,t)}}function xvs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function gvs(s){if(Array.isArray(s))return Nke(s)}function Nke(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,d$e(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 Ivs(s){if(Array.isArray(s))return s}function Put(s){var t=FF(s,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]}function Lut(s,t,r){if(s.lte(0))return new Bl(0);var n=hge.getDigitCount(s.toNumber()),a=new Bl(10).pow(n),i=s.div(a),l=n!==1?.05:.1,o=new Bl(Math.ceil(i.div(l).toNumber())).add(r).mul(l),c=o.mul(a);return t?c:new Bl(Math.ceil(c))}function Pvs(s,t,r){var n=1,a=new Bl(s);if(!a.isint()&&r){var i=Math.abs(s);i<1?(n=new Bl(10).pow(hge.getDigitCount(s)-1),a=new Bl(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new Bl(Math.floor(s)))}else s===0?a=new Bl(Math.floor((t-1)/2)):r||(a=new Bl(Math.floor(s)));var l=Math.floor((t-1)/2),o=_vs(bvs(function(c){return a.add(new Bl(c-l).mul(n)).toNumber()}),kke);return o(0,t)}function Dut(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 Bl(0),tickMin:new Bl(0),tickMax:new Bl(0)};var i=Lut(new Bl(t).sub(s).div(r-1),n,a),l;s<=0&&t>=0?l=new Bl(0):(l=new Bl(s).add(t).div(2),l=l.sub(new Bl(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Bl(t).sub(l).div(i).toNumber()),d=o+c+1;return d>r?Dut(s,t,r,n,a+1):(d0?c+(r-d):c,o=t>0?o:o+(r-d)),{step:i,tickMin:l.sub(new Bl(o).mul(i)),tickMax:l.add(new Bl(c).mul(i))})}function Lvs(s){var t=FF(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=Put([r,n]),c=FF(o,2),d=c[0],h=c[1];if(d===-1/0||h===1/0){var m=h===1/0?[d].concat(Cke(kke(0,a-1).map(function(){return 1/0}))):[].concat(Cke(kke(0,a-1).map(function(){return-1/0})),[h]);return r>n?Ske(m):m}if(d===h)return Pvs(d,a,i);var x=Dut(d,h,l,i),g=x.step,v=x.tickMin,j=x.tickMax,b=hge.rangeStep(v,j.add(new Bl(.1).mul(g)),g);return r>n?Ske(b):b}function Dvs(s,t){var r=FF(s,2),n=r[0],a=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Put([n,a]),o=FF(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[n,a];if(c===d)return[c];var h=Math.max(t,2),m=Lut(new Bl(d).sub(c).div(h-1),i,0),x=[].concat(Cke(hge.rangeStep(new Bl(c),new Bl(d).sub(new Bl(.99).mul(m)),m)),[d]);return n>a?Ske(x):x}var Rvs=Mut(Lvs),Ovs=Mut(Dvs),Fvs="Invariant failed";function P5(s,t){throw new Error(Fvs)}var Bvs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function RI(s){"@babel/helpers - typeof";return RI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},RI(s)}function kme(){return kme=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 Gvs(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 Wvs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Kvs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,m=a[d].coordinate,x=d>=o-1?a[0].coordinate:a[d+1].coordinate,g=void 0;if(_f(m-h)!==_f(x-m)){var v=[];if(_f(x-m)===_f(c[1]-c[0])){g=x;var j=m+c[1]-c[0];v[0]=Math.min(j,(j+h)/2),v[1]=Math.max(j,(j+h)/2)}else{g=h;var b=x+c[1]-c[0];v[0]=Math.min(m,(b+m)/2),v[1]=Math.max(m,(b+m)/2)}var N=[Math.min(m,(g+m)/2),Math.max(m,(g+m)/2)];if(t>N[0]&&t<=N[1]||t>=v[0]&&t<=v[1]){l=a[d].index;break}}else{var S=Math.min(h,x),T=Math.max(h,x);if(t>(S+m)/2&&t<=(T+m)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(n[A].coordinate+n[A-1].coordinate)/2&&t<=(n[A].coordinate+n[A+1].coordinate)/2||A===o-1&&t>(n[A].coordinate+n[A-1].coordinate)/2){l=n[A].index;break}return l},VEe=function(t){var r,n=t,a=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Ad(Ad({},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},u1s=function(t){var r=t.barSize,n=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(N&&N.length){var S=N[0].type.defaultProps,T=S!==void 0?Ad(Ad({},S),N[0].props):N[0].props,A=T.barSize,P=T[b];l[P]||(l[P]=[]);var D=Fi(A)?r:A;l[P].push({item:N[0],stackList:N.slice(1),barSize:Fi(D)?void 0:wf(D,n,0)})}}return l},h1s=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=wf(r,a,0,!0),h,m=[];if(l[0].barSize===+l[0].barSize){var x=!1,g=a/c,v=l.reduce(function(A,P){return A+P.barSize||0},0);v+=(c-1)*d,v>=a&&(v-=(c-1)*d,d=0),v>=a&&g>0&&(x=!0,g*=.9,v=c*g);var j=(a-v)/2>>0,b={offset:j-d,size:0};h=l.reduce(function(A,P){var D={item:P.item,position:{offset:b.offset+b.size+d,size:x?g:P.barSize}},B=[].concat(m$e(A),[D]);return b=B[B.length-1].position,P.stackList&&P.stackList.length&&P.stackList.forEach(function(z){B.push({item:z,position:b})}),B},m)}else{var N=wf(n,a,0,!0);a-2*N-(c-1)*d<=0&&(d=0);var S=(a-2*N-(c-1)*d)/c;S>1&&(S>>=0);var T=o===+o?Math.min(S,o):S;h=l.reduce(function(A,P,D){var B=[].concat(m$e(A),[{item:P.item,position:{offset:N+(S+d)*D+(S-T)/2,size:T}}]);return P.stackList&&P.stackList.length&&P.stackList.forEach(function(z){B.push({item:z,position:B[B.length-1].position})}),B},m)}return h},m1s=function(t,r,n,a){var i=n.children,l=n.width,o=n.margin,c=l-(o.left||0)-(o.right||0),d=But({children:i,legendWidth:c});if(d){var h=a||{},m=h.width,x=h.height,g=d.align,v=d.verticalAlign,j=d.layout;if((j==="vertical"||j==="horizontal"&&v==="middle")&&g!=="center"&&wn(t[g]))return Ad(Ad({},t),{},LM({},g,t[g]+(m||0)));if((j==="horizontal"||j==="vertical"&&g==="center")&&v!=="middle"&&wn(t[v]))return Ad(Ad({},t),{},LM({},v,t[v]+(x||0)))}return t},f1s=function(t,r,n){return Fi(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},zut=function(t,r,n,a,i){var l=r.props.children,o=Sx(l,Tz).filter(function(d){return f1s(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,h){var m=Vu(h,n);if(Fi(m))return d;var x=Array.isArray(m)?[dge(m),cge(m)]:[m,m],g=c.reduce(function(v,j){var b=Vu(h,j,0),N=x[0]-Math.abs(Array.isArray(b)?b[0]:b),S=x[1]+Math.abs(Array.isArray(b)?b[1]:b);return[Math.min(N,v[0]),Math.max(S,v[1])]},[1/0,-1/0]);return[Math.min(g[0],d[0]),Math.max(g[1],d[1])]},[1/0,-1/0])}return null},p1s=function(t,r,n,a,i){var l=r.map(function(o){return zut(t,o,n,i,a)}).filter(function(o){return!Fi(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},$ut=function(t,r,n,a,i){var l=r.map(function(c){var d=c.props.dataKey;return n==="number"&&d&&zut(t,c,d,a)||x8(t,d,n,i)});if(n==="number")return l.reduce(function(c,d){return[Math.min(c[0],d[0]),Math.max(c[1],d[1])]},[1/0,-1/0]);var o={};return l.reduce(function(c,d){for(var h=0,m=d.length;h=2?_f(o[0]-o[1])*2*d:d,r&&(t.ticks||t.niceTicks)){var h=(t.ticks||t.niceTicks).map(function(m){var x=i?i.indexOf(m):m;return{coordinate:a(x)+d,value:m,offset:d}});return h.filter(function(m){return!bz(m.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(m,x){return{coordinate:a(m)+d,value:m,index:x,offset:d}}):a.ticks&&!n?a.ticks(t.tickCount).map(function(m){return{coordinate:a(m)+d,value:m,offset:d}}):a.domain().map(function(m,x){return{coordinate:a(m)+d,value:i?i[m]:m,index:x,offset:d}})},n_e=new WeakMap,OU=function(t,r){if(typeof r!="function")return t;n_e.has(t)||n_e.set(t,new WeakMap);var n=n_e.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},Vut=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:IF(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:bme(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:p8(),realScaleType:"point"}:i==="category"?{scale:IF(),realScaleType:"band"}:{scale:bme(),realScaleType:"linear"};if(E5(a)){var c="scale".concat(Yxe(a));return{scale:(o$e[c]||p8)(),realScaleType:o$e[c]?c:"point"}}return Ti(a)?{scale:a}:{scale:p8(),realScaleType:"point"}},p$e=1e-4,Hut=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])-p$e,l=Math.max(a[0],a[1])+p$e,o=t(r[0]),c=t(r[n-1]);(ol||cl)&&t.domain([r[0],r[n-1]])}},x1s=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])}},v1s=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)}},b1s={sign:y1s,expand:Bos,none:TI,silhouette:zos,wiggle:$os,positive:v1s},_1s=function(t,r,n){var a=r.map(function(o){return o.props.dataKey}),i=b1s[n],l=Fos().keys(a).value(function(o,c){return+Vu(o,c,0)}).order(tke).offset(i);return l(t)},w1s=function(t,r,n,a,i,l){if(!t)return null;var o=l?r.reverse():r,c={},d=o.reduce(function(m,x){var g,v=(g=x.type)!==null&&g!==void 0&&g.defaultProps?Ad(Ad({},x.type.defaultProps),x.props):x.props,j=v.stackId,b=v.hide;if(b)return m;var N=v[n],S=m[N]||{hasStack:!1,stackGroups:{}};if(Gu(j)){var T=S.stackGroups[j]||{numericAxisId:n,cateAxisId:a,items:[]};T.items.push(x),S.hasStack=!0,S.stackGroups[j]=T}else S.stackGroups[GP("_stackId_")]={numericAxisId:n,cateAxisId:a,items:[x]};return Ad(Ad({},m),{},LM({},N,S))},c),h={};return Object.keys(d).reduce(function(m,x){var g=d[x];if(g.hasStack){var v={};g.stackGroups=Object.keys(g.stackGroups).reduce(function(j,b){var N=g.stackGroups[b];return Ad(Ad({},j),{},LM({},b,{numericAxisId:n,cateAxisId:a,items:N.items,stackedData:_1s(t,N.items,i)}))},v)}return Ad(Ad({},m),{},LM({},x,g))},h)},Gut=function(t,r){var n=r.realScaleType,a=r.type,i=r.tickCount,l=r.originalDomain,o=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&l&&(l[0]==="auto"||l[1]==="auto")){var d=t.domain();if(!d.length)return null;var h=Rvs(d,i,o);return t.domain([dge(h),cge(h)]),{niceTicks:h}}if(i&&a==="number"){var m=t.domain(),x=Ovs(m,i,o);return{niceTicks:x}}return null};function x$e(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&&!Fi(a[t.dataKey])){var o=Qhe(r,"value",a[t.dataKey]);if(o)return o.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=Vu(a,Fi(l)?t.dataKey:l);return Fi(c)?null:t.scale(c)}var g$e=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=Vu(l,r.dataKey,r.domain[o]);return Fi(c)?null:r.scale(c)-i/2+a},j1s=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]},N1s=function(t,r){var n,a=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Ad(Ad({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(Gu(i)){var l=r[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},k1s=function(t){return t.reduce(function(r,n){return[dge(n.concat([r[0]]).filter(wn)),cge(n.concat([r[1]]).filter(wn))]},[1/0,-1/0])},Wut=function(t,r,n){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,h){var m=k1s(h.slice(r,n+1));return[Math.min(d[0],m[0]),Math.max(d[1],m[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},y$e=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,v$e=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Mke=function(t,r,n){if(Ti(t))return t(r,n);if(!Array.isArray(t))return r;var a=[];if(wn(t[0]))a[0]=n?t[0]:Math.min(t[0],r[0]);else if(y$e.test(t[0])){var i=+y$e.exec(t[0])[1];a[0]=r[0]-i}else Ti(t[0])?a[0]=t[0](r[0]):a[0]=r[0];if(wn(t[1]))a[1]=n?t[1]:Math.max(t[1],r[1]);else if(v$e.test(t[1])){var l=+v$e.exec(t[1])[1];a[1]=r[1]+l}else Ti(t[1])?a[1]=t[1](r[1]):a[1]=r[1];return a},Cme=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=yEe(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},L1s=function(t,r,n,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,h=wf(t.cx,l,l/2),m=wf(t.cy,o,o/2),x=Zut(l,o,n),g=wf(t.innerRadius,x,0),v=wf(t.outerRadius,x,x*.8),j=Object.keys(r);return j.reduce(function(b,N){var S=r[N],T=S.domain,A=S.reversed,P;if(Fi(S.range))a==="angleAxis"?P=[c,d]:a==="radiusAxis"&&(P=[g,v]),A&&(P=[P[1],P[0]]);else{P=S.range;var D=P,B=T1s(D,2);c=B[0],d=B[1]}var z=Vut(S,i),F=z.realScaleType,$=z.scale;$.domain(T).range(P),Hut($);var X=Gut($,Sb(Sb({},S),{},{realScaleType:F})),K=Sb(Sb(Sb({},S),X),{},{range:P,radius:v,realScaleType:F,scale:$,cx:h,cy:m,innerRadius:g,outerRadius:v,startAngle:c,endAngle:d});return Sb(Sb({},b),{},Yut({},N,K))},{})},D1s=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))},R1s=function(t,r){var n=t.x,a=t.y,i=r.cx,l=r.cy,o=D1s({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:P1s(d),angleInRadian:d}},O1s=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}},F1s=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},j$e=function(t,r){var n=t.x,a=t.y,i=R1s({x:n,y:a},r),l=i.radius,o=i.angle,c=r.innerRadius,d=r.outerRadius;if(ld)return!1;if(l===0)return!0;var h=O1s(r),m=h.startAngle,x=h.endAngle,g=o,v;if(m<=x){for(;g>x;)g-=360;for(;g=m&&g<=x}else{for(;g>m;)g-=360;for(;g=x&&g<=m}return v?Sb(Sb({},r),{},{radius:l,angle:F1s(g,r)}):null},Xut=function(t){return!k.isValidElement(t)&&!Ti(t)&&typeof t!="boolean"?t.className:""};function UF(s){"@babel/helpers - typeof";return UF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},UF(s)}var B1s=["offset"];function z1s(s){return V1s(s)||q1s(s)||U1s(s)||$1s()}function $1s(){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 U1s(s,t){if(s){if(typeof s=="string")return Ike(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 Ike(s,t)}}function q1s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function V1s(s){if(Array.isArray(s))return Ike(s)}function Ike(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 G1s(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 N$e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Ru(s){for(var t=1;t=0?1:-1,T,A;a==="insideStart"?(T=g+S*l,A=j):a==="insideEnd"?(T=v-S*l,A=!j):a==="end"&&(T=v+S*l,A=j),A=N<=0?A:!A;var P=pc(d,h,b,T),D=pc(d,h,b,T+(A?1:-1)*359),B="M".concat(P.x,",").concat(P.y,` A`).concat(b,",").concat(b,",0,1,").concat(A?0:1,`, `).concat(D.x,",").concat(D.y),z=Fi(t.id)?GP("recharts-radial-line-"):t.id;return wt.createElement("text",qF({},n,{dominantBaseline:"central",className:Ui("recharts-radial-bar-label",o)}),wt.createElement("defs",null,wt.createElement("path",{id:z,d:B})),wt.createElement("textPath",{xlinkHref:"#".concat(z)},r))},J1s=function(t){var r=t.viewBox,n=t.offset,a=t.position,i=r,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,h=i.startAngle,m=i.endAngle,x=(h+m)/2;if(a==="outside"){var g=pc(l,o,d+n,x),v=g.x,j=g.y;return{x:v,y:j,textAnchor:v>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var b=(c+d)/2,N=pc(l,o,b,x),S=N.x,T=N.y;return{x:S,y:T,textAnchor:"middle",verticalAnchor:"middle"}},ebs=function(t){var r=t.viewBox,n=t.parentViewBox,a=t.offset,i=t.position,l=r,o=l.x,c=l.y,d=l.width,h=l.height,m=h>=0?1:-1,x=m*a,g=m>0?"end":"start",v=m>0?"start":"end",j=d>=0?1:-1,b=j*a,N=j>0?"end":"start",S=j>0?"start":"end";if(i==="top"){var T={x:o+d/2,y:c-m*a,textAnchor:"middle",verticalAnchor:g};return Ru(Ru({},T),n?{height:Math.max(c-n.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+h+x,textAnchor:"middle",verticalAnchor:v};return Ru(Ru({},A),n?{height:Math.max(n.y+n.height-(c+h),0),width:d}:{})}if(i==="left"){var P={x:o-b,y:c+h/2,textAnchor:N,verticalAnchor:"middle"};return Ru(Ru({},P),n?{width:Math.max(P.x-n.x,0),height:h}:{})}if(i==="right"){var D={x:o+d+b,y:c+h/2,textAnchor:S,verticalAnchor:"middle"};return Ru(Ru({},D),n?{width:Math.max(n.x+n.width-D.x,0),height:h}:{})}var B=n?{width:d,height:h}:{};return i==="insideLeft"?Ru({x:o+b,y:c+h/2,textAnchor:S,verticalAnchor:"middle"},B):i==="insideRight"?Ru({x:o+d-b,y:c+h/2,textAnchor:N,verticalAnchor:"middle"},B):i==="insideTop"?Ru({x:o+d/2,y:c+x,textAnchor:"middle",verticalAnchor:v},B):i==="insideBottom"?Ru({x:o+d/2,y:c+h-x,textAnchor:"middle",verticalAnchor:g},B):i==="insideTopLeft"?Ru({x:o+b,y:c+x,textAnchor:S,verticalAnchor:v},B):i==="insideTopRight"?Ru({x:o+d-b,y:c+x,textAnchor:N,verticalAnchor:v},B):i==="insideBottomLeft"?Ru({x:o+b,y:c+h-x,textAnchor:S,verticalAnchor:g},B):i==="insideBottomRight"?Ru({x:o+d-b,y:c+h-x,textAnchor:N,verticalAnchor:g},B):UP(i)&&(wn(i.x)||Q4(i.x))&&(wn(i.y)||Q4(i.y))?Ru({x:o+wf(i.x,d),y:c+wf(i.y,h),textAnchor:"end",verticalAnchor:"end"},B):Ru({x:o+d/2,y:c+h/2,textAnchor:"middle",verticalAnchor:"middle"},B)},tbs=function(t){return"cx"in t&&wn(t.cx)};function jh(s){var t=s.offset,r=t===void 0?5:t,n=H1s(s,B1s),a=Ru({offset:r},n),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,h=a.className,m=h===void 0?"":h,x=a.textBreakAll;if(!i||Fi(o)&&Fi(c)&&!k.isValidElement(d)&&!Ti(d))return null;if(k.isValidElement(d))return k.cloneElement(d,a);var g;if(Ti(d)){if(g=k.createElement(d,a),k.isValidElement(g))return g}else g=Z1s(a);var v=tbs(i),j=oi(a,!0);if(v&&(l==="insideStart"||l==="insideEnd"||l==="end"))return Q1s(a,g,j);var b=v?J1s(a):ebs(a);return wt.createElement(M5,qF({className:Ui("recharts-label",m)},j,b,{breakAll:x}),g)}jh.displayName="Label";var Qut=function(t){var r=t.cx,n=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,h=t.outerRadius,m=t.x,x=t.y,g=t.top,v=t.left,j=t.width,b=t.height,N=t.clockWise,S=t.labelViewBox;if(S)return S;if(wn(j)&&wn(b)){if(wn(m)&&wn(x))return{x:m,y:x,width:j,height:b};if(wn(g)&&wn(v))return{x:g,y:v,width:j,height:b}}return wn(m)&&wn(x)?{x:m,y:x,width:0,height:0}:wn(r)&&wn(n)?{cx:r,cy:n,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:h||c||o||0,clockWise:N}:t.viewBox?t.viewBox:{}},sbs=function(t,r){return t?t===!0?wt.createElement(jh,{key:"label-implicit",viewBox:r}):Gu(t)?wt.createElement(jh,{key:"label-implicit",viewBox:r,value:t}):k.isValidElement(t)?t.type===jh?k.cloneElement(t,{key:"label-implicit",viewBox:r}):wt.createElement(jh,{key:"label-implicit",content:t,viewBox:r}):Ti(t)?wt.createElement(jh,{key:"label-implicit",content:t,viewBox:r}):UP(t)?wt.createElement(jh,qF({viewBox:r},t,{key:"label-implicit"})):null:null},rbs=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=Qut(t),l=Sx(a,jh).map(function(c,d){return k.cloneElement(c,{viewBox:r||i,key:"label-".concat(d)})});if(!n)return l;var o=sbs(t.label,r||i);return[o].concat(z1s(l))};jh.parseViewBox=Qut;jh.renderCallByParent=rbs;function nbs(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var abs=nbs;const ibs=Io(abs);function VF(s){"@babel/helpers - typeof";return VF=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},VF(s)}var obs=["valueAccessor"],lbs=["data","dataKey","clockWise","id","textBreakAll"];function cbs(s){return mbs(s)||hbs(s)||ubs(s)||dbs()}function dbs(){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 ubs(s,t){if(s){if(typeof s=="string")return Pke(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 Pke(s,t)}}function hbs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function mbs(s){if(Array.isArray(s))return Pke(s)}function Pke(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 gbs(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 ybs=function(t){return Array.isArray(t.value)?ibs(t.value):t.value};function d_(s){var t=s.valueAccessor,r=t===void 0?ybs:t,n=C$e(s,obs),a=n.data,i=n.dataKey,l=n.clockWise,o=n.id,c=n.textBreakAll,d=C$e(n,lbs);return!a||!a.length?null:wt.createElement(tl,{className:"recharts-label-list"},a.map(function(h,m){var x=Fi(i)?r(h,m):Vu(h&&h.payload,i),g=Fi(o)?{}:{id:"".concat(o,"-").concat(m)};return wt.createElement(jh,Eme({},oi(h,!0),d,g,{parentViewBox:h.parentViewBox,value:x,textBreakAll:c,viewBox:jh.parseViewBox(Fi(l)?h:S$e(S$e({},h),{},{clockWise:l})),key:"label-".concat(m),index:m}))}))}d_.displayName="LabelList";function vbs(s,t){return s?s===!0?wt.createElement(d_,{key:"labelList-implicit",data:t}):wt.isValidElement(s)||Ti(s)?wt.createElement(d_,{key:"labelList-implicit",data:t,content:s}):UP(s)?wt.createElement(d_,Eme({data:t},s,{key:"labelList-implicit"})):null:null}function bbs(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=Sx(n,d_).map(function(l,o){return k.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!r)return a;var i=vbs(s.label,t);return[i].concat(cbs(a))}d_.renderCallByParent=bbs;function HF(s){"@babel/helpers - typeof";return HF=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},HF(s)}function Lke(){return Lke=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 g=pc(r,n,a,l),v=pc(r,n,a,d);x+="L ".concat(v.x,",").concat(v.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(g.x,",").concat(g.y," Z")}else x+="L ".concat(r,",").concat(n," Z");return x},kbs=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,h=t.endAngle,m=_f(h-d),x=FU({cx:r,cy:n,radius:i,angle:d,sign:m,cornerRadius:l,cornerIsExternal:c}),g=x.circleTangency,v=x.lineTangency,j=x.theta,b=FU({cx:r,cy:n,radius:i,angle:h,sign:-m,cornerRadius:l,cornerIsExternal:c}),N=b.circleTangency,S=b.lineTangency,T=b.theta,A=c?Math.abs(d-h):Math.abs(d-h)-j-T;if(A<0)return o?"M ".concat(v.x,",").concat(v.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):Jut({cx:r,cy:n,innerRadius:a,outerRadius:i,startAngle:d,endAngle:h});var P="M ".concat(v.x,",").concat(v.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(g.x,",").concat(g.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(m<0),",").concat(N.x,",").concat(N.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(S.x,",").concat(S.y,` `);if(a>0){var D=FU({cx:r,cy:n,radius:a,angle:d,sign:m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),B=D.circleTangency,z=D.lineTangency,F=D.theta,$=FU({cx:r,cy:n,radius:a,angle:h,sign:-m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),X=$.circleTangency,K=$.lineTangency,Q=$.theta,Y=c?Math.abs(d-h):Math.abs(d-h)-F-Q;if(Y<0&&l===0)return"".concat(P,"L").concat(r,",").concat(n,"Z");P+="L".concat(K.x,",").concat(K.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(X.x,",").concat(X.y,` A`).concat(a,",").concat(a,",0,").concat(+(Y>180),",").concat(+(m>0),",").concat(B.x,",").concat(B.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(z.x,",").concat(z.y,"Z")}else P+="L".concat(r,",").concat(n,"Z");return P},Sbs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},eht=function(t){var r=E$e(E$e({},Sbs),t),n=r.cx,a=r.cy,i=r.innerRadius,l=r.outerRadius,o=r.cornerRadius,c=r.forceCornerRadius,d=r.cornerIsExternal,h=r.startAngle,m=r.endAngle,x=r.className;if(l0&&Math.abs(h-m)<360?b=kbs({cx:n,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(j,v/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:h,endAngle:m}):b=Jut({cx:n,cy:a,innerRadius:i,outerRadius:l,startAngle:h,endAngle:m}),wt.createElement("path",Lke({},oi(r,!0),{className:g,d:b,role:"img"}))};function GF(s){"@babel/helpers - typeof";return GF=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},GF(s)}function Dke(){return Dke=Object.assign?Object.assign.bind():function(s){for(var t=1;tBbs.call(s,t));function tT(s,t){return s===t||!s&&!t&&s!==s&&t!==t}const Ubs="__v",qbs="__o",Vbs="_owner",{getOwnPropertyDescriptor:L$e,keys:D$e}=Object;function Hbs(s,t){return s.byteLength===t.byteLength&&Mme(new Uint8Array(s),new Uint8Array(t))}function Gbs(s,t,r){let n=s.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(s[n],t[n],n,n,s,t,r))return!1;return!0}function Wbs(s,t){return s.byteLength===t.byteLength&&Mme(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function Kbs(s,t){return tT(s.getTime(),t.getTime())}function Ybs(s,t){return s.name===t.name&&s.message===t.message&&s.cause===t.cause&&s.stack===t.stack}function Zbs(s,t){return s===t}function R$e(s,t,r){const n=s.size;if(n!==t.size)return!1;if(!n)return!0;const a=new Array(n),i=s.entries();let l,o,c=0;for(;(l=i.next())&&!l.done;){const d=t.entries();let h=!1,m=0;for(;(o=d.next())&&!o.done;){if(a[m]){m++;continue}const x=l.value,g=o.value;if(r.equals(x[0],g[0],c,m,s,t,r)&&r.equals(x[1],g[1],x[0],g[0],s,t,r)){h=a[m]=!0;break}m++}if(!h)return!1;c++}return!0}const Xbs=tT;function Qbs(s,t,r){const n=D$e(s);let a=n.length;if(D$e(t).length!==a)return!1;for(;a-- >0;)if(!nht(s,t,r,n[a]))return!1;return!0}function sR(s,t,r){const n=P$e(s);let a=n.length;if(P$e(t).length!==a)return!1;let i,l,o;for(;a-- >0;)if(i=n[a],!nht(s,t,r,i)||(l=L$e(s,i),o=L$e(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function Jbs(s,t){return tT(s.valueOf(),t.valueOf())}function e_s(s,t){return s.source===t.source&&s.flags===t.flags}function O$e(s,t,r){const n=s.size;if(n!==t.size)return!1;if(!n)return!0;const a=new Array(n),i=s.values();let l,o;for(;(l=i.next())&&!l.done;){const c=t.values();let d=!1,h=0;for(;(o=c.next())&&!o.done;){if(!a[h]&&r.equals(l.value,o.value,l.value,o.value,s,t,r)){d=a[h]=!0;break}h++}if(!d)return!1}return!0}function Mme(s,t){let r=s.byteLength;if(t.byteLength!==r||s.byteOffset!==t.byteOffset)return!1;for(;r-- >0;)if(s[r]!==t[r])return!1;return!0}function t_s(s,t){return s.hostname===t.hostname&&s.pathname===t.pathname&&s.protocol===t.protocol&&s.port===t.port&&s.hash===t.hash&&s.username===t.username&&s.password===t.password}function nht(s,t,r,n){return(n===Vbs||n===qbs||n===Ubs)&&(s.$$typeof||t.$$typeof)?!0:$bs(t,n)&&r.equals(s[n],t[n],n,n,s,t,r)}const s_s="[object ArrayBuffer]",r_s="[object Arguments]",n_s="[object Boolean]",a_s="[object DataView]",i_s="[object Date]",o_s="[object Error]",l_s="[object Map]",c_s="[object Number]",d_s="[object Object]",u_s="[object RegExp]",h_s="[object Set]",m_s="[object String]",f_s={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},p_s="[object URL]",x_s=Object.prototype.toString;function g_s({areArrayBuffersEqual:s,areArraysEqual:t,areDataViewsEqual:r,areDatesEqual:n,areErrorsEqual:a,areFunctionsEqual:i,areMapsEqual:l,areNumbersEqual:o,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:h,areSetsEqual:m,areTypedArraysEqual:x,areUrlsEqual:g,unknownTagComparators:v}){return function(b,N,S){if(b===N)return!0;if(b==null||N==null)return!1;const T=typeof b;if(T!==typeof N)return!1;if(T!=="object")return T==="number"?o(b,N,S):T==="function"?i(b,N,S):!1;const A=b.constructor;if(A!==N.constructor)return!1;if(A===Object)return c(b,N,S);if(Array.isArray(b))return t(b,N,S);if(A===Date)return n(b,N,S);if(A===RegExp)return h(b,N,S);if(A===Map)return l(b,N,S);if(A===Set)return m(b,N,S);const P=x_s.call(b);if(P===i_s)return n(b,N,S);if(P===u_s)return h(b,N,S);if(P===l_s)return l(b,N,S);if(P===h_s)return m(b,N,S);if(P===d_s)return typeof b.then!="function"&&typeof N.then!="function"&&c(b,N,S);if(P===p_s)return g(b,N,S);if(P===o_s)return a(b,N,S);if(P===r_s)return c(b,N,S);if(f_s[P])return x(b,N,S);if(P===s_s)return s(b,N,S);if(P===a_s)return r(b,N,S);if(P===n_s||P===c_s||P===m_s)return d(b,N,S);if(v){let D=v[P];if(!D){const B=zbs(b);B&&(D=v[B])}if(D)return D(b,N,S)}return!1}}function y_s({circular:s,createCustomConfig:t,strict:r}){let n={areArrayBuffersEqual:Hbs,areArraysEqual:r?sR:Gbs,areDataViewsEqual:Wbs,areDatesEqual:Kbs,areErrorsEqual:Ybs,areFunctionsEqual:Zbs,areMapsEqual:r?a_e(R$e,sR):R$e,areNumbersEqual:Xbs,areObjectsEqual:r?sR:Qbs,arePrimitiveWrappersEqual:Jbs,areRegExpsEqual:e_s,areSetsEqual:r?a_e(O$e,sR):O$e,areTypedArraysEqual:r?a_e(Mme,sR):Mme,areUrlsEqual:t_s,unknownTagComparators:void 0};if(t&&(n=Object.assign({},n,t(n))),s){const a=zU(n.areArraysEqual),i=zU(n.areMapsEqual),l=zU(n.areObjectsEqual),o=zU(n.areSetsEqual);n=Object.assign({},n,{areArraysEqual:a,areMapsEqual:i,areObjectsEqual:l,areSetsEqual:o})}return n}function v_s(s){return function(t,r,n,a,i,l,o){return s(t,r,o)}}function b_s({circular:s,comparator:t,createState:r,equals:n,strict:a}){if(r)return function(o,c){const{cache:d=s?new WeakMap:void 0,meta:h}=r();return t(o,c,{cache:d,equals:n,meta:h,strict:a})};if(s)return function(o,c){return t(o,c,{cache:new WeakMap,equals:n,meta:void 0,strict:a})};const i={cache:void 0,equals:n,meta:void 0,strict:a};return function(o,c){return t(o,c,i)}}const __s=rN();rN({strict:!0});rN({circular:!0});rN({circular:!0,strict:!0});rN({createInternalComparator:()=>tT});rN({strict:!0,createInternalComparator:()=>tT});rN({circular:!0,createInternalComparator:()=>tT});rN({circular:!0,createInternalComparator:()=>tT,strict:!0});function rN(s={}){const{circular:t=!1,createInternalComparator:r,createState:n,strict:a=!1}=s,i=y_s(s),l=g_s(i),o=r?r(l):v_s(l);return b_s({circular:t,comparator:l,createState:n,equals:o,strict:a})}function w_s(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function F$e(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):w_s(a)};requestAnimationFrame(n)}function Rke(s){"@babel/helpers - typeof";return Rke=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},Rke(s)}function j_s(s){return C_s(s)||S_s(s)||k_s(s)||N_s()}function N_s(){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 k_s(s,t){if(s){if(typeof s=="string")return B$e(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 B$e(s,t)}}function B$e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1?1:N<0?0:N},j=function(N){for(var S=N>1?1:N,T=S,A=0;A<8;++A){var P=m(T)-S,D=g(T);if(Math.abs(P-S)0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(h,m,x){var g=-(h-m)*n,v=x*i,j=x+(g-v)*o/1e3,b=x*o/1e3+h;return Math.abs(b-m)s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function nws(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 i_e(s){return lws(s)||ows(s)||iws(s)||aws()}function aws(){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 iws(s,t){if(s){if(typeof s=="string")return $ke(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 $ke(s,t)}}function ows(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function lws(s){if(Array.isArray(s))return $ke(s)}function $ke(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 Lme(s){return Lme=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Lme(s)}var d1=function(s){mws(r,s);var t=fws(r);function r(n,a){var i;cws(this,r),i=t.call(this,n,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,h=l.to,m=l.steps,x=l.children,g=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(Vke(i)),i.changeStyle=i.changeStyle.bind(Vke(i)),!o||g<=0)return i.state={style:{}},typeof x=="function"&&(i.state={style:h}),qke(i);if(m&&m.length)i.state={style:m[0].style};else if(d){if(typeof x=="function")return i.state={style:d},qke(i);i.state={style:c?CR({},c,d):d}}else i.state={style:{}};return i}return uws(r,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,h=i.to,m=i.from,x=this.state.style;if(o){if(!l){var g={style:c?CR({},c,h):h};this.state&&x&&(c&&x[c]!==h||!c&&x!==h)&&this.setState(g);return}if(!(__s(a.to,h)&&a.canBegin&&a.isActive)){var v=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var j=v||d?m:a.to;if(this.state&&x){var b={style:c?CR({},c,j):j};(c&&x[c]!==j||!c&&x!==j)&&this.setState(b)}this.runAnimation(Ay(Ay({},this.props),{},{from:j,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,h=a.begin,m=a.onAnimationEnd,x=a.onAnimationStart,g=tws(l,o,V_s(d),c,this.changeStyle),v=function(){i.stopJSAnimation=g()};this.manager.start([x,h,v,c,m])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],h=d.style,m=d.duration,x=m===void 0?0:m,g=function(j,b,N){if(N===0)return j;var S=b.duration,T=b.easing,A=T===void 0?"ease":T,P=b.style,D=b.properties,B=b.onAnimationEnd,z=N>0?l[N-1]:b,F=D||Object.keys(P);if(typeof A=="function"||A==="spring")return[].concat(i_e(j),[i.runJSAnimation.bind(i,{from:z.style,to:P,duration:S,easing:A}),S]);var $=U$e(F,S,A),X=Ay(Ay(Ay({},z.style),P),{},{transition:$});return[].concat(i_e(j),[X,S,B]).filter(I_s)};return this.manager.start([c].concat(i_e(l.reduce(g,[h,Math.max(x,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=T_s());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,h=a.onAnimationStart,m=a.onAnimationEnd,x=a.steps,g=a.children,v=this.manager;if(this.unSubscribe=v.subscribe(this.handleStyleChange),typeof d=="function"||typeof g=="function"||d==="spring"){this.runJSAnimation(a);return}if(x.length>1){this.runStepAnimation(a);return}var j=o?CR({},o,c):c,b=U$e(Object.keys(j),l,d);v.start([h,i,Ay(Ay({},j),{},{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=rws(a,sws),d=k.Children.count(i),h=this.state.style;if(typeof i=="function")return i(h);if(!o||d===0||l<=0)return i;var m=function(g){var v=g.props,j=v.style,b=j===void 0?{}:j,N=v.className,S=k.cloneElement(g,Ay(Ay({},c),{},{style:Ay(Ay({},b),h),className:N}));return S};return d===1?m(k.Children.only(i)):wt.createElement("div",null,k.Children.map(i,function(x){return m(x)}))}}]),r}(k.PureComponent);d1.displayName="Animate";d1.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};d1.propTypes={from:yl.oneOfType([yl.object,yl.string]),to:yl.oneOfType([yl.object,yl.string]),attributeName:yl.string,duration:yl.number,begin:yl.number,easing:yl.oneOfType([yl.string,yl.func]),steps:yl.arrayOf(yl.shape({duration:yl.number.isRequired,style:yl.object.isRequired,easing:yl.oneOfType([yl.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),yl.func]),properties:yl.arrayOf("string"),onAnimationEnd:yl.func})),children:yl.oneOfType([yl.node,yl.func]),isActive:yl.bool,canBegin:yl.bool,onAnimationEnd:yl.func,shouldReAnimate:yl.bool,onAnimationStart:yl.func,onAnimationReStart:yl.func};function YF(s){"@babel/helpers - typeof";return YF=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},YF(s)}function Dme(){return Dme=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0?1:-1,c=n>=0?1:-1,d=a>=0&&n>=0||a<0&&n<0?1:0,h;if(l>0&&i instanceof Array){for(var m=[0,0,0,0],x=0,g=4;xl?l:i[x];h="M".concat(t,",").concat(r+o*m[0]),m[0]>0&&(h+="A ".concat(m[0],",").concat(m[0],",0,0,").concat(d,",").concat(t+c*m[0],",").concat(r)),h+="L ".concat(t+n-c*m[1],",").concat(r),m[1]>0&&(h+="A ".concat(m[1],",").concat(m[1],",0,0,").concat(d,`, `).concat(t+n,",").concat(r+o*m[1])),h+="L ".concat(t+n,",").concat(r+a-o*m[2]),m[2]>0&&(h+="A ".concat(m[2],",").concat(m[2],",0,0,").concat(d,`, `).concat(t+n-c*m[2],",").concat(r+a)),h+="L ".concat(t+c*m[3],",").concat(r+a),m[3]>0&&(h+="A ".concat(m[3],",").concat(m[3],",0,0,").concat(d,`, `).concat(t,",").concat(r+a-o*m[3])),h+="Z"}else if(l>0&&i===+i&&i>0){var v=Math.min(l,i);h="M ".concat(t,",").concat(r+o*v,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+c*v,",").concat(r,` L `).concat(t+n-c*v,",").concat(r,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+n,",").concat(r+o*v,` L `).concat(t+n,",").concat(r+a-o*v,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+n-c*v,",").concat(r+a,` L `).concat(t+c*v,",").concat(r+a,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t,",").concat(r+a-o*v," Z")}else h="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(a," h ").concat(-n," Z");return h},Nws=function(t,r){if(!t||!r)return!1;var n=t.x,a=t.y,i=r.x,l=r.y,o=r.width,c=r.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),h=Math.max(i,i+o),m=Math.min(l,l+c),x=Math.max(l,l+c);return n>=d&&n<=h&&a>=m&&a<=x}return!1},kws={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},HEe=function(t){var r=Z$e(Z$e({},kws),t),n=k.useRef(),a=k.useState(-1),i=xws(a,2),l=i[0],o=i[1];k.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var A=n.current.getTotalLength();A&&o(A)}catch{}},[]);var c=r.x,d=r.y,h=r.width,m=r.height,x=r.radius,g=r.className,v=r.animationEasing,j=r.animationDuration,b=r.animationBegin,N=r.isAnimationActive,S=r.isUpdateAnimationActive;if(c!==+c||d!==+d||h!==+h||m!==+m||h===0||m===0)return null;var T=Ui("recharts-rectangle",g);return S?wt.createElement(d1,{canBegin:l>0,from:{width:h,height:m,x:c,y:d},to:{width:h,height:m,x:c,y:d},duration:j,animationEasing:v,isActive:S},function(A){var P=A.width,D=A.height,B=A.x,z=A.y;return wt.createElement(d1,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:j,isActive:N,easing:v},wt.createElement("path",Dme({},oi(r,!0),{className:T,d:X$e(B,z,P,D,x),ref:n})))}):wt.createElement("path",Dme({},oi(r,!0),{className:T,d:X$e(c,d,h,m,x)}))},Sws=["points","className","baseLinePoints","connectNulls"];function RA(){return RA=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 Tws(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 Q$e(s){return Iws(s)||Mws(s)||Aws(s)||Ews()}function Ews(){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 Aws(s,t){if(s){if(typeof s=="string")return Hke(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 Hke(s,t)}}function Mws(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Iws(s){if(Array.isArray(s))return Hke(s)}function Hke(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){J$e(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),J$e(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},y8=function(t,r){var n=Pws(t);r&&(n=[n.reduce(function(i,l){return[].concat(Q$e(i),Q$e(l))},[])]);var a=n.map(function(i){return i.reduce(function(l,o,c){return"".concat(l).concat(c===0?"M":"L").concat(o.x,",").concat(o.y)},"")}).join("");return n.length===1?"".concat(a,"Z"):a},Lws=function(t,r,n){var a=y8(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(y8(r.reverse(),n).slice(1))},Dws=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,i=t.connectNulls,l=Cws(t,Sws);if(!r||!r.length)return null;var o=Ui("recharts-polygon",n);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=Lws(r,a,i);return wt.createElement("g",{className:o},wt.createElement("path",RA({},oi(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?wt.createElement("path",RA({},oi(l,!0),{fill:"none",d:y8(r,i)})):null,c?wt.createElement("path",RA({},oi(l,!0),{fill:"none",d:y8(a,i)})):null)}var h=y8(r,i);return wt.createElement("path",RA({},oi(l,!0),{fill:h.slice(-1)==="Z"?l.fill:"none",className:o,d:h}))};function Gke(){return Gke=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 Uws(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 qws=function(t,r,n,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(r,"h").concat(n)},Vws=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,h=t.width,m=h===void 0?0:h,x=t.height,g=x===void 0?0:x,v=t.className,j=$ws(t,Rws),b=Ows({x:n,y:i,top:o,left:d,width:m,height:g},j);return!wn(n)||!wn(i)||!wn(m)||!wn(g)||!wn(o)||!wn(d)?null:wt.createElement("path",Wke({},oi(b,!0),{className:Ui("recharts-cross",v),d:qws(n,i,m,g,o,d)}))},Hws=lge,Gws=wut,Wws=_1;function Kws(s,t){return s&&s.length?Hws(s,Wws(t),Gws):void 0}var Yws=Kws;const Zws=Io(Yws);var Xws=lge,Qws=_1,Jws=jut;function ejs(s,t){return s&&s.length?Xws(s,Qws(t),Jws):void 0}var tjs=ejs;const sjs=Io(tjs);var rjs=["cx","cy","angle","ticks","axisLine"],njs=["ticks","tick","angle","tickFormatter","stroke"];function FI(s){"@babel/helpers - typeof";return FI=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},FI(s)}function v8(){return v8=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 ajs(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 ijs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function rUe(s,t){for(var r=0;riUe?l=a==="outer"?"start":"end":i<-iUe?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=uk(uk({},oi(this.props,!1)),{},{fill:"none"},oi(o,!1));if(c==="circle")return wt.createElement(mge,O4({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var h=this.props.ticks,m=h.map(function(x){return pc(a,i,l,x.coordinate)});return wt.createElement(Dws,O4({className:"recharts-polar-angle-axis-line"},d,{points:m}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,h=oi(this.props,!1),m=oi(l,!1),x=uk(uk({},h),{},{fill:"none"},oi(o,!1)),g=i.map(function(v,j){var b=n.getTickLineCoord(v),N=n.getTickTextAnchor(v),S=uk(uk(uk({textAnchor:N},h),{},{stroke:"none",fill:d},m),{},{index:j,payload:v,x:b.x2,y:b.y2});return wt.createElement(tl,O4({className:Ui("recharts-polar-angle-axis-tick",Xut(l)),key:"tick-".concat(v.coordinate)},A5(n.props,v,j)),o&&wt.createElement("line",O4({className:"recharts-polar-angle-axis-tick-line"},x,b)),l&&t.renderTickItem(l,S,c?c(v.value,j):v.value))});return wt.createElement(tl,{className:"recharts-polar-angle-axis-ticks"},g)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.radius,l=n.axisLine;return i<=0||!a||!a.length?null:wt.createElement(tl,{className:Ui("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,i){var l;return wt.isValidElement(n)?l=wt.cloneElement(n,a):Ti(n)?l=n(a):l=wt.createElement(M5,O4({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(k.PureComponent);xge(gge,"displayName","PolarAngleAxis");xge(gge,"axisType","angleAxis");xge(gge,"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 _js=vdt,wjs=_js(Object.getPrototypeOf,Object),jjs=wjs,Njs=L_,kjs=jjs,Sjs=D_,Cjs="[object Object]",Tjs=Function.prototype,Ejs=Object.prototype,pht=Tjs.toString,Ajs=Ejs.hasOwnProperty,Mjs=pht.call(Object);function Ijs(s){if(!Sjs(s)||Njs(s)!=Cjs)return!1;var t=kjs(s);if(t===null)return!0;var r=Ajs.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&pht.call(r)==Mjs}var Pjs=Ijs;const Ljs=Io(Pjs);var Djs=L_,Rjs=D_,Ojs="[object Boolean]";function Fjs(s){return s===!0||s===!1||Rjs(s)&&Djs(s)==Ojs}var Bjs=Fjs;const zjs=Io(Bjs);function XF(s){"@babel/helpers - typeof";return XF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},XF(s)}function Fme(){return Fme=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0,from:{upperWidth:0,lowerWidth:0,height:x,x:c,y:d},to:{upperWidth:h,lowerWidth:m,height:x,x:c,y:d},duration:j,animationEasing:v,isActive:N},function(T){var A=T.upperWidth,P=T.lowerWidth,D=T.height,B=T.x,z=T.y;return wt.createElement(d1,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:j,easing:v},wt.createElement("path",Fme({},oi(r,!0),{className:S,d:dUe(B,z,A,P,D),ref:n})))}):wt.createElement("g",null,wt.createElement("path",Fme({},oi(r,!0),{className:S,d:dUe(c,d,h,m,x)})))},Xjs=["option","shapeType","propTransformer","activeClassName","isActive"];function QF(s){"@babel/helpers - typeof";return QF=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},QF(s)}function Qjs(s,t){if(s==null)return{};var r=Jjs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Jjs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function uUe(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 Bme(s){for(var t=1;t0?kx(T,"paddingAngle",0):0;if(P){var B=lx(P.endAngle-P.startAngle,T.endAngle-T.startAngle),z=cc(cc({},T),{},{startAngle:S+D,endAngle:S+B(j)+D});b.push(z),S=z.endAngle}else{var F=T.endAngle,$=T.startAngle,X=lx(0,F-$),K=X(j),Q=cc(cc({},T),{},{startAngle:S+D,endAngle:S+K+D});b.push(Q),S=Q.endAngle}}),wt.createElement(tl,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||!Cz(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,h=a.cy,m=a.innerRadius,x=a.outerRadius,g=a.isAnimationActive,v=this.state.isAnimationFinished;if(i||!l||!l.length||!wn(d)||!wn(h)||!wn(m)||!wn(x))return null;var j=Ui("recharts-pie",o);return wt.createElement(tl,{tabIndex:this.props.rootTabIndex,className:j,ref:function(N){n.pieRef=N}},this.renderSectors(),c&&this.renderLabels(l),jh.renderCallByParent(this.props,null,!1),(!g||v)&&d_.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n=360?S:S-1)*c,A=b-S*g-T,P=a.reduce(function(z,F){var $=Vu(F,N,0);return z+(wn($)?$:0)},0),D;if(P>0){var B;D=a.map(function(z,F){var $=Vu(z,N,0),X=Vu(z,h,F),K=(wn($)?$:0)/P,Q;F?Q=B.endAngle+_f(j)*c*($!==0?1:0):Q=l;var Y=Q+_f(j)*(($!==0?g:0)+K*A),ne=(Q+Y)/2,de=(v.innerRadius+v.outerRadius)/2,ce=[{name:X,value:$,payload:z,dataKey:N,type:x}],ae=pc(v.cx,v.cy,de,ne);return B=cc(cc(cc({percent:K,cornerRadius:i,name:X,tooltipPayload:ce,midAngle:ne,middleRadius:de,tooltipPosition:ae},z),v),{},{value:Vu(z,N),startAngle:Q,endAngle:Y,payload:z,paddingAngle:_f(j)*c}),B})}return cc(cc({},v),{},{sectors:D,data:a})});var b2s=Math.ceil,_2s=Math.max;function w2s(s,t,r,n){for(var a=-1,i=_2s(b2s((t-s)/(r||1)),0),l=Array(i);i--;)l[n?i:++a]=s,s+=r;return l}var j2s=w2s,N2s=Fdt,pUe=1/0,k2s=17976931348623157e292;function S2s(s){if(!s)return s===0?s:0;if(s=N2s(s),s===pUe||s===-pUe){var t=s<0?-1:1;return t*k2s}return s===s?s:0}var vht=S2s,C2s=j2s,T2s=tge,o_e=vht;function E2s(s){return function(t,r,n){return n&&typeof n!="number"&&T2s(t,r,n)&&(r=n=void 0),t=o_e(t),r===void 0?(r=t,t=0):r=o_e(r),n=n===void 0?t0&&n.handleDrag(a.changedTouches[0])}),Xp(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()}),Xp(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Xp(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Xp(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Xp(n,"handleSlideDragStart",function(a){var i=bUe(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 q2s(t,s),B2s(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var a=n.startX,i=n.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,h=d.length-1,m=Math.min(a,i),x=Math.max(a,i),g=t.getIndexInRange(l,m),v=t.getIndexInRange(l,x);return{startIndex:g-g%c,endIndex:v===h?h:v-v%c}}},{key:"getTextOfTick",value:function(n){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Vu(i[n],o,n);return Ti(l)?l(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,h=c.width,m=c.travellerWidth,x=c.startIndex,g=c.endIndex,v=c.onChange,j=n.pageX-i;j>0?j=Math.min(j,d+h-m-o,d+h-m-l):j<0&&(j=Math.max(j,d-l,d-o));var b=this.getIndex({startX:l+j,endX:o+j});(b.startIndex!==x||b.endIndex!==g)&&v&&v(b),this.setState({startX:l+j,endX:o+j,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,a){var i=bUe(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],h=this.props,m=h.x,x=h.width,g=h.travellerWidth,v=h.onChange,j=h.gap,b=h.data,N={startX:this.state.startX,endX:this.state.endX},S=n.pageX-i;S>0?S=Math.min(S,m+x-g-d):S<0&&(S=Math.max(S,m-d)),N[l]=d+S;var T=this.getIndex(N),A=T.startIndex,P=T.endIndex,D=function(){var z=b.length-1;return l==="startX"&&(o>c?A%j===0:P%j===0)||oc?P%j===0:A%j===0)||o>c&&P===z};this.setState(Xp(Xp({},l,d+S),"brushMoveStartX",n.pageX),function(){v&&D()&&v(T)})}},{key:"handleTravellerMoveKeyboard",value:function(n,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,h=this.state[a],m=o.indexOf(h);if(m!==-1){var x=m+n;if(!(x===-1||x>=o.length)){var g=o[x];a==="startX"&&g>=d||a==="endX"&&g<=c||this.setState(Xp({},a,g),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.fill,d=n.stroke;return wt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.data,d=n.children,h=n.padding,m=k.Children.only(d);return m?wt.cloneElement(m,{x:a,y:i,width:l,height:o,margin:h,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,a){var i,l,o=this,c=this.props,d=c.y,h=c.travellerWidth,m=c.height,x=c.traveller,g=c.ariaLabel,v=c.data,j=c.startIndex,b=c.endIndex,N=Math.max(n,this.props.x),S=l_e(l_e({},oi(this.props,!1)),{},{x:N,y:d,width:h,height:m}),T=g||"Min value: ".concat((i=v[j])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=v[b])===null||l===void 0?void 0:l.name);return wt.createElement(tl,{tabIndex:0,role:"slider","aria-label":T,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(P){["ArrowLeft","ArrowRight"].includes(P.key)&&(P.preventDefault(),P.stopPropagation(),o.handleTravellerMoveKeyboard(P.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(x,S))}},{key:"renderSlide",value:function(n,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,h=Math.min(n,a)+d,m=Math.max(Math.abs(a-n)-d,0);return wt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:h,y:l,width:m,height:o})}},{key:"renderText",value:function(){var n=this.props,a=n.startIndex,i=n.endIndex,l=n.y,o=n.height,c=n.travellerWidth,d=n.stroke,h=this.state,m=h.startX,x=h.endX,g=5,v={pointerEvents:"none",fill:d};return wt.createElement(tl,{className:"recharts-brush-texts"},wt.createElement(M5,Ume({textAnchor:"end",verticalAnchor:"middle",x:Math.min(m,x)-g,y:l+o/2},v),this.getTextOfTick(a)),wt.createElement(M5,Ume({textAnchor:"start",verticalAnchor:"middle",x:Math.max(m,x)+c+g,y:l+o/2},v),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,a=n.data,i=n.className,l=n.children,o=n.x,c=n.y,d=n.width,h=n.height,m=n.alwaysShowText,x=this.state,g=x.startX,v=x.endX,j=x.isTextActive,b=x.isSlideMoving,N=x.isTravellerMoving,S=x.isTravellerFocused;if(!a||!a.length||!wn(o)||!wn(c)||!wn(d)||!wn(h)||d<=0||h<=0)return null;var T=Ui("recharts-brush",i),A=wt.Children.count(l)===1,P=O2s("userSelect","none");return wt.createElement(tl,{className:T,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:P},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(g,v),this.renderTravellerLayer(g,"startX"),this.renderTravellerLayer(v,"endX"),(j||b||N||S||m)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var a=n.x,i=n.y,l=n.width,o=n.height,c=n.stroke,d=Math.floor(i+o/2)-1;return wt.createElement(wt.Fragment,null,wt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),wt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),wt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,a){var i;return wt.isValidElement(n)?i=wt.cloneElement(n,a):Ti(n)?i=n(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(n,a){var i=n.data,l=n.width,o=n.x,c=n.travellerWidth,d=n.updateId,h=n.startIndex,m=n.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return l_e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?H2s({data:i,width:l,x:o,travellerWidth:c,startIndex:h,endIndex:m}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var x=a.scale.domain().map(function(g){return a.scale(g)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(n.startIndex),endX:a.scale(n.endIndex),scaleValues:x}}return null}},{key:"getIndexInRange",value:function(n,a){for(var i=n.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);n[c]>a?o=c:l=c}return a>=n[o]?o:l}}])}(k.PureComponent);Xp(UI,"displayName","Brush");Xp(UI,"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 G2s=gEe;function W2s(s,t){var r;return G2s(s,function(n,a,i){return r=t(n,a,i),!r}),!!r}var K2s=W2s,Y2s=udt,Z2s=_1,X2s=K2s,Q2s=wp,J2s=tge;function eNs(s,t,r){var n=Q2s(s)?Y2s:X2s;return r&&J2s(s,t,r)&&(t=void 0),n(s,Z2s(t))}var tNs=eNs;const sNs=Io(tNs);var t1=function(t,r){var n=t.alwaysShow,a=t.ifOverflow;return n&&(a="extendDomain"),a===r},_Ue=Pdt;function rNs(s,t,r){t=="__proto__"&&_Ue?_Ue(s,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):s[t]=r}var nNs=rNs,aNs=nNs,iNs=Mdt,oNs=_1;function lNs(s,t){var r={};return t=oNs(t),iNs(s,function(n,a,i){aNs(r,a,t(n,a,i))}),r}var cNs=lNs;const dNs=Io(cNs);function uNs(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 TNs(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 ENs(s,t){var r=s.x,n=s.y,a=CNs(s,jNs),i="".concat(r),l=parseInt(i,10),o="".concat(n),c=parseInt(o,10),d="".concat(t.height||a.height),h=parseInt(d,10),m="".concat(t.width||a.width),x=parseInt(m,10);return rR(rR(rR(rR(rR({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:h,width:x,name:t.name,radius:t.radius})}function jUe(s){return wt.createElement(xht,Qke({shapeType:"rectangle",propTransformer:ENs,activeClassName:"recharts-active-bar"},s))}var ANs=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=wn(n)||Xas(n);return i?t(n,a):(i||P5(),r)}},MNs=["value","background"],Nht;function qI(s){"@babel/helpers - typeof";return qI=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},qI(s)}function INs(s,t){if(s==null)return{};var r=PNs(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 PNs(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 Vme(){return Vme=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(ne)0&&Math.abs(Y)0&&(Q=Math.min((Oe||0)-(Y[Me-1]||0),Q))}),Number.isFinite(Q)){var ne=Q/K,de=j.layout==="vertical"?n.height:n.width;if(j.padding==="gap"&&(B=ne*de/2),j.padding==="no-gap"){var ce=wf(t.barCategoryGap,ne*de),ae=ne*de/2;B=ae-ce-(ae-ce)/de*ce}}}a==="xAxis"?z=[n.left+(T.left||0)+(B||0),n.left+n.width-(T.right||0)-(B||0)]:a==="yAxis"?z=c==="horizontal"?[n.top+n.height-(T.bottom||0),n.top+(T.top||0)]:[n.top+(T.top||0)+(B||0),n.top+n.height-(T.bottom||0)-(B||0)]:z=j.range,P&&(z=[z[1],z[0]]);var ie=Vut(j,i,x),me=ie.scale,oe=ie.realScaleType;me.domain(N).range(z),Hut(me);var ge=Gut(me,Uy(Uy({},j),{},{realScaleType:oe}));a==="xAxis"?(X=b==="top"&&!A||b==="bottom"&&A,F=n.left,$=m[D]-X*j.height):a==="yAxis"&&(X=b==="left"&&!A||b==="right"&&A,F=m[D]-X*j.width,$=n.top);var be=Uy(Uy(Uy({},j),ge),{},{realScaleType:oe,x:F,y:$,scale:me,width:a==="xAxis"?n.width:j.width,height:a==="yAxis"?n.height:j.height});return be.bandSize=Cme(be,ge),!j.hide&&a==="xAxis"?m[D]+=(X?-1:1)*be.height:j.hide||(m[D]+=(X?-1:1)*be.width),Uy(Uy({},g),{},bge({},v,be))},{})},Eht=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)}},VNs=function(t){var r=t.x1,n=t.y1,a=t.x2,i=t.y2;return Eht({x:r,y:n},{x:a,y:i})},Aht=function(){function s(t){$Ns(this,s),this.scale=t}return UNs(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)}}])}();bge(Aht,"EPS",1e-4);var GEe=function(t){var r=Object.keys(t).reduce(function(n,a){return Uy(Uy({},n),{},bge({},a,Aht.create(t[a])))},{});return Uy(Uy({},r),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return dNs(a,function(c,d){return r[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return jht(a,function(i,l){return r[l].isInRange(i)})}})};function HNs(s){return(s%180+180)%180}var GNs=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=HNs(a),l=i*Math.PI/180,o=Math.atan(n/r),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var XNs=ZNs,QNs=vht;function JNs(s){var t=QNs(s),r=t%1;return t===t?r?t-r:t:0}var eks=JNs,tks=kdt,sks=_1,rks=eks,nks=Math.max;function aks(s,t,r){var n=s==null?0:s.length;if(!n)return-1;var a=r==null?0:rks(r);return a<0&&(a=nks(n+a,0)),tks(s,sks(t),a)}var iks=aks,oks=XNs,lks=iks,cks=oks(lks),dks=cks;const uks=Io(dks);var hks=ras(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("")}),WEe=k.createContext(void 0),KEe=k.createContext(void 0),Mht=k.createContext(void 0),Iht=k.createContext({}),Pht=k.createContext(void 0),Lht=k.createContext(0),Dht=k.createContext(0),TUe=function(t){var r=t.state,n=r.xAxisMap,a=r.yAxisMap,i=r.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,h=hks(i);return wt.createElement(WEe.Provider,{value:n},wt.createElement(KEe.Provider,{value:a},wt.createElement(Iht.Provider,{value:i},wt.createElement(Mht.Provider,{value:h},wt.createElement(Pht.Provider,{value:l},wt.createElement(Lht.Provider,{value:d},wt.createElement(Dht.Provider,{value:c},o)))))))},mks=function(){return k.useContext(Pht)},Rht=function(t){var r=k.useContext(WEe);r==null&&P5();var n=r[t];return n==null&&P5(),n},fks=function(){var t=k.useContext(WEe);return pj(t)},pks=function(){var t=k.useContext(KEe),r=uks(t,function(n){return jht(n.domain,Number.isFinite)});return r||pj(t)},Oht=function(t){var r=k.useContext(KEe);r==null&&P5();var n=r[t];return n==null&&P5(),n},xks=function(){var t=k.useContext(Mht);return t},gks=function(){return k.useContext(Iht)},YEe=function(){return k.useContext(Dht)},ZEe=function(){return k.useContext(Lht)};function VI(s){"@babel/helpers - typeof";return VI=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},VI(s)}function yks(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function vks(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 eSs(s,t){return Vht(s,t+1)}function tSs(s,t,r,n,a){for(var i=(n||[]).slice(),l=t.start,o=t.end,c=0,d=1,h=l,m=function(){var v=n==null?void 0:n[c];if(v===void 0)return{v:Vht(n,d)};var j=c,b,N=function(){return b===void 0&&(b=r(v,j)),b},S=v.coordinate,T=c===0||Yme(s,S,N,h,o);T||(c=0,h=l,d+=1),T&&(h=S+s*(N()/2+a),c+=d)},x;d<=i.length;)if(x=m(),x)return x.v;return[]}function rB(s){"@babel/helpers - typeof";return rB=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},rB(s)}function RUe(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 Tm(s){for(var t=1;t0?g.coordinate-b*s:g.coordinate})}else i[x]=g=Tm(Tm({},g),{},{tickCoord:g.coordinate});var N=Yme(s,g.tickCoord,j,o,c);N&&(c=g.tickCoord-s*(j()/2+a),i[x]=Tm(Tm({},g),{},{isShow:!0}))},h=l-1;h>=0;h--)d(h);return i}function iSs(s,t,r,n,a,i){var l=(n||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var h=n[o-1],m=r(h,o-1),x=s*(h.coordinate+s*m/2-d);l[o-1]=h=Tm(Tm({},h),{},{tickCoord:x>0?h.coordinate-x*s:h.coordinate});var g=Yme(s,h.tickCoord,function(){return m},c,d);g&&(d=h.tickCoord-s*(m/2+a),l[o-1]=Tm(Tm({},h),{},{isShow:!0}))}for(var v=i?o-1:o,j=function(S){var T=l[S],A,P=function(){return A===void 0&&(A=r(T,S)),A};if(S===0){var D=s*(T.coordinate-s*P()/2-c);l[S]=T=Tm(Tm({},T),{},{tickCoord:D<0?T.coordinate-D*s:T.coordinate})}else l[S]=T=Tm(Tm({},T),{},{tickCoord:T.coordinate});var B=Yme(s,T.tickCoord,P,c,d);B&&(c=T.tickCoord+s*(P()/2+a),l[S]=Tm(Tm({},T),{},{isShow:!0}))},b=0;b=2?_f(a[1].coordinate-a[0].coordinate):1,N=Jks(i,b,g);return c==="equidistantPreserveStart"?tSs(b,N,j,a,l):(c==="preserveStart"||c==="preserveStartEnd"?x=iSs(b,N,j,a,l,c==="preserveStartEnd"):x=aSs(b,N,j,a,l),x.filter(function(S){return S.isShow}))}var oSs=["viewBox"],lSs=["viewBox"],cSs=["ticks"];function WI(s){"@babel/helpers - typeof";return WI=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},WI(s)}function FA(){return FA=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 dSs(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 uSs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function FUe(s,t){for(var r=0;r0?c(this.props):c(g)),l<=0||o<=0||!v||!v.length?null:wt.createElement(tl,{className:Ui("recharts-cartesian-axis",d),ref:function(b){n.layerReference=b}},i&&this.renderAxisLine(),this.renderTicks(v,this.state.fontSize,this.state.letterSpacing),jh.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,a,i){var l,o=Ui(a.className,"recharts-cartesian-axis-tick-value");return wt.isValidElement(n)?l=wt.cloneElement(n,Du(Du({},a),{},{className:o})):Ti(n)?l=n(Du(Du({},a),{},{className:o})):l=wt.createElement(M5,FA({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(k.Component);eAe(JP,"displayName","CartesianAxis");eAe(JP,"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 ySs=["x1","y1","x2","y2","key"],vSs=["offset"];function L5(s){"@babel/helpers - typeof";return L5=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},L5(s)}function BUe(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 Im(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function jSs(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 NSs=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return wt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Wht(s,t){var r;if(wt.isValidElement(s))r=wt.cloneElement(s,t);else if(Ti(s))r=s(t);else{var n=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=zUe(t,ySs),d=oi(c,!1);d.offset;var h=zUe(d,vSs);r=wt.createElement("line",t3({},h,{x1:n,y1:a,x2:i,y2:l,fill:"none",key:o}))}return r}function kSs(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=Im(Im({},s),{},{x1:t,y1:o,x2:t+r,y2:o,key:"line-".concat(c),index:c});return Wht(a,d)});return wt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function SSs(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=Im(Im({},s),{},{x1:o,y1:t,x2:o,y2:t+r,key:"line-".concat(c),index:c});return Wht(a,d)});return wt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function CSs(s){var t=s.horizontalFill,r=s.fillOpacity,n=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var h=o.map(function(x){return Math.round(x+a-a)}).sort(function(x,g){return x-g});a!==h[0]&&h.unshift(0);var m=h.map(function(x,g){var v=!h[g+1],j=v?a+l-x:h[g+1]-x;if(j<=0)return null;var b=g%t.length;return wt.createElement("rect",{key:"react-".concat(g),y:x,x:n,height:j,width:i,stroke:"none",fill:t[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return wt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},m)}function TSs(s){var t=s.vertical,r=t===void 0?!0:t,n=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!r||!n||!n.length)return null;var h=d.map(function(x){return Math.round(x+i-i)}).sort(function(x,g){return x-g});i!==h[0]&&h.unshift(0);var m=h.map(function(x,g){var v=!h[g+1],j=v?i+o-x:h[g+1]-x;if(j<=0)return null;var b=g%n.length;return wt.createElement("rect",{key:"react-".concat(g),x,y:l,width:j,height:c,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return wt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},m)}var ESs=function(t,r){var n=t.xAxis,a=t.width,i=t.height,l=t.offset;return qut(JEe(Im(Im(Im({},JP.defaultProps),n),{},{ticks:Yb(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,r)},ASs=function(t,r){var n=t.yAxis,a=t.width,i=t.height,l=t.offset;return qut(JEe(Im(Im(Im({},JP.defaultProps),n),{},{ticks:Yb(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,r)},WE={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function Kht(s){var t,r,n,a,i,l,o=YEe(),c=ZEe(),d=gks(),h=Im(Im({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:WE.stroke,fill:(r=s.fill)!==null&&r!==void 0?r:WE.fill,horizontal:(n=s.horizontal)!==null&&n!==void 0?n:WE.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:WE.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:WE.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:WE.verticalFill,x:wn(s.x)?s.x:d.left,y:wn(s.y)?s.y:d.top,width:wn(s.width)?s.width:d.width,height:wn(s.height)?s.height:d.height}),m=h.x,x=h.y,g=h.width,v=h.height,j=h.syncWithTicks,b=h.horizontalValues,N=h.verticalValues,S=fks(),T=pks();if(!wn(g)||g<=0||!wn(v)||v<=0||!wn(m)||m!==+m||!wn(x)||x!==+x)return null;var A=h.verticalCoordinatesGenerator||ESs,P=h.horizontalCoordinatesGenerator||ASs,D=h.horizontalPoints,B=h.verticalPoints;if((!D||!D.length)&&Ti(P)){var z=b&&b.length,F=P({yAxis:T?Im(Im({},T),{},{ticks:z?b:T.ticks}):void 0,width:o,height:c,offset:d},z?!0:j);l0(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(L5(F),"]")),Array.isArray(F)&&(D=F)}if((!B||!B.length)&&Ti(A)){var $=N&&N.length,X=A({xAxis:S?Im(Im({},S),{},{ticks:$?N:S.ticks}):void 0,width:o,height:c,offset:d},$?!0:j);l0(Array.isArray(X),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(L5(X),"]")),Array.isArray(X)&&(B=X)}return wt.createElement("g",{className:"recharts-cartesian-grid"},wt.createElement(NSs,{fill:h.fill,fillOpacity:h.fillOpacity,x:h.x,y:h.y,width:h.width,height:h.height,ry:h.ry}),wt.createElement(kSs,t3({},h,{offset:d,horizontalPoints:D,xAxis:S,yAxis:T})),wt.createElement(SSs,t3({},h,{offset:d,verticalPoints:B,xAxis:S,yAxis:T})),wt.createElement(CSs,t3({},h,{horizontalPoints:D})),wt.createElement(TSs,t3({},h,{verticalPoints:B})))}Kht.displayName="CartesianGrid";var MSs=["type","layout","connectNulls","ref"],ISs=["key"];function KI(s){"@babel/helpers - typeof";return KI=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},KI(s)}function $Ue(s,t){if(s==null)return{};var r=PSs(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 PSs(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 b8(){return b8=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){g=[].concat(KE(c.slice(0,v)),[m-j]);break}var b=g.length%2===0?[0,x]:[x];return[].concat(KE(t.repeat(c,h)),KE(g),b).map(function(N){return"".concat(N,"px")}).join(", ")}),qy(r,"id",GP("recharts-line-")),qy(r,"pathRef",function(l){r.mainCurve=l}),qy(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),qy(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return qSs(t,s),BSs(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,l=i.points,o=i.xAxis,c=i.yAxis,d=i.layout,h=i.children,m=Sx(h,Tz);if(!m)return null;var x=function(j,b){return{x:j.x,y:j.y,value:j.value,errorVal:Vu(j.payload,b)}},g={clipPath:n?"url(#clipPath-".concat(a,")"):null};return wt.createElement(tl,g,m.map(function(v){return wt.cloneElement(v,{key:"bar-".concat(v.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:x})}))}},{key:"renderDots",value:function(n,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,h=o.dataKey,m=oi(this.props,!1),x=oi(c,!0),g=d.map(function(j,b){var N=Kp(Kp(Kp({key:"dot-".concat(b),r:3},m),x),{},{index:b,cx:j.x,cy:j.y,value:j.value,dataKey:h,payload:j.payload,points:d});return t.renderDotItem(c,N)}),v={clipPath:n?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return wt.createElement(tl,b8({className:"recharts-line-dots",key:"dots"},v),g)}},{key:"renderCurveStatically",value:function(n,a,i,l){var o=this.props,c=o.type,d=o.layout,h=o.connectNulls;o.ref;var m=$Ue(o,MSs),x=Kp(Kp(Kp({},oi(m,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:n},l),{},{type:c,layout:d,connectNulls:h});return wt.createElement(Ame,b8({},x,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,h=l.animationBegin,m=l.animationDuration,x=l.animationEasing,g=l.animationId,v=l.animateNewValues,j=l.width,b=l.height,N=this.state,S=N.prevPoints,T=N.totalLength;return wt.createElement(d1,{begin:h,duration:m,isActive:d,easing:x,from:{t:0},to:{t:1},key:"line-".concat(g),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var P=A.t;if(S){var D=S.length/o.length,B=o.map(function(K,Q){var Y=Math.floor(Q*D);if(S[Y]){var ne=S[Y],de=lx(ne.x,K.x),ce=lx(ne.y,K.y);return Kp(Kp({},K),{},{x:de(P),y:ce(P)})}if(v){var ae=lx(j*2,K.x),ie=lx(b/2,K.y);return Kp(Kp({},K),{},{x:ae(P),y:ie(P)})}return Kp(Kp({},K),{},{x:K.x,y:K.y})});return i.renderCurveStatically(B,n,a)}var z=lx(0,T),F=z(P),$;if(c){var X="".concat(c).split(/[,\s]+/gim).map(function(K){return parseFloat(K)});$=i.getStrokeDasharray(F,T,X)}else $=i.generateSimpleStrokeDasharray(T,F);return i.renderCurveStatically(o,n,a,{strokeDasharray:$})})}},{key:"renderCurve",value:function(n,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,h=c.totalLength;return o&&l&&l.length&&(!d&&h>0||!Cz(d,l))?this.renderCurveWithAnimation(n,a):this.renderCurveStatically(l,n,a)}},{key:"render",value:function(){var n,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,h=a.yAxis,m=a.top,x=a.left,g=a.width,v=a.height,j=a.isAnimationActive,b=a.id;if(i||!o||!o.length)return null;var N=this.state.isAnimationFinished,S=o.length===1,T=Ui("recharts-line",c),A=d&&d.allowDataOverflow,P=h&&h.allowDataOverflow,D=A||P,B=Fi(b)?this.id:b,z=(n=oi(l,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},F=z.r,$=F===void 0?3:F,X=z.strokeWidth,K=X===void 0?2:X,Q=cis(l)?l:{},Y=Q.clipDot,ne=Y===void 0?!0:Y,de=$*2+K;return wt.createElement(tl,{className:T},A||P?wt.createElement("defs",null,wt.createElement("clipPath",{id:"clipPath-".concat(B)},wt.createElement("rect",{x:A?x:x-g/2,y:P?m:m-v/2,width:A?g:g*2,height:P?v:v*2})),!ne&&wt.createElement("clipPath",{id:"clipPath-dots-".concat(B)},wt.createElement("rect",{x:x-de/2,y:m-de/2,width:g+de,height:v+de}))):null,!S&&this.renderCurve(D,B),this.renderErrorBar(D,B),(S||l)&&this.renderDots(D,ne,B),(!j||N)&&d_.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(KE(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 ICs(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 PCs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function LCs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r0?l:t&&t.length&&wn(a)&&wn(i)?t.slice(a,i+1):[]};function dmt(s){return s==="number"?[0,"auto"]:void 0}var gSe=function(t,r,n,a){var i=t.graphicalItems,l=t.tooltipAxis,o=kge(r,t);return n<0||!i||!i.length||n>=o.length?null:i.reduce(function(c,d){var h,m=(h=d.props.data)!==null&&h!==void 0?h:r;m&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(m=m.slice(t.dataStartIndex,t.dataEndIndex+1));var x;if(l.dataKey&&!l.allowDuplicatedCategory){var g=m===void 0?o:m;x=Qhe(g,l.dataKey,a)}else x=m&&m[n]||o[n];return x?[].concat(QI(c),[Kut(d,x)]):c},[])},YUe=function(t,r,n,a){var i=a||{x:t.chartX,y:t.chartY},l=GCs(i,n),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,h=d1s(l,o,d,c);if(h>=0&&d){var m=d[h]&&d[h].value,x=gSe(t,r,h,m),g=WCs(n,o,h,i);return{activeTooltipIndex:h,activeLabel:m,activePayload:x,activeCoordinate:g}}return null},KCs=function(t,r){var n=r.axes,a=r.graphicalItems,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,x=t.stackOffset,g=Uut(h,i);return n.reduce(function(v,j){var b,N=j.type.defaultProps!==void 0?Pr(Pr({},j.type.defaultProps),j.props):j.props,S=N.type,T=N.dataKey,A=N.allowDataOverflow,P=N.allowDuplicatedCategory,D=N.scale,B=N.ticks,z=N.includeHidden,F=N[l];if(v[F])return v;var $=kge(t.data,{graphicalItems:a.filter(function(ge){var be,Oe=l in ge.props?ge.props[l]:(be=ge.type.defaultProps)===null||be===void 0?void 0:be[l];return Oe===F}),dataStartIndex:c,dataEndIndex:d}),X=$.length,K,Q,Y;bCs(N.domain,A,S)&&(K=Mke(N.domain,null,A),g&&(S==="number"||D!=="auto")&&(Y=x8($,T,"category")));var ne=dmt(S);if(!K||K.length===0){var de,ce=(de=N.domain)!==null&&de!==void 0?de:ne;if(T){if(K=x8($,T,S),S==="category"&&g){var ae=Jas(K);P&&ae?(Q=K,K=$me(0,X)):P||(K=b$e(ce,K,j).reduce(function(ge,be){return ge.indexOf(be)>=0?ge:[].concat(QI(ge),[be])},[]))}else if(S==="category")P?K=K.filter(function(ge){return ge!==""&&!Fi(ge)}):K=b$e(ce,K,j).reduce(function(ge,be){return ge.indexOf(be)>=0||be===""||Fi(be)?ge:[].concat(QI(ge),[be])},[]);else if(S==="number"){var ie=p1s($,a.filter(function(ge){var be,Oe,Me=l in ge.props?ge.props[l]:(be=ge.type.defaultProps)===null||be===void 0?void 0:be[l],Pe="hide"in ge.props?ge.props.hide:(Oe=ge.type.defaultProps)===null||Oe===void 0?void 0:Oe.hide;return Me===F&&(z||!Pe)}),T,i,h);ie&&(K=ie)}g&&(S==="number"||D!=="auto")&&(Y=x8($,T,"category"))}else g?K=$me(0,X):o&&o[F]&&o[F].hasStack&&S==="number"?K=x==="expand"?[0,1]:Wut(o[F].stackGroups,c,d):K=$ut($,a.filter(function(ge){var be=l in ge.props?ge.props[l]:ge.type.defaultProps[l],Oe="hide"in ge.props?ge.props.hide:ge.type.defaultProps.hide;return be===F&&(z||!Oe)}),S,h,!0);if(S==="number")K=fSe(m,K,F,i,B),ce&&(K=Mke(ce,K,A));else if(S==="category"&&ce){var me=ce,oe=K.every(function(ge){return me.indexOf(ge)>=0});oe&&(K=me)}}return Pr(Pr({},v),{},gi({},F,Pr(Pr({},N),{},{axisType:i,domain:K,categoricalDomain:Y,duplicateDomain:Q,originalDomain:(b=N.domain)!==null&&b!==void 0?b:ne,isCategorical:g,layout:h})))},{})},YCs=function(t,r){var n=r.graphicalItems,a=r.Axis,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,x=kge(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:d}),g=x.length,v=Uut(h,i),j=-1;return n.reduce(function(b,N){var S=N.type.defaultProps!==void 0?Pr(Pr({},N.type.defaultProps),N.props):N.props,T=S[l],A=dmt("number");if(!b[T]){j++;var P;return v?P=$me(0,g):o&&o[T]&&o[T].hasStack?(P=Wut(o[T].stackGroups,c,d),P=fSe(m,P,T,i)):(P=Mke(A,$ut(x,n.filter(function(D){var B,z,F=l in D.props?D.props[l]:(B=D.type.defaultProps)===null||B===void 0?void 0:B[l],$="hide"in D.props?D.props.hide:(z=D.type.defaultProps)===null||z===void 0?void 0:z.hide;return F===T&&!$}),"number",h),a.defaultProps.allowDataOverflow),P=fSe(m,P,T,i)),Pr(Pr({},b),{},gi({},T,Pr(Pr({axisType:i},a.defaultProps),{},{hide:!0,orientation:kx(VCs,"".concat(i,".").concat(j%2),null),domain:P,originalDomain:A,isCategorical:v,layout:h})))}return b},{})},ZCs=function(t,r){var n=r.axisType,a=n===void 0?"xAxis":n,i=r.AxisComp,l=r.graphicalItems,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.children,m="".concat(a,"Id"),x=Sx(h,i),g={};return x&&x.length?g=KCs(t,{axes:x,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(g=YCs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),g},XCs=function(t){var r=pj(t),n=Yb(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:yEe(n,function(a){return a.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Cme(r,n)}},ZUe=function(t){var r=t.children,n=t.defaultShowTooltip,a=tx(r,UI),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}},QCs=function(t){return!t||!t.length?!1:t.some(function(r){var n=l_(r&&r.type);return n&&n.indexOf("Bar")>=0})},XUe=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},JCs=function(t,r){var n=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=n.width,h=n.height,m=n.children,x=n.margin||{},g=tx(m,UI),v=tx(m,MM),j=Object.keys(c).reduce(function(P,D){var B=c[D],z=B.orientation;return!B.mirror&&!B.hide?Pr(Pr({},P),{},gi({},z,P[z]+B.width)):P},{left:x.left||0,right:x.right||0}),b=Object.keys(l).reduce(function(P,D){var B=l[D],z=B.orientation;return!B.mirror&&!B.hide?Pr(Pr({},P),{},gi({},z,kx(P,"".concat(z))+B.height)):P},{top:x.top||0,bottom:x.bottom||0}),N=Pr(Pr({},b),j),S=N.bottom;g&&(N.bottom+=g.props.height||UI.defaultProps.height),v&&r&&(N=m1s(N,a,n,r));var T=d-N.left-N.right,A=h-N.top-N.bottom;return Pr(Pr({brushBottom:S},N),{},{width:Math.max(T,0),height:Math.max(A,0)})},e4s=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},tAe=function(t){var r=t.chartName,n=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,h=t.formatAxisMap,m=t.defaultProps,x=function(N,S){var T=S.graphicalItems,A=S.stackGroups,P=S.offset,D=S.updateId,B=S.dataStartIndex,z=S.dataEndIndex,F=N.barSize,$=N.layout,X=N.barGap,K=N.barCategoryGap,Q=N.maxBarSize,Y=XUe($),ne=Y.numericAxisName,de=Y.cateAxisName,ce=QCs(T),ae=[];return T.forEach(function(ie,me){var oe=kge(N.data,{graphicalItems:[ie],dataStartIndex:B,dataEndIndex:z}),ge=ie.type.defaultProps!==void 0?Pr(Pr({},ie.type.defaultProps),ie.props):ie.props,be=ge.dataKey,Oe=ge.maxBarSize,Me=ge["".concat(ne,"Id")],Pe=ge["".concat(de,"Id")],Ee={},$e=c.reduce(function($t,lt){var it=S["".concat(lt.axisType,"Map")],Nt=ge["".concat(lt.axisType,"Id")];it&&it[Nt]||lt.axisType==="zAxis"||P5();var Ft=it[Nt];return Pr(Pr({},$t),{},gi(gi({},lt.axisType,Ft),"".concat(lt.axisType,"Ticks"),Yb(Ft)))},Ee),Se=$e[de],ze=$e["".concat(de,"Ticks")],Te=A&&A[Me]&&A[Me].hasStack&&N1s(ie,A[Me].stackGroups),ye=l_(ie.type).indexOf("Bar")>=0,ct=Cme(Se,ze),ve=[],rt=ce&&u1s({barSize:F,stackGroups:A,totalSize:e4s($e,de)});if(ye){var Re,Qe,Ke=Fi(Oe)?Q:Oe,Ce=(Re=(Qe=Cme(Se,ze,!0))!==null&&Qe!==void 0?Qe:Ke)!==null&&Re!==void 0?Re:0;ve=h1s({barGap:X,barCategoryGap:K,bandSize:Ce!==ct?Ce:ct,sizeList:rt[Pe],maxBarSize:Ke}),Ce!==ct&&(ve=ve.map(function($t){return Pr(Pr({},$t),{},{position:Pr(Pr({},$t.position),{},{offset:$t.position.offset-Ce/2})})}))}var nt=ie&&ie.type&&ie.type.getComposedData;nt&&ae.push({props:Pr(Pr({},nt(Pr(Pr({},$e),{},{displayedData:oe,props:N,dataKey:be,item:ie,bandSize:ct,barPosition:ve,offset:P,stackedData:Te,layout:$,dataStartIndex:B,dataEndIndex:z}))),{},gi(gi(gi({key:ie.key||"item-".concat(me)},ne,$e[ne]),de,$e[de]),"animationId",D)),childIndex:his(ie,N.children),item:ie})}),ae},g=function(N,S){var T=N.props,A=N.dataStartIndex,P=N.dataEndIndex,D=N.updateId;if(!m7e({props:T}))return null;var B=T.children,z=T.layout,F=T.stackOffset,$=T.data,X=T.reverseStackOrder,K=XUe(z),Q=K.numericAxisName,Y=K.cateAxisName,ne=Sx(B,n),de=w1s($,ne,"".concat(Q,"Id"),"".concat(Y,"Id"),F,X),ce=c.reduce(function(ge,be){var Oe="".concat(be.axisType,"Map");return Pr(Pr({},ge),{},gi({},Oe,ZCs(T,Pr(Pr({},be),{},{graphicalItems:ne,stackGroups:be.axisType===Q&&de,dataStartIndex:A,dataEndIndex:P}))))},{}),ae=JCs(Pr(Pr({},ce),{},{props:T,graphicalItems:ne}),S==null?void 0:S.legendBBox);Object.keys(ce).forEach(function(ge){ce[ge]=h(T,ce[ge],ae,ge.replace("Map",""),r)});var ie=ce["".concat(Y,"Map")],me=XCs(ie),oe=x(T,Pr(Pr({},ce),{},{dataStartIndex:A,dataEndIndex:P,updateId:D,graphicalItems:ne,stackGroups:de,offset:ae}));return Pr(Pr({formattedGraphicalItems:oe,graphicalItems:ne,offset:ae,stackGroups:de},me),ce)},v=function(b){function N(S){var T,A,P;return PCs(this,N),P=RCs(this,N,[S]),gi(P,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),gi(P,"accessibilityManager",new vCs),gi(P,"handleLegendBBoxUpdate",function(D){if(D){var B=P.state,z=B.dataStartIndex,F=B.dataEndIndex,$=B.updateId;P.setState(Pr({legendBBox:D},g({props:P.props,dataStartIndex:z,dataEndIndex:F,updateId:$},Pr(Pr({},P.state),{},{legendBBox:D}))))}}),gi(P,"handleReceiveSyncEvent",function(D,B,z){if(P.props.syncId===D){if(z===P.eventEmitterSymbol&&typeof P.props.syncMethod!="function")return;P.applySyncEvent(B)}}),gi(P,"handleBrushChange",function(D){var B=D.startIndex,z=D.endIndex;if(B!==P.state.dataStartIndex||z!==P.state.dataEndIndex){var F=P.state.updateId;P.setState(function(){return Pr({dataStartIndex:B,dataEndIndex:z},g({props:P.props,dataStartIndex:B,dataEndIndex:z,updateId:F},P.state))}),P.triggerSyncEvent({dataStartIndex:B,dataEndIndex:z})}}),gi(P,"handleMouseEnter",function(D){var B=P.getMouseInfo(D);if(B){var z=Pr(Pr({},B),{},{isTooltipActive:!0});P.setState(z),P.triggerSyncEvent(z);var F=P.props.onMouseEnter;Ti(F)&&F(z,D)}}),gi(P,"triggeredAfterMouseMove",function(D){var B=P.getMouseInfo(D),z=B?Pr(Pr({},B),{},{isTooltipActive:!0}):{isTooltipActive:!1};P.setState(z),P.triggerSyncEvent(z);var F=P.props.onMouseMove;Ti(F)&&F(z,D)}),gi(P,"handleItemMouseEnter",function(D){P.setState(function(){return{isTooltipActive:!0,activeItem:D,activePayload:D.tooltipPayload,activeCoordinate:D.tooltipPosition||{x:D.cx,y:D.cy}}})}),gi(P,"handleItemMouseLeave",function(){P.setState(function(){return{isTooltipActive:!1}})}),gi(P,"handleMouseMove",function(D){D.persist(),P.throttleTriggeredAfterMouseMove(D)}),gi(P,"handleMouseLeave",function(D){P.throttleTriggeredAfterMouseMove.cancel();var B={isTooltipActive:!1};P.setState(B),P.triggerSyncEvent(B);var z=P.props.onMouseLeave;Ti(z)&&z(B,D)}),gi(P,"handleOuterEvent",function(D){var B=uis(D),z=kx(P.props,"".concat(B));if(B&&Ti(z)){var F,$;/.*touch.*/i.test(B)?$=P.getMouseInfo(D.changedTouches[0]):$=P.getMouseInfo(D),z((F=$)!==null&&F!==void 0?F:{},D)}}),gi(P,"handleClick",function(D){var B=P.getMouseInfo(D);if(B){var z=Pr(Pr({},B),{},{isTooltipActive:!0});P.setState(z),P.triggerSyncEvent(z);var F=P.props.onClick;Ti(F)&&F(z,D)}}),gi(P,"handleMouseDown",function(D){var B=P.props.onMouseDown;if(Ti(B)){var z=P.getMouseInfo(D);B(z,D)}}),gi(P,"handleMouseUp",function(D){var B=P.props.onMouseUp;if(Ti(B)){var z=P.getMouseInfo(D);B(z,D)}}),gi(P,"handleTouchMove",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&P.throttleTriggeredAfterMouseMove(D.changedTouches[0])}),gi(P,"handleTouchStart",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&P.handleMouseDown(D.changedTouches[0])}),gi(P,"handleTouchEnd",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&P.handleMouseUp(D.changedTouches[0])}),gi(P,"handleDoubleClick",function(D){var B=P.props.onDoubleClick;if(Ti(B)){var z=P.getMouseInfo(D);B(z,D)}}),gi(P,"handleContextMenu",function(D){var B=P.props.onContextMenu;if(Ti(B)){var z=P.getMouseInfo(D);B(z,D)}}),gi(P,"triggerSyncEvent",function(D){P.props.syncId!==void 0&&d_e.emit(u_e,P.props.syncId,D,P.eventEmitterSymbol)}),gi(P,"applySyncEvent",function(D){var B=P.props,z=B.layout,F=B.syncMethod,$=P.state.updateId,X=D.dataStartIndex,K=D.dataEndIndex;if(D.dataStartIndex!==void 0||D.dataEndIndex!==void 0)P.setState(Pr({dataStartIndex:X,dataEndIndex:K},g({props:P.props,dataStartIndex:X,dataEndIndex:K,updateId:$},P.state)));else if(D.activeTooltipIndex!==void 0){var Q=D.chartX,Y=D.chartY,ne=D.activeTooltipIndex,de=P.state,ce=de.offset,ae=de.tooltipTicks;if(!ce)return;if(typeof F=="function")ne=F(ae,D);else if(F==="value"){ne=-1;for(var ie=0;ie=0){var Te,ye;if(Q.dataKey&&!Q.allowDuplicatedCategory){var ct=typeof Q.dataKey=="function"?ze:"payload.".concat(Q.dataKey.toString());Te=Qhe(ie,ct,ne),ye=me&&oe&&Qhe(oe,ct,ne)}else Te=ie==null?void 0:ie[Y],ye=me&&oe&&oe[Y];if(Pe||Me){var ve=D.props.activeIndex!==void 0?D.props.activeIndex:Y;return[k.cloneElement(D,Pr(Pr(Pr({},F.props),$e),{},{activeIndex:ve})),null,null]}if(!Fi(Te))return[Se].concat(QI(P.renderActivePoints({item:F,activePoint:Te,basePoint:ye,childIndex:Y,isRange:me})))}else{var rt,Re=(rt=P.getItemByXY(P.state.activeCoordinate))!==null&&rt!==void 0?rt:{graphicalItem:Se},Qe=Re.graphicalItem,Ke=Qe.item,Ce=Ke===void 0?D:Ke,nt=Qe.childIndex,$t=Pr(Pr(Pr({},F.props),$e),{},{activeIndex:nt});return[k.cloneElement(Ce,$t),null,null]}return me?[Se,null,null]:[Se,null]}),gi(P,"renderCustomized",function(D,B,z){return k.cloneElement(D,Pr(Pr({key:"recharts-customized-".concat(z)},P.props),P.state))}),gi(P,"renderMap",{CartesianGrid:{handler:UU,once:!0},ReferenceArea:{handler:P.renderReferenceElement},ReferenceLine:{handler:UU},ReferenceDot:{handler:P.renderReferenceElement},XAxis:{handler:UU},YAxis:{handler:UU},Brush:{handler:P.renderBrush,once:!0},Bar:{handler:P.renderGraphicChild},Line:{handler:P.renderGraphicChild},Area:{handler:P.renderGraphicChild},Radar:{handler:P.renderGraphicChild},RadialBar:{handler:P.renderGraphicChild},Scatter:{handler:P.renderGraphicChild},Pie:{handler:P.renderGraphicChild},Funnel:{handler:P.renderGraphicChild},Tooltip:{handler:P.renderCursor,once:!0},PolarGrid:{handler:P.renderPolarGrid,once:!0},PolarAngleAxis:{handler:P.renderPolarAxis},PolarRadiusAxis:{handler:P.renderPolarAxis},Customized:{handler:P.renderCustomized}}),P.clipPathId="".concat((T=S.id)!==null&&T!==void 0?T:GP("recharts"),"-clip"),P.throttleTriggeredAfterMouseMove=Bdt(P.triggeredAfterMouseMove,(A=S.throttleDelay)!==null&&A!==void 0?A:1e3/60),P.state={},P}return BCs(N,b),DCs(N,[{key:"componentDidMount",value:function(){var T,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var T=this.props,A=T.children,P=T.data,D=T.height,B=T.layout,z=tx(A,rp);if(z){var F=z.props.defaultIndex;if(!(typeof F!="number"||F<0||F>this.state.tooltipTicks.length-1)){var $=this.state.tooltipTicks[F]&&this.state.tooltipTicks[F].value,X=gSe(this.state,P,F,$),K=this.state.tooltipTicks[F].coordinate,Q=(this.state.offset.top+D)/2,Y=B==="horizontal",ne=Y?{x:K,y:Q}:{y:K,x:Q},de=this.state.formattedGraphicalItems.find(function(ae){var ie=ae.item;return ie.type.name==="Scatter"});de&&(ne=Pr(Pr({},ne),de.props.points[F].tooltipPosition),X=de.props.points[F].tooltipPayload);var ce={activeTooltipIndex:F,isTooltipActive:!0,activeLabel:$,activePayload:X,activeCoordinate:ne};this.setState(ce),this.renderCursor(z),this.accessibilityManager.setIndex(F)}}}},{key:"getSnapshotBeforeUpdate",value:function(T,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==T.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==T.margin){var P,D;this.accessibilityManager.setDetails({offset:{left:(P=this.props.margin.left)!==null&&P!==void 0?P:0,top:(D=this.props.margin.top)!==null&&D!==void 0?D:0}})}return null}},{key:"componentDidUpdate",value:function(T){GNe([tx(T.children,rp)],[tx(this.props.children,rp)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var T=tx(this.props.children,rp);if(T&&typeof T.props.shared=="boolean"){var A=T.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(T){if(!this.container)return null;var A=this.container,P=A.getBoundingClientRect(),D=Fxs(P),B={chartX:Math.round(T.pageX-D.left),chartY:Math.round(T.pageY-D.top)},z=P.width/A.offsetWidth||1,F=this.inRange(B.chartX,B.chartY,z);if(!F)return null;var $=this.state,X=$.xAxisMap,K=$.yAxisMap,Q=this.getTooltipEventType(),Y=YUe(this.state,this.props.data,this.props.layout,F);if(Q!=="axis"&&X&&K){var ne=pj(X).scale,de=pj(K).scale,ce=ne&&ne.invert?ne.invert(B.chartX):null,ae=de&&de.invert?de.invert(B.chartY):null;return Pr(Pr({},B),{},{xValue:ce,yValue:ae},Y)}return Y?Pr(Pr({},B),Y):null}},{key:"inRange",value:function(T,A){var P=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,D=this.props.layout,B=T/P,z=A/P;if(D==="horizontal"||D==="vertical"){var F=this.state.offset,$=B>=F.left&&B<=F.left+F.width&&z>=F.top&&z<=F.top+F.height;return $?{x:B,y:z}:null}var X=this.state,K=X.angleAxisMap,Q=X.radiusAxisMap;if(K&&Q){var Y=pj(K);return j$e({x:B,y:z},Y)}return null}},{key:"parseEventsOfWrapper",value:function(){var T=this.props.children,A=this.getTooltipEventType(),P=tx(T,rp),D={};P&&A==="axis"&&(P.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 B=Jhe(this.props,this.handleOuterEvent);return Pr(Pr({},B),D)}},{key:"addListener",value:function(){d_e.on(u_e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){d_e.removeListener(u_e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(T,A,P){for(var D=this.state.formattedGraphicalItems,B=0,z=D.length;B{const{data:S,error:T}=await H.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(T)throw T;return S}}),{data:n}=gt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:S,error:T}=await H.from("profiles").select("id, name, email");if(T)throw T;return S}});if(r)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((n||[]).map(S=>[S.id,S])),l=a.reduce((S,T)=>S+(T.sent_count||0),0),o=a.reduce((S,T)=>S+(T.open_count||0),0),c=a.reduce((S,T)=>S+(T.click_count||0),0),d=a.reduce((S,T)=>S+(T.bounce_count||0),0),h=a.reduce((S,T)=>S+(T.complaint_count||0),0),m=l>0?(o/l*100).toFixed(1):"0.0",x=l>0?(c/l*100).toFixed(1):"0.0",g=[{label:"Campaigns Sent",value:a.length,icon:Zr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:fr,color:"text-green-600"},{label:"Avg Open Rate",value:`${m}%`,icon:jn,color:"text-blue-600"},{label:"Avg Click Rate",value:`${x}%`,icon:tm,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:od,color:"text-orange-600"},{label:"Complaints",value:h,icon:_o,color:"text-destructive"}],v=new Map;a.forEach(S=>{var P,D;const T=S.user_id,A=v.get(T)||{name:((P=i.get(T))==null?void 0:P.name)||((D=i.get(T))==null?void 0:D.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=S.sent_count||0,A.opens+=S.open_count||0,A.clicks+=S.click_count||0,v.set(T,A)});const j=[...v.entries()].map(([S,T])=>({id:S,...T,openRate:T.sent>0?+(T.opens/T.sent*100).toFixed(1):0})).sort((S,T)=>T.sent-S.sent),b=j.slice(0,6).map(S=>({name:S.name,value:S.sent})),N=a.map(S=>{var T;return{name:S.name.length>20?S.name.slice(0,20)+"…":S.name,agent:((T=i.get(S.user_id))==null?void 0:T.name)||"Unknown",openRate:S.sent_count>0?+(S.open_count/S.sent_count*100).toFixed(1):0,clickRate:S.sent_count>0?+(S.click_count/S.sent_count*100).toFixed(1):0,sent:S.sent_count,date:S.sent_at?Ss(new Date(S.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold 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:g.map(S=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx(S.icon,{className:`h-5 w-5 mx-auto mb-1 ${S.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:S.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.label})]})},S.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(IM,{width:"100%",height:"100%",children:e.jsxs(umt,{data:N,children:[e.jsx(D5,{dataKey:"date",fontSize:11}),e.jsx(R5,{fontSize:11,unit:"%"}),e.jsx(rp,{formatter:S=>`${S}%`}),e.jsx(j_,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(j_,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(IM,{width:"100%",height:"100%",children:e.jsxs(hmt,{children:[e.jsx(w1,{data:b,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:S,percent:T})=>`${S} (${(T*100).toFixed(0)}%)`,fontSize:11,children:b.map((S,T)=>e.jsx(wz,{fill:QUe[T%QUe.length]},T))}),e.jsx(rp,{})]})})})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(IM,{width:"100%",height:"100%",children:e.jsxs(t4s,{data:N,children:[e.jsx(D5,{dataKey:"date",fontSize:11}),e.jsx(R5,{fontSize:11}),e.jsx(rp,{}),e.jsx(Ez,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Agent Performance"})}),e.jsx(De,{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:j.map(S=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:S.name}),e.jsx("td",{className:"py-2.5 text-center",children:S.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:S.sent}),e.jsx("td",{className:"py-2.5 text-center",children:S.opens}),e.jsx("td",{className:"py-2.5 text-center",children:S.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Ge,{variant:"outline",children:[S.openRate,"%"]})})]},S.id))})]})})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((S,T)=>{const A=S.sent_count>0?S.open_count/S.sent_count:0;return(T.sent_count>0?T.open_count/T.sent_count:0)-A}).slice(0,10).map((S,T)=>{const A=S.sent_count>0?(S.open_count/S.sent_count*100).toFixed(1):"0.0",P=S.sent_count>0?(S.click_count/S.sent_count*100).toFixed(1):"0.0",D=i.get(S.user_id);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/30 cursor-pointer",onClick:()=>s(`/admin/email-campaigns/${S.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",T+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:S.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(D==null?void 0:D.name)||"Unknown"," · ",S.sent_at?Ss(new Date(S.sent_at),"MMM d, yyyy"):""," · ",S.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(jn,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(tm,{className:"h-3 w-3"})," ",P,"%"]})]})]},S.id)})})})]})]})})}const r4s=()=>{const{toast:s}=Ea(),[t,r]=k.useState(!0),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});k.useEffect(()=>{d()},[]);const d=async()=>{try{r(!0);const h=new Date;h.setDate(h.getDate()-30);const m=h.toISOString(),{data:x}=await H.from("website_apps").select("slug, name").order("sort_order"),g=[];let v=0;for(;;){const{data:P,error:D}=await H.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(v,v+999);if(D)throw D;if(g.push(...P||[]),!P||P.length<1e3)break;v+=1e3}const j=[];for(v=0;;){const{data:P,error:D}=await H.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",m).order("created_at",{ascending:!1}).range(v,v+999);if(D)throw D;if(j.push(...P||[]),!P||P.length<1e3||(v+=1e3,v>2e4))break}const b=new Map;for(const P of x||[])b.set(P.slug,{app_slug:P.slug,app_name:P.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const P of g){const D=b.get(P.app_slug);D&&(D.installs+=1,P.enabled&&(D.enabled+=1))}for(const P of j){const D=b.get(P.app_slug);D&&(P.event_type==="impression"?D.impressions+=1:P.event_type==="expand"?D.expands+=1:P.event_type==="cta_click"?D.cta_clicks+=1:P.event_type==="lead_capture"&&(D.lead_captures+=1))}const N=new Map;for(const P of g){if(!P.enabled)continue;const D=N.get(P.user_id)||{user_id:P.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};D.apps_enabled.includes(P.app_slug)||D.apps_enabled.push(P.app_slug),N.set(P.user_id,D)}for(const P of j){const D=N.get(P.user_id);D&&(D.events_30d+=1,P.event_type==="lead_capture"&&(D.leads_30d+=1))}const S=Array.from(N.keys());if(S.length>0){const{data:P}=await H.from("profiles").select("id, name, email").in("id",S);for(const D of P||[]){const B=N.get(D.id);B&&(B.name=D.name,B.email=D.email)}}const T=Array.from(b.values()),A=Array.from(N.values()).sort((P,D)=>D.events_30d-P.events_30d);a(T),l(A),c({installs:T.reduce((P,D)=>P+D.enabled,0),activeAgents:A.length,impressions30d:T.reduce((P,D)=>P+D.impressions,0),leads30d:T.reduce((P,D)=>P+D.lead_captures,0)})}catch(h){console.error(h),s({title:"Error",description:h.message||"Failed to load website app analytics",variant:"destructive"})}finally{r(!1)}};return t?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(gc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"App Performance (last 30 days)"})}),e.jsx(De,{children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{className:"text-right",children:"Installs"}),e.jsx(Tt,{className:"text-right",children:"Enabled"}),e.jsx(Tt,{className:"text-right",children:"Impressions"}),e.jsx(Tt,{className:"text-right",children:"Expands"}),e.jsx(Tt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(Bn,{children:[n.map(h=>{const m=h.impressions>0?(h.lead_captures/h.impressions*100).toFixed(1):"—";return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:h.app_name}),e.jsx(ft,{className:"text-right",children:h.installs}),e.jsx(ft,{className:"text-right",children:h.enabled}),e.jsx(ft,{className:"text-right",children:h.impressions}),e.jsx(ft,{className:"text-right",children:h.expands}),e.jsx(ft,{className:"text-right",children:h.cta_clicks}),e.jsx(ft,{className:"text-right font-semibold",children:h.lead_captures}),e.jsx(ft,{className:"text-right text-muted-foreground",children:m==="—"?"—":`${m}%`})]},h.app_slug)}),n.length===0&&e.jsx(qs,{children:e.jsx(ft,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(De,{children:[e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Apps Enabled"}),e.jsx(Tt,{className:"text-right",children:"Events (30d)"}),e.jsx(Tt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(Bn,{children:[i.slice(0,100).map(h=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:h.name||"—"}),e.jsx(ft,{className:"text-muted-foreground",children:h.email||"—"}),e.jsx(ft,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:h.apps_enabled.map(m=>e.jsx(Ge,{variant:"secondary",className:"text-xs",children:m},m))})}),e.jsx(ft,{className:"text-right",children:h.events_30d}),e.jsx(ft,{className:"text-right font-semibold",children:h.leads_30d})]},h.user_id)),i.length===0&&e.jsx(qs,{children:e.jsx(ft,{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."]})]})]})]})},n4s=()=>{const[s,t]=k.useState([]),[r,n]=k.useState([]),[a,i]=k.useState({}),[l,o]=k.useState(!0);k.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:m},{data:x}]=await Promise.all([H.rpc("get_extension_usage_summary"),H.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),g=m||[],v=x||[];t(g),n(v);const j=Array.from(new Set(v.map(b=>b.user_id)));if(j.length){const{data:b}=await H.from("profiles").select("id, name, email").in("id",j),N={};(b||[]).forEach(S=>{N[S.id]={name:S.name,email:S.email}}),i(N)}}finally{o(!1)}},d=s.reduce((m,x)=>({users:m.users+1,contacts:m.contacts+Number(x.contacts_saved||0),listings:m.listings+Number(x.listings_imported||0),activities:m.activities+Number(x.activities_logged||0),events:m.events+Number(x.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(Ne,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const h=m=>{switch(m){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return m}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(w3,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(bi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Users by Extension Activity"})}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{className:"text-right",children:"Total"}),e.jsx(Tt,{className:"text-right",children:"Contacts"}),e.jsx(Tt,{className:"text-right",children:"Listings"}),e.jsx(Tt,{className:"text-right",children:"Activities"}),e.jsx(Tt,{children:"First Used"}),e.jsx(Tt,{children:"Last Used"})]})}),e.jsx(Bn,{children:s.map(m=>e.jsxs(qs,{children:[e.jsxs(ft,{children:[e.jsx("div",{className:"font-medium",children:m.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.email})]}),e.jsx(ft,{className:"text-right font-medium",children:m.total_events}),e.jsx(ft,{className:"text-right",children:m.contacts_saved}),e.jsx(ft,{className:"text-right",children:m.listings_imported}),e.jsx(ft,{className:"text-right",children:m.activities_logged}),e.jsx(ft,{className:"text-xs text-muted-foreground",children:m.first_event_at?Ss(new Date(m.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(ft,{className:"text-xs text-muted-foreground",children:m.last_event_at?Ss(new Date(m.last_event_at),"MMM d, h:mm a"):"—"})]},m.user_id))})]})})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Recent Activity"})}),e.jsx(De,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:r.map(m=>{const x=a[m.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ge,{variant:"secondary",children:h(m.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(x==null?void 0:x.name)||(x==null?void 0:x.email)||m.user_id.slice(0,8)}),m.metadata&&Object.keys(m.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(m.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(m.created_at),"MMM d, h:mm a")})]},m.id)})})})]})]})},a4s=()=>e.jsx(_s,{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(Rn,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"analytics",children:"Analytics"}),e.jsx(Xt,{value:"website-apps",children:"Website Apps"}),e.jsx(Xt,{value:"extension",children:"Chrome Extension"}),e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Xt,{value:"activity",children:"Activity"}),e.jsx(Xt,{value:"shares",children:"Shares"})]}),e.jsx(as,{value:"analytics",className:"space-y-4",children:e.jsx(yss,{})}),e.jsx(as,{value:"website-apps",className:"space-y-4",children:e.jsx(r4s,{})}),e.jsx(as,{value:"extension",className:"space-y-4",children:e.jsx(n4s,{})}),e.jsx(as,{value:"content",className:"space-y-4",children:e.jsx(bss,{})}),e.jsx(as,{value:"email-campaigns",className:"space-y-4",children:e.jsx(s4s,{})}),e.jsx(as,{value:"activity",className:"space-y-4",children:e.jsx(gss,{})}),e.jsx(as,{value:"shares",className:"space-y-4",children:e.jsx(Nct,{})})]})]})});function i4s(){const s=es(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState([]),[g,v]=k.useState([]),[j,b]=k.useState([]),[N,S]=k.useState(!1),[T,A]=k.useState(null),[P,D]=k.useState(""),{data:B,isLoading:z}=gt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(ct)throw ct;return ye}}),{data:F}=gt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(ct)throw ct;return ye}}),{data:$}=gt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(ct)throw ct;return ye}}),{data:X}=gt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(ct)throw ct;return ye}}),{data:K,isLoading:Q}=gt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(ct)throw ct;return ye}}),Y=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),h(""),x([]),v([]),b([]),a(null),D("")},ne=ye=>{a(ye),l({title:ye.title,description:ye.description||"",publish_date:ye.publish_date.split("T")[0],is_published:ye.is_published,category_id:ye.category_id||""}),h(ye.preview_image_url||""),D("");const ct=(F==null?void 0:F.filter(Re=>Re.resource_id===ye.id))||[];x(ct.map(Re=>({id:Re.id,name:Re.name,file_url:Re.file_url,file_size:Re.file_size,sort_order:Re.sort_order})));const ve=($==null?void 0:$.filter(Re=>Re.resource_id===ye.id))||[];v(ve.map(Re=>({id:Re.id,title:Re.title,video_url:Re.video_url,sort_order:Re.sort_order})));const rt=(X==null?void 0:X.filter(Re=>Re.resource_id===ye.id))||[];b(rt.map(Re=>({id:Re.id,title:Re.title,canva_share_link:Re.canva_share_link,sort_order:Re.sort_order}))),r(!0)},de=ye=>{var ve;const ct=(ve=ye.target.files)==null?void 0:ve[0];ct&&(c(ct),h(URL.createObjectURL(ct)))},ce=()=>{x([...m,{name:"",file_url:"",sort_order:m.length}])},ae=ye=>{x(m.filter((ct,ve)=>ve!==ye))},ie=(ye,ct,ve)=>{const rt=[...m];if(ct==="file"&&ve instanceof File){const Re=ve.name.replace(/\.[^/.]+$/,"");rt[ye]={...rt[ye],file:ve,file_size:ve.size,name:rt[ye].name||Re}}else rt[ye]={...rt[ye],[ct]:ve};x(rt)},me=()=>{v([...g,{title:"",video_url:"",sort_order:g.length}])},oe=ye=>{v(g.filter((ct,ve)=>ve!==ye))},ge=(ye,ct,ve)=>{const rt=[...g];ct==="file"&&ve instanceof File?rt[ye]={...rt[ye],file:ve}:rt[ye]={...rt[ye],[ct]:ve},v(rt)},be=()=>{b([...j,{title:"",canva_share_link:"",sort_order:j.length}])},Oe=ye=>{b(j.filter((ct,ve)=>ve!==ye))},Me=(ye,ct,ve)=>{const rt=[...j];rt[ye]={...rt[ye],[ct]:ve},b(rt)},Pe=async(ye,ct)=>{try{const ve=await H.functions.invoke("bunny-upload",{body:{action:"create",title:ye.name}});if(ve.error)throw ve.error;const{videoId:rt,uploadUrl:Re,libraryId:Qe}=ve.data,Ke=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:rt,libraryId:Qe}});if(Ke.error)throw Ke.error;const{uploadUrl:Ce,apiKey:nt}=Ke.data,$t=new XMLHttpRequest;return $t.open("PUT",Ce,!0),$t.setRequestHeader("AccessKey",nt),$t.upload.onprogress=lt=>{if(lt.lengthComputable){const it=Math.round(lt.loaded/lt.total*100),Nt=[...g];Nt[ct]={...Nt[ct],uploadProgress:it},v(Nt)}},await new Promise((lt,it)=>{$t.onload=()=>$t.status>=200&&$t.status<300?lt():it(new Error("Upload failed")),$t.onerror=()=>it(new Error("Upload failed")),$t.send(ye)}),`https://iframe.mediadelivery.net/embed/${Qe}/${rt}`}catch(ve){throw console.error("Bunny upload error:",ve),ve}},Ee=Lt({mutationFn:async ye=>{const{data:ct,error:ve}=await H.from("brokerage_resource_categories").insert({name:ye,sort_order:(K==null?void 0:K.length)||0}).select().single();if(ve)throw ve;return ct},onSuccess:ye=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ye.id}),D(""),ue.success("Category created")},onError:ye=>{ue.error("Failed to create category: "+ye.message)}}),$e=Lt({mutationFn:async()=>{S(!0);let ye=(n==null?void 0:n.preview_image_url)||null;if(o){const rt=o.name.split(".").pop(),Re=`${Date.now()}.${rt}`,{error:Qe}=await H.storage.from("brokerage-resources").upload(`previews/${Re}`,o);if(Qe)throw Qe;const{data:Ke}=H.storage.from("brokerage-resources").getPublicUrl(`previews/${Re}`);ye=Ke.publicUrl}const ct={title:i.title,description:i.description||null,preview_image_url:ye,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let ve;if(n){const{error:rt}=await H.from("brokerage_resources").update(ct).eq("id",n.id);if(rt)throw rt;ve=n.id;const Re=(F==null?void 0:F.filter(Ft=>Ft.resource_id===n.id).map(Ft=>Ft.id))||[],Qe=m.filter(Ft=>Ft.id).map(Ft=>Ft.id),Ke=Re.filter(Ft=>!Qe.includes(Ft));Ke.length>0&&await H.from("brokerage_resource_pdfs").delete().in("id",Ke);const Ce=($==null?void 0:$.filter(Ft=>Ft.resource_id===n.id).map(Ft=>Ft.id))||[],nt=g.filter(Ft=>Ft.id).map(Ft=>Ft.id),$t=Ce.filter(Ft=>!nt.includes(Ft));$t.length>0&&await H.from("brokerage_resource_videos").delete().in("id",$t);const lt=(X==null?void 0:X.filter(Ft=>Ft.resource_id===n.id).map(Ft=>Ft.id))||[],it=j.filter(Ft=>Ft.id).map(Ft=>Ft.id),Nt=lt.filter(Ft=>!it.includes(Ft));Nt.length>0&&await H.from("brokerage_resource_links").delete().in("id",Nt)}else{const{data:rt,error:Re}=await H.from("brokerage_resources").insert(ct).select().single();if(Re)throw Re;ve=rt.id}for(let rt=0;rt{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ue.success(n?"Resource updated":"Resource created"),r(!1),Y(),S(!1)},onError:ye=>{ue.error("Failed to save resource: "+ye.message),S(!1)}}),Se=Lt({mutationFn:async ye=>{const{error:ct}=await H.from("brokerage_resources").delete().eq("id",ye);if(ct)throw ct},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ue.success("Resource deleted")},onError:ye=>{ue.error("Failed to delete: "+ye.message)}}),ze=ye=>{if(ye.preventDefault(),!i.title){ue.error("Please enter a title");return}$e.mutate()},Te=ye=>{const ct=(F==null?void 0:F.filter(Re=>Re.resource_id===ye).length)||0,ve=($==null?void 0:$.filter(Re=>Re.resource_id===ye).length)||0,rt=(X==null?void 0:X.filter(Re=>Re.resource_id===ye).length)||0;return{pdfCount:ct,videoCount:ve,linkCount:rt}};return e.jsx(_s,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(B==null?void 0:B.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(B==null?void 0:B.filter(ye=>ye.is_published).length)||0})})]})]}),e.jsxs(G,{onClick:()=>{Y(),r(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Content"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:z?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(B==null?void 0:B.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):B==null?void 0:B.map(ye=>{const{pdfCount:ct,videoCount:ve,linkCount:rt}=Te(ye.id),Re=K==null?void 0:K.find(Qe=>Qe.id===ye.category_id);return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ye.preview_image_url?e.jsx("img",{src:ye.preview_image_url,alt:ye.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(Yu,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ye.title}),ye.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ye.description})]})]})}),e.jsx(ft,{children:Re?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Re.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),ct]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),ve]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xo,{className:"h-3.5 w-3.5"}),rt]})]})}),e.jsx(ft,{children:Ss(new Date(ye.publish_date),"MMM d, yyyy")}),e.jsx(ft,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ye.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ye.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{const Qe=(F==null?void 0:F.filter(nt=>nt.resource_id===ye.id))||[],Ke=($==null?void 0:$.filter(nt=>nt.resource_id===ye.id))||[],Ce=(X==null?void 0:X.filter(nt=>nt.resource_id===ye.id))||[];A({...ye,pdfs:Qe,videos:Ke,links:Ce})},children:e.jsx(jn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ne(ye),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Se.mutate(ye.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},ye.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(js,{children:e.jsx(bs,{children:n?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:ze,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[d?e.jsx("img",{src:d,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(Yu,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ke,{type:"file",accept:"image/*",onChange:de})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:i.title,onChange:ye=>l({...i,title:ye.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Ah,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{value:i.category_id,onValueChange:ye=>l({...i,category_id:ye}),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select a category"})}),e.jsx(Fs,{children:K==null?void 0:K.map(ye=>e.jsx(mt,{value:ye.id,children:ye.name},ye.id))})]}),i.category_id&&e.jsx(G,{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(ke,{placeholder:"Or create new category...",value:P,onChange:ye=>D(ye.target.value),className:"flex-1"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",disabled:!P.trim()||Ee.isPending,onClick:()=>Ee.mutate(P.trim()),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:i.description,onChange:ye=>l({...i,description:ye}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:i.publish_date,onChange:ye=>l({...i,publish_date:ye.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(br,{checked:i.is_published,onCheckedChange:ye=>l({...i,is_published:ye})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"PDF Documents (",m.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),m.map((ye,ct)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ke,{placeholder:"PDF Name",value:ye.name,onChange:ve=>ie(ct,"name",ve.target.value),className:"flex-1"}),e.jsx(ke,{type:"file",accept:".pdf",onChange:ve=>{var Re;const rt=(Re=ve.target.files)==null?void 0:Re[0];rt&&ie(ct,"file",rt)},className:"flex-1"}),ye.file_url&&!ye.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(ct),children:e.jsx(_r,{className:"h-4 w-4"})})]},ct))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Videos (",g.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:me,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),g.map((ye,ct)=>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(ke,{placeholder:"Video Title",value:ye.title,onChange:ve=>ge(ct,"title",ve.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>oe(ct),children:e.jsx(_r,{className:"h-4 w-4"})})]}),e.jsx(ke,{type:"file",accept:"video/*",onChange:ve=>{var Re;const rt=(Re=ve.target.files)==null?void 0:Re[0];rt&&ge(ct,"file",rt)}}),ye.uploadProgress!==void 0&&ye.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:`${ye.uploadProgress}%`}})}),ye.video_url&&!ye.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},ct))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4"}),"Canva Links (",j.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),j.map((ye,ct)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ke,{placeholder:"Link Title",value:ye.title,onChange:ve=>Me(ct,"title",ve.target.value),className:"flex-1"}),e.jsx(ke,{placeholder:"Canva Share Link",value:ye.canva_share_link,onChange:ve=>Me(ct,"canva_share_link",ve.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>Oe(ct),children:e.jsx(_r,{className:"h-4 w-4"})})]},ct))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:$e.isPending||N,children:$e.isPending||N?"Saving...":n?"Update":"Create"})]})]})]})}),e.jsx(vs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:T==null?void 0:T.title})}),T&&e.jsxs("div",{className:"space-y-4",children:[T.preview_image_url&&e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-48 object-cover rounded-lg"}),T.description&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),T.pdfs&&T.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"PDF Documents (",T.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.pdfs.map(ye=>e.jsx("a",{href:ye.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ye.name},ye.id))})]}),T.videos&&T.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Videos (",T.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.videos.map(ye=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ye.title})},ye.id))})]}),T.links&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4"}),"Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.links.map(ye=>e.jsx("a",{href:ye.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ye.title},ye.id))})]})]})]})})]})})}const mmt=[{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 o4s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,P]=k.useState(""),[D,B]=k.useState("Learn More"),[z,F]=k.useState("top"),[$,X]=k.useState(""),[K,Q]=k.useState(!0),[Y,ne]=k.useState(""),[de,ce]=k.useState("");k.useEffect(()=>{ae()},[]);const ae=async()=>{try{const{data:Ee,error:$e}=await H.from("dashboard_banners").select("*").order("placement").order("sort_order");if($e)throw $e;t(Ee||[])}catch(Ee){ue.error("Failed to load banners: "+Ee.message)}finally{n(!1)}},ie=()=>{j(""),N(""),T(""),P(""),B("Learn More"),F("top"),X(""),Q(!0),ne(""),ce(""),d(null)},me=Ee=>{d(Ee),j(Ee.title),N(Ee.description||""),T(Ee.image_url),P(Ee.link_url||""),B(Ee.link_text||"Learn More"),F(Ee.placement),X(Ee.section_after||""),Q(Ee.is_active),ne(Ee.start_date?Ss(new Date(Ee.start_date),"yyyy-MM-dd'T'HH:mm"):""),ce(Ee.end_date?Ss(new Date(Ee.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},oe=async Ee=>{var Se;const $e=(Se=Ee.target.files)==null?void 0:Se[0];if($e){m(!0);try{const ze=$e.name.split(".").pop(),Te=`${Date.now()}.${ze}`,{error:ye}=await H.storage.from("banner-images").upload(Te,$e);if(ye)throw ye;const{data:{publicUrl:ct}}=H.storage.from("banner-images").getPublicUrl(Te);T(ct),ue.success("Image uploaded successfully")}catch(ze){ue.error("Failed to upload image: "+ze.message)}finally{m(!1)}}},ge=async()=>{if(!v.trim()||!S){ue.error("Please fill in required fields (title and image)");return}g(!0);try{const Ee={title:v.trim(),description:b.trim()||null,image_url:S,link_url:A.trim()||null,link_text:D.trim()||"Learn More",placement:z,section_after:z==="between"?$:null,is_active:K,start_date:Y?new Date(Y).toISOString():null,end_date:de?new Date(de).toISOString():null};if(c){const{error:$e}=await H.from("dashboard_banners").update(Ee).eq("id",c.id);if($e)throw $e;ue.success("Banner updated successfully")}else{const $e=s.filter(ze=>ze.placement===z).length,{error:Se}=await H.from("dashboard_banners").insert({...Ee,sort_order:$e});if(Se)throw Se;ue.success("Banner created successfully")}i(!1),ie(),ae()}catch(Ee){ue.error("Failed to save banner: "+Ee.message)}finally{g(!1)}},be=async()=>{if(c)try{const{error:Ee}=await H.from("dashboard_banners").delete().eq("id",c.id);if(Ee)throw Ee;ue.success("Banner deleted successfully"),o(!1),d(null),ae()}catch(Ee){ue.error("Failed to delete banner: "+Ee.message)}},Oe=async Ee=>{try{const{error:$e}=await H.from("dashboard_banners").update({is_active:!Ee.is_active}).eq("id",Ee.id);if($e)throw $e;ue.success(Ee.is_active?"Banner deactivated":"Banner activated"),ae()}catch($e){ue.error("Failed to update banner: "+$e.message)}},Me=s.filter(Ee=>Ee.placement==="top"),Pe=s.filter(Ee=>Ee.placement==="between");return r?e.jsx(_s,{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(_s,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Nr,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(vs,{open:a&&z==="top",onOpenChange:Ee=>{Ee||ie(),i(Ee),Ee&&F("top")},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{onClick:()=>{ie(),F("top")},children:[e.jsx(Ws,{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(js,{children:[e.jsxs(bs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Fr,{children:"Configure the banner's content and display settings"})]}),e.jsx(JUe,{title:v,setTitle:j,description:b,setDescription:N,imageUrl:S,linkUrl:A,setLinkUrl:P,linkText:D,setLinkText:B,placement:z,setPlacement:F,sectionAfter:$,setSectionAfter:X,isActive:K,setIsActive:Q,startDate:Y,setStartDate:ne,endDate:de,setEndDate:ce,handleImageUpload:oe,uploading:h,showPlacementOptions:!1}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx(G,{onClick:ge,disabled:x,children:x?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{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(Ee=>e.jsx(eqe,{banner:Ee,onEdit:()=>me(Ee),onDelete:()=>{d(Ee),o(!0)},onToggleActive:()=>Oe(Ee)},Ee.id))})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Nr,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(vs,{open:a&&z==="between",onOpenChange:Ee=>{Ee||ie(),i(Ee),Ee&&F("between")},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{onClick:()=>{ie(),F("between")},children:[e.jsx(Ws,{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(js,{children:[e.jsxs(bs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Fr,{children:"Configure where this banner appears between sections"})]}),e.jsx(JUe,{title:v,setTitle:j,description:b,setDescription:N,imageUrl:S,linkUrl:A,setLinkUrl:P,linkText:D,setLinkText:B,placement:z,setPlacement:F,sectionAfter:$,setSectionAfter:X,isActive:K,setIsActive:Q,startDate:Y,setStartDate:ne,endDate:de,setEndDate:ce,handleImageUpload:oe,uploading:h,showPlacementOptions:!0}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx(G,{onClick:ge,disabled:x,children:x?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{children:Pe.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:Pe.map(Ee=>e.jsx(eqe,{banner:Ee,onEdit:()=>me(Ee),onDelete:()=>{d(Ee),o(!0)},onToggleActive:()=>Oe(Ee),showSection:!0},Ee.id))})})]})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Delete Banner"}),e.jsxs(Fr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}function JUe({title:s,setTitle:t,description:r,setDescription:n,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:h,sectionAfter:m,setSectionAfter:x,isActive:g,setIsActive:v,startDate:j,setStartDate:b,endDate:N,setEndDate:S,handleImageUpload:T,uploading:A,showPlacementOptions:P}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",placeholder:"Banner headline...",value:s,onChange:D=>t(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",placeholder:"Optional banner description...",value:r,onChange:D=>n(D.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ke,{type:"file",accept:"image/*",onChange:T,disabled:A,className:"flex-1"}),A&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(ke,{id:"linkUrl",placeholder:"https://...",value:i,onChange:D=>l(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"linkText",children:"Button Text"}),e.jsx(ke,{id:"linkText",placeholder:"Learn More",value:o,onChange:D=>c(D.target.value)})]})]}),P&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Placement"}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select section placement..."})}),e.jsx(Fs,{children:mmt.map(D=>e.jsx(mt,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(ke,{id:"startDate",type:"datetime-local",value:j,onChange:D=>b(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(ke,{id:"endDate",type:"datetime-local",value:N,onChange:D=>S(D.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"isActive",checked:g,onCheckedChange:v}),e.jsx(he,{htmlFor:"isActive",children:"Active"})]})})]})}function eqe({banner:s,onEdit:t,onDelete:r,onToggleActive:n,showSection:a=!1}){var c;const i=(c=mmt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=k.useState(null);return k.useEffect(()=>{(async()=>{const{count:h}=await H.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(h??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Su,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx(Ge,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Ge,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(Dd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-semibold",children:l})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.link_url&&e.jsx("a",{href:s.link_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(G,{variant:"ghost",size:"icon",children:e.jsx(Yr,{className:"h-4 w-4"})})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:n,children:s.is_active?e.jsx(jn,{className:"h-4 w-4"}):e.jsx(am,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]})}const qU={open:{label:"Open",icon:cn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:tc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:mi,color:"bg-green-500"},closed:{label:"Closed",icon:Mc,color:"bg-muted-foreground"}},tqe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function l4s(){var z,F;const{user:s}=As(),t=es(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),[c,d]=k.useState("all"),[h,m]=k.useState("all"),[x,g]=k.useState(!1),{data:v=[],isLoading:j}=gt({queryKey:["admin-support-tickets",c,h],queryFn:async()=>{let $=H.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&($=$.eq("status",c)),h!=="all"&&($=$.eq("category",h));const{data:X,error:K}=await $;if(K)throw K;return X}}),{data:b=[]}=gt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:$,error:X}=await H.from("user_roles").select("user_id").eq("role","admin");if(X)throw X;const K=$.map(ae=>ae.user_id),{data:Q,error:Y}=await H.from("profiles").select("id, name, email").in("id",K);if(Y)throw Y;const{data:ne,error:de}=await H.from("support_notification_settings").select("user_id, receive_notifications");if(de)throw de;const ce=new Map((ne==null?void 0:ne.map(ae=>[ae.user_id,ae.receive_notifications]))||[]);return Q.map(ae=>({...ae,receives_notifications:ce.get(ae.id)||!1}))}}),{data:N=[]}=gt({queryKey:["admin-ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:$,error:X}=await H.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(X)throw X;return $},enabled:!!r}),S=Lt({mutationFn:async({userId:$,enabled:X})=>{const{data:K}=await H.from("support_notification_settings").select("id").eq("user_id",$).maybeSingle();if(K){const{error:Q}=await H.from("support_notification_settings").update({receive_notifications:X}).eq("user_id",$);if(Q)throw Q}else{const{error:Q}=await H.from("support_notification_settings").insert({user_id:$,receive_notifications:X});if(Q)throw Q}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ue.success("Notification settings updated")},onError:()=>{ue.error("Failed to update settings")}}),T=Lt({mutationFn:async({ticketId:$,status:X})=>{const{error:K}=await H.from("support_tickets").update({status:X}).eq("id",$);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),r&&n({...r,status:r.status}),ue.success("Status updated")},onError:()=>{ue.error("Failed to update status")}}),A=Lt({mutationFn:async({ticketId:$,assignedTo:X})=>{const{error:K}=await H.from("support_tickets").update({assigned_to:X}).eq("id",$);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ue.success("Ticket assigned")},onError:()=>{ue.error("Failed to assign ticket")}}),P=Lt({mutationFn:async({content:$,attachments:X})=>{var Q,Y;if(!r||!s)throw new Error("Missing data");const{error:K}=await H.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:$,is_admin_reply:!0,attachments:X});if(K)throw K;try{await H.functions.invoke("support-reply-notify",{body:{ticketId:r.id,ticketSubject:r.subject,replyContent:$,userEmail:(Q=r.profiles)==null?void 0:Q.email,userName:(Y=r.profiles)==null?void 0:Y.name}})}catch(ne){console.error("Failed to send reply notification:",ne)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",r==null?void 0:r.id]}),i(""),o([]),ue.success("Reply sent!")},onError:()=>{ue.error("Failed to send reply")}}),D=()=>{!a.trim()&&l.length===0||P.mutate({content:a,attachments:l})};k.useEffect(()=>{const $=H.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{H.removeChannel($)}},[t]);const B=v.filter($=>$.status==="open").length;return r?(qU[r.status].icon,e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",children:tqe[r.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((z=r.profiles)==null?void 0:z.name)||"Unknown"," (",(F=r.profiles)==null?void 0:F.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm",children:"Status"})}),e.jsx(De,{children:e.jsxs(zs,{value:r.status,onValueChange:$=>{T.mutate({ticketId:r.id,status:$}),n({...r,status:$})},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"open",children:"Open"}),e.jsx(mt,{value:"in_progress",children:"In Progress"}),e.jsx(mt,{value:"resolved",children:"Resolved"}),e.jsx(mt,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm",children:"Assigned To"})}),e.jsx(De,{children:e.jsxs(zs,{value:r.assigned_to||"unassigned",onValueChange:$=>{const X=$==="unassigned"?null:$;A.mutate({ticketId:r.id,assignedTo:X}),n({...r,assigned_to:X})},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Unassigned"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"unassigned",children:"Unassigned"}),b.map($=>e.jsx(mt,{value:$.id,children:$.name},$.id))]})]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(Nr,{children:["Created on ",Ss(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(ti,{className:"h-[300px] pr-4",children:N.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:N.map($=>{var X,K;return e.jsxs("div",{className:`p-4 rounded-lg ${$.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:$.is_admin_reply?`${((X=$.profiles)==null?void 0:X.name)||"Admin"} (Support)`:((K=$.profiles)==null?void 0:K.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date($.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:$.content}),$.attachments&&$.attachments.length>0&&e.jsx(Glt,{attachments:$.attachments})]},$.id)})})}),e.jsx(po,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ur,{placeholder:"Type your reply...",value:a,onChange:$=>i($.target.value),className:"min-h-[80px]"}),e.jsx(G,{onClick:D,disabled:!a.trim()&&l.length===0||P.isPending,className:"self-end",children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsx(Hlt,{value:l,onChange:o,disabled:P.isPending})]})]})]})]})})):e.jsx(_s,{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",B>0&&e.jsxs(Ge,{variant:"destructive",className:"ml-2",children:[B," open"]})]})]}),e.jsxs(vs,{open:x,onOpenChange:g,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Email Notification Settings"}),e.jsx(Fr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:b.map($=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:$.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:$.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$.receives_notifications?e.jsx(Rm,{className:"h-4 w-4 text-primary"}):e.jsx(Fv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(br,{checked:$.receives_notifications,onCheckedChange:X=>S.mutate({userId:$.id,enabled:X})})]})]},$.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(Rn,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Dn,{children:[e.jsx(Xt,{value:"all",children:"All"}),e.jsx(Xt,{value:"open",children:"Open"}),e.jsx(Xt,{value:"in_progress",children:"In Progress"}),e.jsx(Xt,{value:"resolved",children:"Resolved"}),e.jsx(Xt,{value:"closed",children:"Closed"})]})}),e.jsxs(zs,{value:h,onValueChange:m,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"All Categories"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Categories"}),e.jsx(mt,{value:"general",children:"General Support"}),e.jsx(mt,{value:"technology",children:"Technology Support"}),e.jsx(mt,{value:"crm",children:"CRM Support"}),e.jsx(mt,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:j?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):v.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(tc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:v.map($=>{var K,Q;const X=qU[$.status].icon;return e.jsx(Ne,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n($),children:e.jsx(De,{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:$.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Ge,{variant:"outline",className:"text-xs",children:tqe[$.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(K=$.profiles)==null?void 0:K.name," • ",Ss(new Date($.created_at),"MMM d, yyyy")]}),$.assigned_to&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"}),((Q=b.find(Y=>Y.id===$.assigned_to))==null?void 0:Q.name)||"Assigned"]})]})]}),e.jsxs(Ge,{className:qU[$.status].color,children:[e.jsx(X,{className:"h-3 w-3 mr-1"}),qU[$.status].label]})]})})},$.id)})})})]})]})})}const fmt=hm.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 c4s({content:s,onChange:t,variables:r}){const n=cTe({extensions:[uTe,_Te.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),wTe.configure({types:["heading","paragraph"]}),jTe,fmt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});k.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const a=l=>{n&&n.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!n)return;const l=n.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return n?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBold().run(),className:n.isActive("bold")?"bg-muted":"",children:e.jsx(qj,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleItalic().run(),className:n.isActive("italic")?"bg-muted":"",children:e.jsx(Kj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBulletList().run(),className:n.isActive("bulletList")?"bg-muted":"",children:e.jsx(lm,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleOrderedList().run(),className:n.isActive("orderedList")?"bg-muted":"",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("left").run(),className:n.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(y3,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("center").run(),className:n.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(g3,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("right").run(),className:n.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(v3,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:i,className:n.isActive("link")?"bg-muted":"",children:e.jsx(xo,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleCodeBlock().run(),className:n.isActive("codeBlock")?"bg-muted":"",children:e.jsx(j3,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),children:e.jsx(s2,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),children:e.jsx(e2,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),r.length>0&&e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(gM,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Vd,{align:"end",className:"w-64",children:r.map(l=>e.jsxs(Da,{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(oTe,{editor:n,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),r.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(l=>e.jsx(Ge,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-xs",onClick:()=>{navigator.clipboard.writeText(`{{${l.key}}}`)},children:`{{${l.key}}}`},l.key))})]})]}):null}function d4s(){const s=es(),[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(!0),[g,v]=k.useState("visual"),{data:j,isLoading:b}=gt({queryKey:["email-templates"],queryFn:async()=>{const{data:P,error:D}=await H.from("email_templates").select("*").order("name");if(D)throw D;return P.map(B=>({...B,available_variables:B.available_variables||[]}))}}),N=Lt({mutationFn:async P=>{const{error:D}=await H.from("email_templates").update({subject:P.subject,body_html:P.body_html,description:P.description,is_active:P.is_active}).eq("id",P.id);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ue.success("Email template updated successfully"),r(null)},onError:P=>{ue.error("Failed to update template: "+P.message)}}),S=P=>{r(P),l(P.subject),c(P.body_html),h(P.description||""),x(P.is_active),v("visual")},T=()=>{t&&N.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:m})},A=(P,D)=>{let B=P;return D.forEach(z=>{const F=`{{${z.key}}}`,$=`[${z.label}]`;B=B.replace(new RegExp(F.replace(/[{}]/g,"\\$&"),"g"),$)}),B};return t?e.jsxs(_s,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(G,{variant:"ghost",onClick:()=>r(null),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(G,{variant:"outline",onClick:()=>a(t),children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(G,{onClick:T,disabled:N.isPending,children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),N.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5"}),t.name]}),e.jsxs(Nr,{className:"mt-1",children:["Template slug: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:t.slug})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{htmlFor:"active-toggle",children:"Active"}),e.jsx(br,{id:"active-toggle",checked:m,onCheckedChange:x})]})]})}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",value:d,onChange:P=>h(P.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"subject",children:"Email Subject"}),e.jsx(ke,{id:"subject",value:i,onChange:P=>l(P.target.value),placeholder:"Email subject line"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["You can use variables like ","{{name}}"," in the subject"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Email Body"}),e.jsx(Rn,{value:g,onValueChange:P=>v(P),children:e.jsxs(Dn,{className:"h-8",children:[e.jsxs(Xt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(Zj,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Xt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(j3,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),g==="visual"?e.jsx(c4s,{content:o,onChange:c,variables:t.available_variables}):e.jsx(ur,{value:o,onChange:P=>c(P.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(js,{children:[e.jsx(bs,{children:"Email Preview"}),e.jsxs(Fr,{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(_s,{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((P,D)=>e.jsx(Ne,{children:e.jsxs(Ot,{children:[e.jsx(Vs,{className:"h-5 w-48"}),e.jsx(Vs,{className:"h-4 w-96"})]})},D))}):e.jsx("div",{className:"grid gap-4",children:j==null?void 0:j.map(P=>e.jsxs(Ne,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(zt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Qs,{className:"h-5 w-5 text-muted-foreground"}),P.name,!P.is_active&&e.jsx(Ge,{variant:"secondary",children:"Inactive"})]}),e.jsx(Nr,{children:P.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>a(P),children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(G,{size:"sm",onClick:()=>S(P),children:[e.jsx(nd,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(De,{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:P.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:P.available_variables.map(D=>e.jsx(Ge,{variant:"outline",className:"font-mono text-xs",children:`{{${D.key}}}`},D.key))})]})]})})]},P.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(js,{children:[e.jsxs(bs,{children:["Email Preview: ",n==null?void 0:n.name]}),e.jsxs(Fr,{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 u4s(){const s=es(),[t,r]=k.useState("templates"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[g,v]=k.useState({name:"",description:"",icon:"📧"}),{data:j=[]}=gt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:$,error:X}=await H.from("email_template_categories").select("*").order("sort_order");if(X)throw X;return $}}),{data:b=[],isLoading:N}=gt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:$,error:X}=await H.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(X)throw X;return $}}),S=Lt({mutationFn:async $=>{const X={title:$.title,subject:$.subject,body:$.body,description:$.description||null,tone:$.tone||null,category_id:$.category_id||null,is_active:$.is_active};if($.id){const{error:K}=await H.from("agent_email_templates").update(X).eq("id",$.id);if(K)throw K}else{const{error:K}=await H.from("agent_email_templates").insert(X);if(K)throw K}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ue.success(n?"Template updated":"Template created")},onError:()=>ue.error("Failed to save template")}),T=Lt({mutationFn:async $=>{const{error:X}=await H.from("agent_email_templates").delete().eq("id",$);if(X)throw X},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ue.success("Template deleted")}}),A=Lt({mutationFn:async $=>{const X={name:$.name,description:$.description||null,icon:$.icon};if($.id){const{error:K}=await H.from("email_template_categories").update(X).eq("id",$.id);if(K)throw K}else{const K=j.length>0?Math.max(...j.map(Y=>Y.sort_order))+1:0,{error:Q}=await H.from("email_template_categories").insert({...X,sort_order:K});if(Q)throw Q}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),h(!1),ue.success(i?"Category updated":"Category created")},onError:()=>ue.error("Failed to save category")}),P=Lt({mutationFn:async $=>{const{error:X}=await H.from("email_template_categories").delete().eq("id",$);if(X)throw X},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ue.success("Category deleted")}}),D=()=>{a(null),x({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},B=$=>{a($),x({title:$.title,subject:$.subject,body:$.body,description:$.description||"",tone:$.tone||"",category_id:$.category_id||"",is_active:$.is_active}),c(!0)},z=()=>{l(null),v({name:"",description:"",icon:"📧"}),h(!0)},F=$=>{l($),v({name:$.name,description:$.description||"",icon:$.icon}),h(!0)};return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(rh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(Rn,{value:t,onValueChange:r,children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"templates",className:"gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Xt,{value:"categories",className:"gap-2",children:[e.jsx(im,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(as,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:D,className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Template"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:N?e.jsx(qs,{children:e.jsx(ft,{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(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):b.map($=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:$.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:$.subject})]})}),e.jsx(ft,{className:"hidden md:table-cell",children:$.category?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[$.category.icon," ",$.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ft,{className:"hidden md:table-cell",children:$.tone?e.jsx(Ge,{variant:"secondary",children:$.tone}):"—"}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.is_active?"default":"secondary",children:$.is_active?"Active":"Inactive"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>B($),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&T.mutate($.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},$.id))})]})})})]}),e.jsxs(as,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:z,className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:j.map($=>e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:$.icon})," ",$.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F($),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&P.mutate($.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:$.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[b.filter(X=>X.category_id===$.id).length," templates"]})]})]},$.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(js,{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(he,{children:"Title"}),e.jsx(ke,{value:m.title,onChange:$=>x(X=>({...X,title:$.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Category"}),e.jsxs(zs,{value:m.category_id,onValueChange:$=>x(X=>({...X,category_id:$})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:j.map($=>e.jsxs(mt,{value:$.id,children:[$.icon," ",$.name]},$.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Subject Line"}),e.jsx(ke,{value:m.subject,onChange:$=>x(X=>({...X,subject:$.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Email Body"}),e.jsx(ur,{value:m.body,onChange:$=>x(X=>({...X,body:$.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Description (internal)"}),e.jsx(ke,{value:m.description,onChange:$=>x(X=>({...X,description:$.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Tone"}),e.jsx(ke,{value:m.tone,onChange:$=>x(X=>({...X,tone:$.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{checked:m.is_active,onCheckedChange:$=>x(X=>({...X,is_active:$}))}),e.jsx(he,{children:"Active"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>S.mutate({...m,id:n==null?void 0:n.id}),disabled:S.isPending||!m.title||!m.subject||!m.body,children:[S.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Save Changes":"Create Template"]})]})]})}),e.jsx(vs,{open:d,onOpenChange:h,children:e.jsxs(ys,{className:"sm:max-w-[450px]",children:[e.jsx(js,{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(he,{children:"Icon"}),e.jsx(ke,{value:g.icon,onChange:$=>v(X=>({...X,icon:$.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Name"}),e.jsx(ke,{value:g.name,onChange:$=>v(X=>({...X,name:$.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Description"}),e.jsx(ke,{value:g.description,onChange:$=>v(X=>({...X,description:$.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>A.mutate({...g,id:i==null?void 0:i.id}),disabled:A.isPending||!g.name,children:[A.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const h4s=({brokerageId:s})=>{var Fe,We;const{toast:t}=Ea(),r=vr(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[g,v]=k.useState(!1),[j,b]=k.useState({}),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[P,D]=k.useState({email:"",name:"",password:"",phone:""}),[B,z]=k.useState(!1),[F,$]=k.useState(null),[X,K]=k.useState(!1),[Q,Y]=k.useState(!1),[ne,de]=k.useState(!1),[ce,ae]=k.useState(""),[ie,me]=k.useState(!1),[oe,ge]=k.useState([]),[be,Oe]=k.useState(!1),[Me,Pe]=k.useState(!1),[Ee,$e]=k.useState(null),[Se,ze]=k.useState({name:"",phone:"",email:""}),[Te,ye]=k.useState(!1),[ct,ve]=k.useState(!1),[rt,Re]=k.useState(null),[Qe,Ke]=k.useState("asc"),[Ce,nt]=k.useState(!1),[$t,lt]=k.useState(null),[it,Nt]=k.useState(!1),[Ft,at]=k.useState(null),[Ie,et]=k.useState(""),[Dt,Jt]=k.useState(!1),[cs,Ht]=k.useState(null);k.useEffect(()=>{Qt(),dt()},[s]);const dt=async()=>{try{const{data:He,error:bt}=await H.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(bt)throw bt;ge((He==null?void 0:He.map(ut=>ut.user_id))||[])}catch(He){console.error("Error loading brokerage managers:",He)}},Qt=async()=>{try{l(!0);const{data:He,error:bt}=await H.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(bt)throw bt;const ut=He.agents||[];if(a(ut),ut.length>0){const kt=ut.map(Mt=>Mt.id),{data:Gt}=await H.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",kt);if(Gt&&Gt.length>0){const Mt=Gt.map(Ls=>Ls.assistant_id),{data:Kt}=await H.from("profiles").select("id, name, email").in("id",Mt),Es={};for(const Ls of Gt){const gr=Kt==null?void 0:Kt.find(qr=>qr.id===Ls.assistant_id);gr&&(Es[Ls.agent_id]={name:gr.name||"",email:gr.email||""})}b(Es)}else b({})}}catch(He){console.error("Error loading agents:",He),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},yt=async()=>{if(!P.email||!P.name||!P.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:He}}=await H.auth.getSession(),bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({...P,brokerageId:s})}),ut=await bt.json();if(!bt.ok)throw new Error(ut.error||"Failed to create agent");t({title:"Success",description:`Agent ${P.email} created successfully`}),D({email:"",name:"",password:"",phone:""}),S(!1),Qt()}catch(He){console.error("Error creating agent:",He),t({title:"Error",description:He.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},ss=async He=>{try{const{data:{session:bt}}=await H.auth.getSession(),ut=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bt==null?void 0:bt.access_token}`},body:JSON.stringify({userId:He})}),kt=await ut.json();if(!ut.ok)throw new Error(kt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(bt){console.error("Error resending welcome email:",bt),t({title:"Error",description:bt.message||"Failed to resend welcome email",variant:"destructive"})}},Is=async(He,bt)=>{try{const{error:ut}=await H.functions.invoke("send-password-reset",{body:{email:He,redirectTo:window.location.origin}});if(ut)throw ut;t({title:"Password Reset Sent",description:`Password reset email sent to ${bt}`})}catch(ut){console.error("Error sending password reset:",ut),t({title:"Error",description:ut.message||"Failed to send password reset email",variant:"destructive"})}},fs=He=>{$(He),z(!0)},ar=He=>{$e(He),ze({name:He.name,phone:He.phone||"",email:He.email}),Pe(!0)},Er=async()=>{if(!Ee)return;if(!Se.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const He=Se.email.trim().toLowerCase()!==Ee.email.toLowerCase();ye(!0);try{if(He){if(!Se.email.trim())throw new Error("Email is required");ve(!0);const{data:{session:ut}}=await H.auth.getSession(),kt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ut==null?void 0:ut.access_token}`},body:JSON.stringify({agentId:Ee.id,newEmail:Se.email.trim(),brokerageId:s})}),Gt=await kt.json();if(ve(!1),!kt.ok)throw new Error(Gt.error||"Failed to update email")}const{error:bt}=await H.from("profiles").update({name:Se.name.trim(),phone:Se.phone.trim()||null}).eq("id",Ee.id);if(bt)throw bt;t({title:"Success",description:"Agent profile updated successfully"}),Pe(!1),$e(null),Qt()}catch(bt){console.error("Error updating agent:",bt),t({title:"Error",description:bt.message||"Failed to update agent",variant:"destructive"})}finally{ye(!1),ve(!1)}},Tr=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}me(!0);try{const{data:{session:He}}=await H.auth.getSession(),bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),ut=await bt.json();if(!bt.ok)throw new Error(ut.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),de(!1),ae(""),dt()}catch(He){console.error("Error adding brokerage manager:",He),t({title:"Error",description:He.message||"Failed to add brokerage manager",variant:"destructive"})}finally{me(!1)}},Lr=async He=>{try{const{data:{session:bt}}=await H.auth.getSession(),ut=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bt==null?void 0:bt.access_token}`},body:JSON.stringify({userId:He,role:"brokerage_manager",action:"remove",brokerageId:s})}),kt=await ut.json();if(!ut.ok)throw new Error(kt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),dt()}catch(bt){console.error("Error removing brokerage manager:",bt),t({title:"Error",description:bt.message||"Failed to remove brokerage manager",variant:"destructive"})}},$r=He=>oe.includes(He),kr=He=>{at(He),et(""),Nt(!0)},Sr=async()=>{if(!(!Ft||!Ie)){if(Ie.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Jt(!0);try{const{data:{session:He}}=await H.auth.getSession(),bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({agentId:Ft.id,brokerageId:s,action:"set_password",newPassword:Ie})}),ut=await bt.json();if(!bt.ok)throw new Error(ut.error||"Failed to set password");t({title:"Success",description:`Password set for ${Ft.name}`}),Nt(!1),at(null),et("")}catch(He){console.error("Error setting password:",He),t({title:"Error",description:He.message||"Failed to set password",variant:"destructive"})}finally{Jt(!1)}}},hn=async He=>{Ht(He.id);try{const{data:{session:bt}}=await H.auth.getSession(),ut=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bt==null?void 0:bt.access_token}`},body:JSON.stringify({agentId:He.id,brokerageId:s,action:"claim_account"})}),kt=await ut.json();if(!ut.ok)throw new Error(kt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${He.name}`}),Qt()}catch(bt){console.error("Error claiming account:",bt),t({title:"Error",description:bt.message||"Failed to claim account",variant:"destructive"})}finally{Ht(null)}},zn=async()=>{if(F){K(!0);try{const{data:{session:He}}=await H.auth.getSession(),bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${He==null?void 0:He.access_token}`},body:JSON.stringify({userId:F.id,brokerageId:s})}),ut=await bt.json();if(!bt.ok)throw new Error(ut.error||"Failed to remove agent");t({title:"Success",description:`${F.name} has been removed from your brokerage`}),z(!1),$(null),Qt()}catch(He){console.error("Error removing agent:",He),t({title:"Error",description:He.message||"Failed to remove agent",variant:"destructive"})}finally{K(!1)}}},Xs=He=>{const bt=He.trim().split(" ");return bt.length>1?bt[bt.length-1].toLowerCase():He.toLowerCase()},Ur=He=>{rt===He?Ke(Qe==="asc"?"desc":"asc"):(Re(He),Ke("asc"))},xn=He=>rt!==He?e.jsx(Rd,{className:"ml-1 h-4 w-4"}):Qe==="asc"?e.jsx(Fd,{className:"ml-1 h-4 w-4"}):e.jsx(Ku,{className:"ml-1 h-4 w-4"}),us=n.filter(He=>{if(d==="active"&&!He.claimed||d==="pending"&&He.claimed)return!1;if(!o)return!0;const bt=o.toLowerCase();return He.name.toLowerCase().includes(bt)||He.email.toLowerCase().includes(bt)}),pr=[...us].sort((He,bt)=>{if(!rt)return 0;let ut=0;return rt==="name"?ut=Xs(He.name).localeCompare(Xs(bt.name)):rt==="status"&&(ut=He.claimed===bt.claimed?0:He.claimed?-1:1),Qe==="asc"?ut:-ut});us.filter(He=>He.claimed&&!$r(He.id));const Hr=He=>{x(bt=>{const ut=new Set(bt);return ut.has(He)?ut.delete(He):ut.add(He),ut})},aa=()=>{m.size===pr.length?x(new Set):x(new Set(pr.map(He=>He.id)))},Na=()=>{x(new Set)},Je=async()=>{const He=Array.from(m);if(He.length===0)return;v(!0);let bt=0,ut=0;try{const{data:{session:kt}}=await H.auth.getSession();for(const Gt of He)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify({userId:Gt})})).ok?bt++:ut++}catch{ut++}bt>0?t({title:"Success",description:`Welcome emails sent to ${bt} agent${bt>1?"s":""}${ut>0?` (${ut} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Na()}catch(kt){console.error("Error bulk sending welcome emails:",kt),t({title:"Error",description:kt.message||"Failed to send welcome emails",variant:"destructive"})}finally{v(!1)}};return i?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Agents"}),e.jsx(Nr,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>de(!0),children:[e.jsx(Zu,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(G,{variant:"outline",onClick:()=>Y(!0),children:[e.jsx(Jb,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(G,{onClick:()=>S(!0),children:[e.jsx(nl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(De,{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(fn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents...",value:o,onChange:He=>c(He.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:d,onValueChange:He=>h(He),children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Agents"}),e.jsx(mt,{value:"active",children:"Active"}),e.jsx(mt,{value:"pending",children:"Pending"})]})]})]}),m.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[m.size," agent",m.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{const bt=n.filter(ut=>m.has(ut.id)&&ut.email).map(ut=>({email:ut.email,name:ut.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(bt)),r("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:bt}})},disabled:g,children:[e.jsx(Cu,{className:"mr-2 h-4 w-4"}),"Email Agents (",m.size,")"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:Je,disabled:g,children:[e.jsx(Qs,{className:"mr-2 h-4 w-4"}),g?"Sending...":"Resend Welcome Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:Na,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(Ei,{checked:pr.length>0&&m.size===pr.length,onCheckedChange:aa,"aria-label":"Select all"})}),e.jsx(Tt,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Ur("name"),children:["Name (Last)",xn("name")]})}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Ur("status"),children:["Status",xn("status")]})}),e.jsx(Tt,{children:"Actions"})]})}),e.jsx(Bn,{children:pr.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):pr.map(He=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx(Ei,{checked:m.has(He.id),onCheckedChange:()=>Hr(He.id),"aria-label":`Select ${He.name}`})}),e.jsx(ft,{className:"font-medium",children:He.name}),e.jsx(ft,{children:He.email}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[He.claimed?e.jsx(Ge,{variant:"default",children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Pending"}),$r(He.id)&&e.jsxs(Ge,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(a0,{className:"mr-1 h-3 w-3"}),"Manager"]}),j[He.id]&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:[e.jsx(fr,{className:"mr-1 h-3 w-3"}),"Asst: ",j[He.id].name||j[He.id].email]})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{lt(He),nt(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(iu,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>ar(He),title:"Edit agent",children:e.jsx(Ta,{className:"h-4 w-4"})}),!He.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>ss(He.id),title:"Resend welcome email",children:e.jsx(Qs,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>hn(He),title:"Claim account for agent",disabled:cs===He.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(Yv,{className:"h-4 w-4"})})]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>kr(He),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Kc,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>Is(He.email,He.name),title:"Send password reset email",children:e.jsx(E3,{className:"h-4 w-4"})}),$r(He.id)&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>Lr(He.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Zu,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>fs(He),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},He.id))})]})})]})]}),e.jsx(vs,{open:N,onOpenChange:S,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add New Agent"}),e.jsx(Fr,{children:"Create a new agent account. They'll receive an email to set up their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",value:P.name,onChange:He=>D({...P,name:He.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{id:"email",type:"email",value:P.email,onChange:He=>D({...P,email:He.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ke,{id:"phone",type:"tel",value:P.phone,onChange:He=>D({...P,phone:He.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"password",children:"Temporary Password"}),e.jsx(ke,{id:"password",type:"password",value:P.password,onChange:He=>D({...P,password:He.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(G,{onClick:yt,disabled:T,children:T?"Creating...":"Create Agent"})]})]})}),e.jsx(vs,{open:B,onOpenChange:z,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Remove Agent"}),e.jsxs(Fr,{children:["Are you sure you want to remove ",e.jsx("strong",{children:F==null?void 0:F.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>z(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:zn,disabled:X,children:X?"Removing...":"Remove Agent"})]})]})}),e.jsx(Wlt,{open:Q,onOpenChange:Y,fixedBrokerageId:s,onSuccess:Qt}),e.jsx(vs,{open:ne,onOpenChange:de,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add Brokerage Manager"}),e.jsx(Fr,{children:"Promote an existing active agent to brokerage manager. They will be able to manage agents and view analytics."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{children:[e.jsx(he,{children:"Select Agent"}),e.jsxs(Ao,{open:be,onOpenChange:Oe,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":be,className:"w-full justify-between",children:[ce?((Fe=n.find(He=>He.id===ce))==null?void 0:Fe.name)+" ("+((We=n.find(He=>He.id===ce))==null?void 0:We.email)+")":"Select an agent to promote...",e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-full p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search by name or email..."}),e.jsxs(Lx,{className:"max-h-[200px]",children:[e.jsx(Dx,{children:"No eligible agents found."}),e.jsx(Rx,{children:n.filter(He=>!$r(He.id)).map(He=>e.jsxs(vf,{value:`${He.name} ${He.email}`,onSelect:()=>{ae(He.id),Oe(!1)},children:[e.jsx(Hn,{className:`mr-2 h-4 w-4 ${ce===He.id?"opacity-100":"opacity-0"}`}),He.name," (",He.email,")"]},He.id))})]})]})})]}),n.filter(He=>!$r(He.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(G,{onClick:Tr,disabled:ie||!ce,children:ie?"Adding...":"Add as Manager"})]})]})}),e.jsx(vs,{open:Me,onOpenChange:Pe,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Agent"}),e.jsxs(Fr,{children:["Update profile information for ",Ee==null?void 0:Ee.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"edit-name",children:"Name"}),e.jsx(ke,{id:"edit-name",value:Se.name,onChange:He=>ze({...Se,name:He.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"edit-email",children:"Email"}),e.jsx(ke,{id:"edit-email",type:"email",value:Se.email,onChange:He=>ze({...Se,email:He.target.value}),placeholder:"agent@example.com"}),Se.email.trim().toLowerCase()!==(Ee==null?void 0:Ee.email.toLowerCase())&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Changing email will update their login credentials"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ke,{id:"edit-phone",type:"tel",value:Se.phone,onChange:He=>ze({...Se,phone:He.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>Pe(!1),children:"Cancel"}),e.jsx(G,{onClick:Er,disabled:Te||ct,children:ct?"Updating email...":Te?"Saving...":"Save Changes"})]})]})}),$t&&e.jsx(Klt,{open:Ce,onOpenChange:He=>{nt(He),He||lt(null)},userId:$t.id,userName:$t.name}),e.jsx(vs,{open:it,onOpenChange:Nt,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Set Password"}),e.jsxs(Fr,{children:["Set a new password for ",Ft==null?void 0:Ft.name,". They will be able to log in with this password immediately."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"new-password",children:"New Password"}),e.jsx(ke,{id:"new-password",type:"password",value:Ie,onChange:He=>et(He.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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>Nt(!1),children:"Cancel"}),e.jsx(G,{onClick:Sr,disabled:Dt||!Ie||Ie.length<6,children:Dt?"Setting...":"Set Password"})]})]})})]})},m4s={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},f4s={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},p4s=s=>{switch(s){case"academy_video":return e.jsx(sn,{className:"h-4 w-4"});case"template":return e.jsx(ln,{className:"h-4 w-4"});case"toolbox":return e.jsx(ln,{className:"h-4 w-4"});case"newsletter":return e.jsx(Vv,{className:"h-4 w-4"});case"social_swag":return e.jsx(jr,{className:"h-4 w-4"});case"event":return e.jsx(rn,{className:"h-4 w-4"});default:return e.jsx(Yr,{className:"h-4 w-4"})}},x4s=({brokerageId:s})=>{const{toast:t}=Ea(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState([]),[c,d]=k.useState(!0),[h,m]=k.useState(null);k.useEffect(()=>{x()},[s]);const x=async()=>{try{d(!0);const{data:j,error:b}=await H.from("profiles").select("id, name, email").eq("brokerage_id",s);if(b)throw b;const N=j.map(X=>X.id),S=new Map(j.map(X=>[X.id,X]));if(N.length===0){n([]),i([]),o([]);return}const{data:T,error:A}=await H.from("activity_logs").select("*").in("user_id",N).order("launched_at",{ascending:!1});if(A)throw A;const P=T.map(X=>{var K,Q;return{id:X.id,user_id:X.user_id,app_name:X.app_name,launched_at:X.launched_at,user_name:((K=S.get(X.user_id))==null?void 0:K.name)||"Unknown",user_email:((Q=S.get(X.user_id))==null?void 0:Q.email)||"Unknown"}});n(P);const{data:D,error:B}=await H.from("content_engagement_logs").select("*").in("user_id",N).order("created_at",{ascending:!1});if(B)throw B;const z=(D||[]).map(X=>{var K,Q;return{id:X.id,user_id:X.user_id,resource_type:X.resource_type,resource_id:X.resource_id,resource_title:X.resource_title,action_type:X.action_type,created_at:X.created_at,user_name:((K=S.get(X.user_id))==null?void 0:K.name)||"Unknown",user_email:((Q=S.get(X.user_id))==null?void 0:Q.email)||"Unknown"}});i(z);const F=new Map;j.forEach(X=>{F.set(X.id,{user_id:X.id,user_name:X.name,user_email:X.email,app_launches:0,content_views:0,last_activity:""})}),P.forEach(X=>{const K=F.get(X.user_id);K&&(K.app_launches++,(!K.last_activity||new Date(X.launched_at)>new Date(K.last_activity))&&(K.last_activity=X.launched_at))}),z.forEach(X=>{const K=F.get(X.user_id);K&&(K.content_views++,(!K.last_activity||new Date(X.created_at)>new Date(K.last_activity))&&(K.last_activity=X.created_at))});const $=Array.from(F.values()).filter(X=>X.app_launches>0||X.content_views>0).sort((X,K)=>new Date(K.last_activity).getTime()-new Date(X.last_activity).getTime());o($)}catch(j){console.error("Error loading activity:",j),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},g=j=>r.filter(b=>b.user_id===j),v=j=>a.filter(b=>b.user_id===j);return c?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agent Activity"}),e.jsx(Nr,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(De,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"App Launches"}),e.jsx(Tt,{className:"text-center",children:"Content Views"}),e.jsx(Tt,{children:"Last Active"})]})}),e.jsx(Bn,{children:l.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(j=>e.jsxs(qs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>m({id:j.user_id,name:j.user_name,email:j.user_email}),children:[e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:j.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:j.user_email})]})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"}),j.app_launches]})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),j.content_views]})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:j.last_activity&&al(new Date(j.last_activity),{addSuffix:!0})})]},j.user_id))})]})})})]}),e.jsx(vs,{open:!!h,onOpenChange:j=>!j&&m(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Fr,{children:h==null?void 0:h.email})]}),e.jsxs(Rn,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"content",children:"Content Engagement"}),e.jsx(Xt,{value:"apps",children:"App Launches"})]}),e.jsx(as,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Bn,{children:h&&v(h.id).length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):h&&v(h.id).map(j=>e.jsxs(qs,{children:[e.jsx(ft,{className:"max-w-[200px] truncate font-medium",children:j.resource_title}),e.jsx(ft,{children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[p4s(j.resource_type),m4s[j.resource_type]||j.resource_type]})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:f4s[j.action_type]||j.action_type})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:al(new Date(j.created_at),{addSuffix:!0})})]},j.id))})]})})}),e.jsx(as,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Bn,{children:h&&g(h.id).length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):h&&g(h.id).map(j=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",children:j.app_name})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:al(new Date(j.launched_at),{addSuffix:!0})})]},j.id))})]})})})]})]})})]})},g4s=({brokerageId:s})=>{const{toast:t}=Ea(),[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 H.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(P=>P.id),h=d.length;if(d.length===0){i(!1);return}const{data:m,error:x}=await H.from("profiles").select("id, email").in("id",d);if(x)throw x;const{count:g}=await H.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),v=g||0,j=h-v,{count:b}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),N=new Date;N.setDate(N.getDate()-7);const{count:S}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",N.toISOString()),T=new Date;T.setMonth(T.getMonth()-1);const{count:A}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",T.toISOString());n({totalAgents:h,activeAgents:v,pendingAgents:j,totalLaunches:b||0,launchesThisWeek:S||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(mi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(cn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(Ch,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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"})]})]})]})},y4s=({brokerageId:s})=>{const[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({description:"",maxUses:""});k.useEffect(()=>{m()},[s]);const m=async()=>{try{const{data:N,error:S}=await H.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(S)throw S;r(N||[])}catch(N){console.error("Error loading invite codes:",N),ue.error("Failed to load invite links")}finally{a(!1)}},x=()=>Math.random().toString(36).substring(2,8).toUpperCase(),g=async()=>{l(!0);try{const N=x(),{error:S}=await H.from("invite_codes").insert({code:N,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(S)throw S;ue.success("Invite link created!"),c(!1),h({description:"",maxUses:""}),m()}catch(N){console.error("Error creating invite code:",N),ue.error("Failed to create invite link")}finally{l(!1)}},v=async N=>{try{const{error:S}=await H.from("invite_codes").delete().eq("id",N);if(S)throw S;ue.success("Invite link deleted"),r(t.filter(T=>T.id!==N))}catch(S){console.error("Error deleting invite code:",S),ue.error("Failed to delete invite link")}},j=async(N,S)=>{try{const{error:T}=await H.from("invite_codes").update({is_active:!S}).eq("id",N);if(T)throw T;r(t.map(A=>A.id===N?{...A,is_active:!S}:A)),ue.success(`Invite link ${S?"deactivated":"activated"}`)}catch(T){console.error("Error toggling invite code:",T),ue.error("Failed to update invite link")}},b=N=>{const S=`${window.location.origin}/join?code=${N}`;navigator.clipboard.writeText(S),ue.success("Link copied to clipboard!")};return n?e.jsx(Ne,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Nr,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Create Invite Link"}),e.jsx(Fr,{children:"Create a new invite link for agents to join your brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ke,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:N=>h({...d,description:N.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(ke,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:N=>h({...d,maxUses:N.target.value})})]}),e.jsx(G,{onClick:g,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(De,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(xo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(N=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:N.code}),e.jsx(Ge,{variant:N.is_active?"default":"secondary",children:N.is_active?"Active":"Inactive"})]}),N.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:N.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[N.uses_count," uses",N.max_uses&&` / ${N.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.code),title:"Copy link",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>j(N.id,N.is_active),title:N.is_active?"Deactivate":"Activate",children:N.is_active?"Disable":"Enable"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>v(N.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},N.id))})})]})},v4s=({open:s,onOpenChange:t,referralCode:r,brokerageId:n,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=k.useState(""),[d,h]=k.useState([]),[m,x]=k.useState(""),[g,v]=k.useState(!1),j=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),b=()=>{const A=o.trim().toLowerCase();if(A&&j(A)&&!d.includes(A)){if(d.length>=10){ue.error("Maximum 10 emails per invite");return}h([...d,A]),c("")}else A&&!j(A)?ue.error("Please enter a valid email address"):d.includes(A)&&ue.error("Email already added")},N=A=>{h(d.filter(P=>P!==A))},S=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),b())},T=async()=>{if(d.length===0){ue.error("Please add at least one email address");return}v(!0);try{const{data:A,error:P}=await H.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:m.trim()||void 0,referralCode:r,brokerageId:n,senderName:a,brokerageName:i}});if(P)throw P;A.successCount===A.totalCount?ue.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ue.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),h([]),x(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ue.error("Failed to send invites. Please try again.")}finally{v(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[550px]",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Fr,{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(li,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:"Earn $25/month for each referral!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When they sign up and stay for 30 days, you save on your membership forever."})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:S,onBlur:b}),e.jsx(G,{type:"button",variant:"secondary",onClick:b,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(Ge,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>N(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(_r,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(ur,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:m,onChange:A=>x(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[m.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:d.length===0||g,children:g?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(Zr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},b4s=({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 H.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;n(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Ge,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(mi,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Ge,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Mc,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{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(Qs,{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 ",Ss(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},_4s=()=>{const{brokerageId:s,user:t}=As(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState([]),[h,m]=k.useState(!0),[x,g]=k.useState(!1),[v,j]=k.useState(0);k.useEffect(()=>{s&&b()},[s]);const b=async()=>{try{const[D,B]=await Promise.all([H.from("brokerages").select("name").eq("id",s).single(),t?H.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);D.data&&i(D.data.name),B.data&&o(B.data.name||"A LevelUp Member");const{data:z}=await H.from("referral_codes").select("code").eq("brokerage_id",s).single();if(z)n(z.code);else{const $=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await H.from("referral_codes").insert({brokerage_id:s,code:$}),n($)}const{data:F}=await H.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(F||[])}catch(D){console.error("Error fetching referral data:",D)}finally{m(!1)}},N=()=>{const D=`https://dashboard.relevelup.com/?ref=${r}`;navigator.clipboard.writeText(D),ue.success("Referral link copied to clipboard!")},S=c.filter(D=>D.status==="qualified").length,T=c.filter(D=>D.status==="pending").length,A=S*25,P=Math.max(0,Math.ceil((299-A)/25));return h?null:e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{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(li,{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(mi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),P>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",P," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),A>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(jr,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(De,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(G,{onClick:()=>g(!0),className:"w-full",size:"lg",children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(G,{onClick:N,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",r]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(_l,{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(fr,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:S}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(cn,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:T}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Pending (30 days)"})]})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-sm mb-3",children:"How It Works"}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"1"}),e.jsx("p",{children:"Share your referral link or send an invite email to broker friends"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"2"}),e.jsx("p",{children:"They sign up and subscribe to LevelUp"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"3"}),e.jsx("p",{children:"After 30 days, you get $25/month off your membership - forever!"})]})]})]}),e.jsx(b4s,{brokerageId:s,refreshTrigger:v}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(D=>{var B,z;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:((B=D.referred_brokerage)==null?void 0:B.name)||((z=D.referred_user)==null?void 0:z.email)||"Pending setup"}),e.jsxs(Ge,{variant:D.status==="qualified"?"default":D.status==="pending"?"secondary":"destructive",className:D.status==="qualified"?"bg-green-600":"",children:[D.status==="qualified"&&e.jsx(mi,{className:"h-3 w-3 mr-1"}),D.status]})]},D.id)})]})]})]}),e.jsx(v4s,{open:x,onOpenChange:g,referralCode:r||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>j(D=>D+1)})]})},w4s=({brokerageId:s})=>{const t=vr(),{teams:r,isLoading:n}=Z5(s),{data:a,isLoading:i}=gt({queryKey:["team-aggregate-stats",s,r.map(h=>h.id)],queryFn:async()=>{if(r.length===0)return[];const h=r.map(D=>D.id),{data:m}=await H.from("team_members").select("team_id, user_id, role").in("team_id",h);if(!m||m.length===0)return r.map(D=>({team_id:D.id,team_name:D.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const x=m.map(D=>D.user_id),g=m.filter(D=>D.role==="team_leader").map(D=>D.user_id),{data:v}=await H.from("profiles").select("id, name, avatar_url").in("id",g),j=new Map((v||[]).map(D=>[D.id,D])),{data:b}=await H.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",x),{data:N}=await H.from("deal_pipeline").select("owner_user_id").in("owner_user_id",x),{data:S}=await H.from("agent_videos").select("owner_user_id").in("owner_user_id",x).eq("is_deleted",!1),T=new Map;(b||[]).forEach(D=>{T.set(D.owner_user_id,(T.get(D.owner_user_id)||0)+1)});const A=new Map;(N||[]).forEach(D=>{A.set(D.owner_user_id,(A.get(D.owner_user_id)||0)+1)});const P=new Map;return(S||[]).forEach(D=>{P.set(D.owner_user_id,(P.get(D.owner_user_id)||0)+1)}),r.map(D=>{const B=m.filter(Y=>Y.team_id===D.id),z=B.find(Y=>Y.role==="team_leader"),F=z?j.get(z.user_id):null,$=B.map(Y=>Y.user_id),X=$.reduce((Y,ne)=>Y+(T.get(ne)||0),0),K=$.reduce((Y,ne)=>Y+(A.get(ne)||0),0),Q=$.reduce((Y,ne)=>Y+(P.get(ne)||0),0);return{team_id:D.id,team_name:D.name,member_count:B.length,leader_name:(F==null?void 0:F.name)||null,leader_avatar:(F==null?void 0:F.avatar_url)||null,total_contacts:X,total_deals:K,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(h=>e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(Vs,{className:"h-5 w-32"})}),e.jsx(De,{children:e.jsx(Vs,{className:"h-24 w-full"})})]},h))});if(r.length===0)return e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(G,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((h,m)=>h+m.member_count,0),c=(a||[]).reduce((h,m)=>h+m.total_contacts,0),d=(a||[]).reduce((h,m)=>h+m.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(fr,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:r.length})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(fr,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(k3,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Yu,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(h=>e.jsxs(Ne,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-lg",children:h.team_name}),e.jsxs(Ge,{variant:"secondary",children:[h.member_count," members"]})]}),h.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:h.leader_avatar||""}),e.jsx(bn,{className:"text-xs",children:h.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(nm,{className:"h-3 w-3 text-amber-500"}),h.leader_name]})]})]}),e.jsx(De,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:h.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},h.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},j4s=()=>{const{user:s,isBrokerageManager:t,brokerageId:r,isAdmin:n,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=As(),o=vr(),{toast:c}=Ea(),[d,h]=k.useState(""),[m,x]=k.useState(!0),g=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),g?v():a.length===0&&!r&&x(!1)},[s,t,n,g,o,a,i]);const v=async()=>{if(!g){x(!1);return}try{const{data:j,error:b}=await H.from("brokerages").select("name").eq("id",g).single();if(b)throw b;h(j.name)}catch(j){console.error("Error loading brokerage info:",j),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{x(!1)}};return m?e.jsx(_s,{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"})})}):g?e.jsx(_s,{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(zs,{value:i||"",onValueChange:l,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:a.map(j=>e.jsx(mt,{value:j.id,children:j.name},j.id))})]})]}),e.jsxs(Rn,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Xt,{value:"agents",children:"Agents"}),e.jsx(Xt,{value:"teams",children:"Teams"}),e.jsx(Xt,{value:"invite",children:"Invite Links"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Xt,{value:"activity",children:"Activity"}),e.jsx(Xt,{value:"analytics",children:"Analytics"}),e.jsx(Xt,{value:"shares",children:"Shares"})]}),e.jsx(as,{value:"agents",className:"space-y-4",children:e.jsx(h4s,{brokerageId:g})}),e.jsx(as,{value:"teams",className:"space-y-4",children:e.jsx(w4s,{brokerageId:g})}),e.jsx(as,{value:"invite",className:"space-y-4",children:e.jsx(y4s,{brokerageId:g})}),e.jsx(as,{value:"referrals",className:"space-y-4",children:e.jsx(_4s,{})}),e.jsx(as,{value:"leaderboard",className:"space-y-4",children:e.jsx(dlt,{brokerageId:g,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(as,{value:"activity",className:"space-y-4",children:e.jsx(x4s,{brokerageId:g})}),e.jsx(as,{value:"analytics",className:"space-y-4",children:e.jsx(g4s,{brokerageId:g})}),e.jsx(as,{value:"shares",className:"space-y-4",children:e.jsx(Nct,{brokerageOnly:!0,brokerageId:g})})]})]})}):e.jsx(_s,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})})};function N4s({brokerageId:s,canManage:t}){const{user:r}=As(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),[g,v]=k.useState(!1),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(!1),P=async()=>{try{const{data:$,error:X}=await H.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(X)throw X;const K=$;if(K&&K.length>0){const Q=[...new Set(K.map(ce=>ce.created_by))],{data:Y}=await H.from("profiles").select("id, name, avatar_url").in("id",Q),ne=new Map((Y==null?void 0:Y.map(ce=>[ce.id,ce]))||[]),de=K.map(ce=>({...ce,author:ne.get(ce.created_by)||{name:"Unknown",avatar_url:null}}));a(de)}else a([])}catch($){console.error("Error fetching announcements:",$)}finally{l(!1)}};k.useEffect(()=>{P()},[s]);const D=()=>{b(""),S(""),A(!1),h(null)},B=$=>{$?(h($),b($.title),S($.content),A($.is_pinned)):D(),c(!0)},z=async()=>{if(!j.trim()||!N.trim()){ue.error("Please fill in all fields");return}v(!0);try{if(d){const{error:$}=await H.from("brokerage_announcements").update({title:j.trim(),content:N.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null}).eq("id",d.id);if($)throw $;ue.success("Announcement updated")}else{const{error:$}=await H.from("brokerage_announcements").insert({brokerage_id:s,created_by:r==null?void 0:r.id,title:j.trim(),content:N.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null});if($)throw $;ue.success("Announcement created")}c(!1),D(),P()}catch($){console.error("Error saving announcement:",$),ue.error("Failed to save announcement")}finally{v(!1)}},F=async()=>{if(m)try{const{error:$}=await H.from("brokerage_announcements").delete().eq("id",m);if($)throw $;ue.success("Announcement deleted"),P()}catch($){console.error("Error deleting announcement:",$),ue.error("Failed to delete announcement")}finally{x(null)}};return i?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Cu,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Cu,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(G,{size:"sm",onClick:()=>B(),className:"gap-1",children:[e.jsx(Ws,{className:"h-4 w-4"}),"New"]})]}),e.jsx(De,{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($=>{var X,K,Q,Y;return e.jsx("div",{className:`p-4 rounded-lg border ${$.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:[$.is_pinned&&e.jsx(Jj,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:$.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:$.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(vn,{className:"h-5 w-5",children:[e.jsx(ga,{src:((X=$.author)==null?void 0:X.avatar_url)||void 0}),e.jsx(bn,{className:"text-[10px]",children:((Q=(K=$.author)==null?void 0:K.name)==null?void 0:Q.charAt(0))||"?"})]}),e.jsx("span",{children:(Y=$.author)==null?void 0:Y.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ss(new Date($.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>B($),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>x($.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})},$.id)})})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsx(js,{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(he,{htmlFor:"title",children:"Title"}),e.jsx(ke,{id:"title",value:j,onChange:$=>b($.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"content",children:"Content"}),e.jsx(ur,{id:"content",value:N,onChange:$=>S($.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(br,{id:"pinned",checked:T,onCheckedChange:A}),e.jsxs(he,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Jj,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:z,disabled:g,children:g?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Yo,{open:!!m,onOpenChange:()=>x(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Announcement"}),e.jsx(Uo,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function k4s({brokerageId:s,canManage:t=!1}){const{startImpersonation:r,isLoading:n}=ipe(),{user:a}=As(),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,h]=k.useState(""),[m,x]=k.useState(new Set);k.useEffect(()=>{(async()=>{try{const{data:j,error:b}=await H.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(j||[]),j&&j.length>0){const N=j.map(T=>T.id),{data:S}=await H.from("agent_assistant_assignments").select("agent_id").in("agent_id",N);S&&x(new Set(S.map(T=>T.agent_id)))}}catch(j){console.error("Error fetching agents:",j)}finally{c(!1)}})()},[s]);const g=i.filter(v=>{var j,b;return v.name.toLowerCase().includes(d.toLowerCase())||v.email.toLowerCase().includes(d.toLowerCase())||((j=v.title)==null?void 0:j.toLowerCase().includes(d.toLowerCase()))||((b=v.areas_served)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(De,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},v))})})]}):e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents...",value:d,onChange:v=>h(v.target.value),className:"pl-9"})]})]}),e.jsx(De,{children:g.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:g.map(v=>e.jsx(S4s,{agent:v,hasAssistant:m.has(v.id),canImpersonate:t&&v.id!==(a==null?void 0:a.id),onImpersonate:()=>r(v.id,"/my-brokerage"),impersonationLoading:n},v.id))})})]})}function S4s({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(vn,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(ga,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(bn,{className:"text-lg bg-primary/10 text-primary",children:i})]}),e.jsx("h3",{className:"font-semibold text-sm leading-tight",children:s.name}),s.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s.title}),t&&e.jsx(Ge,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ja,{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(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:n,disabled:a,children:e.jsx(P3,{className:"h-4 w-4"})})}),e.jsxs(Wl,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(Nn,{className:"h-4 w-4"})})}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(Qs,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(om,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.instagram_url,target:"_blank",rel:"noopener noreferrer",title:"Instagram",children:e.jsx(au,{className:"h-4 w-4"})})})]})]})}function C4s({brokerageId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);if(k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await H.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),a(!1);return}const h=c.map(j=>j.id),{data:m,error:x}=await H.from("agent_attendance_stats").select("user_id, total_points").in("user_id",h).order("total_points",{ascending:!1});if(x)throw x;const g=new Map(c.map(j=>[j.id,j])),v=(m||[]).filter(j=>j.total_points>0).map(j=>{const b=g.get(j.user_id);return{user_id:j.user_id,total_points:j.total_points,name:(b==null?void 0:b.name)||"Unknown",avatar_url:(b==null?void 0:b.avatar_url)||null}});r(v)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),n)return e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(De,{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(s_,{className:Bt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(De,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(m=>m[0]).join("").toUpperCase().slice(0,2),h=c+1;return e.jsxs("div",{className:Bt("flex items-center gap-3 p-2 rounded-lg",h<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(h)}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:o.avatar_url||void 0}),e.jsx(bn,{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 T4s({brokerageId:s}){const t=vr(),[r,n]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await H.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),i(!1);return}const h=c.map(j=>j.id),m=new Map(c.map(j=>[j.id,j])),{data:x,error:g}=await H.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",h).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(g)throw g;const v=(x||[]).map(j=>({id:j.id,slug:j.slug,property_address:j.property_address,city:j.city,price:j.price,property_type:j.property_type,agent_id:j.agent_id,agent:m.get(j.agent_id)||null,photos:j.listing_photos||[]}));n(v)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(De,{children:[r.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Cn,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs(G,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(Ws,{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(Cn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),r.length>0&&e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Yr,{className:"h-3 w-3 ml-1"})]})]})]})}function E4s(){const{user:s,isAdmin:t,isBrokerageManager:r}=As(),n=vr(),[a,i]=k.useState(!0),[l,o]=k.useState(null),[c,d]=k.useState(""),[h,m]=k.useState(0),[x,g]=k.useState(!1),[v,j]=k.useState(!1);return k.useEffect(()=>{(async()=>{if(s)try{const{data:N}=await H.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(N!=null&&N.brokerage_id)){i(!1);return}o(N.brokerage_id);const{data:S}=await H.from("brokerages").select("name").eq("id",N.brokerage_id).maybeSingle();S&&d(S.name);const{count:T}=await H.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",N.brokerage_id);if(m(T||0),t)g(!0),j(!0);else if(r){const{data:A}=await H.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",N.brokerage_id).maybeSingle();g(!!A),j(!!A)}}catch(N){console.error("Error fetching brokerage info:",N)}finally{i(!1)}})()},[s,t,r]),a?e.jsx(_s,{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(_s,{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(fr,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[h," ",h===1?"Agent":"Agents"]})]}),v&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>n("/brokerage-content"),children:[e.jsx(Th,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(G,{onClick:()=>n(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(N4s,{brokerageId:l,canManage:x}),e.jsx(k4s,{brokerageId:l,canManage:x}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(C4s,{brokerageId:l}),e.jsx(T4s,{brokerageId:l})]})]})}):e.jsx(_s,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}function A4s(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 M4s(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 sqe={video:{icon:Ho,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ln,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:rl,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:rn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function I4s({item:s,canManage:t}){const[r,n]=k.useState(!1),[a,i]=k.useState(null),l=O$t(),o=vr(),c=sqe[s.content_type]||sqe.link,d=c.icon,h=k.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?A4s(s.url):null,[s]);k.useEffect(()=>{h||!s.url||s.content_type!=="video"||!M4s(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.thumbnail_url&&i(v.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,h]);const m=h||a,x=()=>{o(`/brokerage-content/${s.id}`)},g=async()=>{try{await l.mutateAsync(s.id),ue.success("Content deleted")}catch{ue.error("Failed to delete")}n(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:x,children:[m?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:m,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Ge,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${c.color}`,children:[e.jsx(d,{className:"h-3 w-3 mr-1"}),c.label]}),s.category&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",Ss(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Ss(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,onClick:v=>v.stopPropagation(),children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Eg,{className:"h-4 w-4"})})}),e.jsx(Vd,{align:"end",children:e.jsxs(Da,{onClick:v=>{v.stopPropagation(),n(!0)},className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Yo,{open:r,onOpenChange:n,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Content"}),e.jsxs(Uo,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:g,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function P4s(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 rqe=[{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 L4s({brokerageId:s,categories:t}){var ge;const{user:r}=As(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState("📁"),[m,x]=k.useState(!1);k.useRef(null);const[g,v]=k.useState("video"),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState(""),[X,K]=k.useState(""),Q=R$t(),Y=F$t(s),ne=B$t(),de=z$t(s),ce=()=>{v("video"),b(""),S(""),A(""),D(""),z(""),$(""),K("")},ae=async(be,Oe)=>{var Pe;const Me=(Pe=be.target.files)==null?void 0:Pe[0];if(Me){x(!0);try{const Ee=Me.name.split(".").pop(),$e=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Ee}`,{error:Se}=await H.storage.from("brokerage-content").upload($e,Me);if(Se)throw Se;const{data:{publicUrl:ze}}=H.storage.from("brokerage-content").getPublicUrl($e);Oe==="file"?(D(ze),g==="graphic"&&!B&&z(ze)):z(ze),ue.success("File uploaded")}catch(Ee){ue.error(Ee.message||"Upload failed")}finally{x(!1)}}},ie=async()=>{if(!j.trim()){ue.error("Title is required");return}if(r)try{await Q.mutateAsync({brokerage_id:s,category_id:X||null,content_type:g,title:j.trim(),description:N.trim()||null,url:T.trim()||null,file_url:P.trim()||null,thumbnail_url:B.trim()||null,event_date:F?new Date(F).toISOString():null,created_by:r.id}),ue.success("Content added!"),ce(),a(!1)}catch(be){ue.error(be.message||"Failed to add content")}},me=async()=>{if(o.trim())try{await Y.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),h("📁"),ue.success("Category created")}catch(be){ue.error(be.message||"Failed to create category")}},oe=async()=>{try{await de.mutateAsync(),ue.success("Default categories created")}catch{ue.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(vs,{open:n,onOpenChange:a,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{children:[e.jsx(Ws,{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(js,{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(he,{children:"Content Type"}),e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:rqe.map(be=>e.jsx(mt,{value:be.value,children:be.label},be.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ge=rqe.find(be=>be.value===g))==null?void 0:ge.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Category"}),e.jsxs(zs,{value:X,onValueChange:K,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category (optional)"})}),e.jsx(Fs,{children:t.map(be=>e.jsxs(mt,{value:be.id,children:[be.icon," ",be.name]},be.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Title *"}),e.jsx(ke,{value:j,onChange:be=>b(be.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:N,onChange:be=>S(be.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(g)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:g==="video"?"Video URL":g==="graphic"?"Canva / Image URL":g==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(ke,{value:T,onChange:be=>{const Oe=be.target.value;if(A(Oe),g==="video"&&!B){const Me=P4s(Oe);Me&&z(Me)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(g)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:g==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"file",accept:g==="pdf"?".pdf,.doc,.docx":"image/*",onChange:be=>ae(be,"file"),disabled:m}),m&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]}),P&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Thumbnail Image (optional)"}),e.jsx(ke,{type:"file",accept:"image/*",onChange:be=>ae(be,"thumbnail"),disabled:m}),B&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:B,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>z(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(_r,{className:"h-3 w-3"})})]})]}),g==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Event Date & Time"}),e.jsx(ke,{type:"datetime-local",value:F,onChange:be=>$(be.target.value)})]}),e.jsxs(G,{onClick:ie,disabled:Q.isPending||!j.trim(),className:"w-full",children:[Q.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(vs,{open:i,onOpenChange:l,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{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(G,{variant:"outline",size:"sm",onClick:oe,disabled:de.isPending,children:[de.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(be=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[be.icon," ",be.name]}),!be.is_default&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await ne.mutateAsync(be.id),ue.success("Category deleted")},children:e.jsx(_r,{className:"h-4 w-4"})})]},be.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(ke,{value:d,onChange:be=>h(be.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(ke,{value:o,onChange:be=>c(be.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:be=>be.key==="Enter"&&me()}),e.jsx(G,{size:"sm",onClick:me,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function D4s(){const{user:s,isAdmin:t,isBrokerageManager:r}=As(),[n,a]=k.useState(!0),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(null),[g,v]=k.useState("");k.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await H.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:P}=await H.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(P&&c(P.name),t)h(!0);else if(r){const{data:D}=await H.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();h(!!D)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,r]);const{data:j=[]}=P$t(i),{data:b=[],isLoading:N}=L$t(i,m),S=k.useMemo(()=>{if(!g.trim())return b;const T=g.toLowerCase();return b.filter(A=>{var P;return A.title.toLowerCase().includes(T)||((P=A.description)==null?void 0:P.toLowerCase().includes(T))||A.content_type.toLowerCase().includes(T)})},[b,g]);return n?e.jsx(_s,{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(_s,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(L4s,{brokerageId:i,categories:j}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search content...",value:g,onChange:T=>v(T.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(G,{variant:m===null?"default":"outline",size:"sm",onClick:()=>x(null),children:"All"}),j.map(T=>e.jsxs(G,{variant:m===T.id?"default":"outline",size:"sm",onClick:()=>x(T.id),children:[e.jsx("span",{className:"mr-1",children:T.icon}),T.name]},T.id))]})]}),N?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):S.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(im,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:g.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:S.map(T=>e.jsx(I4s,{item:T,canManage:d},T.id))})]})}):e.jsx(_s,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}const nqe={video:{icon:Ho,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ln,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:rl,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:rn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function R4s(s){try{const t=new URL(s),r=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const n=t.searchParams.get("list");if(n)return`https://www.youtube.com/embed/videoseries?list=${n}`}if(r==="youtube.com"||r==="m.youtube.com"){const n=t.searchParams.get("v");if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtu.be"){const n=t.pathname.slice(1);if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function O4s(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function F4s(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function B4s(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function z4s(){const{contentId:s}=Xi(),{data:t,isLoading:r}=gt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:h}=await H.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(h)throw h;return d},enabled:!!s});if(r)return e.jsx(_s,{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(_s,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sa,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx(G,{asChild:!0,className:"mt-4",children:e.jsx(Kn,{to:"/brokerage-content",children:"Back to Content"})})]})});const n=nqe[t.content_type]||nqe.link,a=n.icon,i=t.url||t.file_url,l=i&&O4s(i)?R4s(i):null,o=i&&F4s(i)?B4s(i):null,c=l||o;return e.jsx(_s,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Kn,{to:"/brokerage-content",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ge,{variant:"secondary",className:`text-xs px-2 py-0.5 ${n.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),n.label]}),t.category&&e.jsxs(Ge,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",Ss(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(Ne,{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(Ne,{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(Ne,{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(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(rn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Ss(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(G,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(G,{variant:t.file_url?"outline":"default",asChild:!0,size:"lg",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{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 tfe={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 $4s(s="open"){const{user:t}=As();return gt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let r=H.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 H.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 U4s(s){return gt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 q4s(s){return gt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 V4s(){const s=es(),{user:t,brokerageId:r}=As();return Lt({mutationFn:async n=>{if(!t||!r)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await H.from("brokerage_help_requests").insert({...n,brokerage_id:r,requester_user_id:t.id}).select().single();if(i)throw i;try{await H.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 H4s(){const s=es(),{user:t}=As();return Lt({mutationFn:async({request_id:r,note:n})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await H.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 G4s(){const s=es();return Lt({mutationFn:async({claim_id:t,request_id:r,claimant_user_id:n})=>{const{error:a}=await H.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await H.from("brokerage_help_requests").update({status:"filled",assigned_user_id:n}).eq("id",r);if(i)throw i;try{await H.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 W4s(){const s=es();return Lt({mutationFn:async({claim_id:t})=>{const{error:r}=await H.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 K4s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 Y4s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 Z4s(){const{user:s,brokerageId:t}=As(),r=es(),n=gt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await H.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=Lt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await H.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 X4s(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 Q4s(s){switch(s.compensation_type){case"flat_fee":return s.compensation_amount?`$${Number(s.compensation_amount).toFixed(0)}`:"Flat fee";case"referral_percent":return s.compensation_amount?`${Number(s.compensation_amount)}% referral`:"Referral";case"goodwill":return"Goodwill"}}function J4s({req:s,onClick:t}){var i;const r=tfe[s.request_type],n=X4s(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(Ne,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(De,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[r.emoji," ",r.label]}),s.status!=="open"&&e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(ya,{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(cn,{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(ja,{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(_l,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Q4s(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 e3s(){var c;const s=vr(),{brokerageId:t}=As(),[r,n]=k.useState("open"),{data:a=[],isLoading:i}=$4s(r),l=Z4s(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(_s,{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(Rn,{value:r,onValueChange:d=>n(d),children:e.jsxs(Dn,{children:[e.jsx(Xt,{value:"open",children:"Open"}),e.jsx(Xt,{value:"mine",children:"My Posts"}),e.jsx(Xt,{value:"my_claims",children:"My Claims"}),e.jsx(Xt,{value:"filled",children:"Filled"})]})}),e.jsxs(G,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(Rm,{className:"h-4 w-4 text-primary"}):e.jsx(Fv,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email-notif",className:"text-sm font-medium cursor-pointer",children:"Email me when teammates post new help requests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can still browse the board either way."})]})]}),e.jsx(br,{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(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Hy,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"font-medium",children:"Nothing here yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:r==="open"?"No open requests right now — be the first to post one!":"Check back later."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(d=>e.jsx(J4s,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(_s,{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(Hy,{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 t3s(){const s=vr(),{toast:t}=Ea(),r=V4s(),[n,a]=k.useState("open_house"),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState("goodwill"),[X,K]=k.useState(""),[Q,Y]=k.useState(""),ne=n==="open_house"||n==="showing_coverage",de=n!=="general",ce=(ie,me)=>!ie||!me?null:`${ie}T${me}:00`,ae=async ie=>{if(ie.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const me=ce(d,m),oe=ce(d,g);await r.mutateAsync({request_type:n,title:i.trim(),description:o.trim()||null,event_start_at:me,event_end_at:oe,address:ne&&j.trim()||null,city:ne&&N.trim()||null,state:ne&&T.trim()||null,zip:ne&&P.trim()||null,mls_number:B.trim()||null,compensation_type:F,compensation_amount:X?Number(X):null,compensation_notes:Q.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(me){t({title:"Could not post",description:(me==null?void 0:me.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(_s,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(wa,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ae,children:e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(tfe).map(ie=>{const me=tfe[ie],oe=ie===n;return e.jsxs("button",{type:"button",onClick:()=>a(ie),className:`text-left p-3 rounded-lg border-2 transition ${oe?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:me.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:me.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:me.description})]},ie)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:i,onChange:ie=>l(ie.target.value),placeholder:n==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Details"}),e.jsx(ur,{id:"description",value:o,onChange:ie=>c(ie.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),de&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"date",children:"Date"}),e.jsx(ke,{id:"date",type:"date",value:d,onChange:ie=>h(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"start",children:"Start"}),e.jsx(ke,{id:"start",type:"time",value:m,onChange:ie=>x(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"end",children:"End"}),e.jsx(ke,{id:"end",type:"time",value:g,onChange:ie=>v(ie.target.value)})]})]}),ne&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"address",children:"Address"}),e.jsx(ke,{id:"address",value:j,onChange:ie=>b(ie.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(ke,{id:"city",value:N,onChange:ie=>S(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(ke,{id:"state",value:T,onChange:ie=>A(ie.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zip",children:"Zip"}),e.jsx(ke,{id:"zip",value:P,onChange:ie=>D(ie.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(ke,{id:"mls",value:B,onChange:ie=>z(ie.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(he,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(ie=>{const me=F===ie.val;return e.jsxs("button",{type:"button",onClick:()=>$(ie.val),className:`text-left p-3 rounded-lg border-2 transition ${me?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ie.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ie.sub})]},ie.val)})}),F!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"amount",children:F==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(ke,{id:"amount",type:"number",min:"0",step:F==="referral_percent"?"1":"5",value:X,onChange:ie=>K(ie.target.value),placeholder:F==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(ke,{id:"comp-notes",value:Q,onChange:ie=>Y(ie.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:r.isPending,className:"gap-2",children:[r.isPending&&e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function s3s(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 m_e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function r3s(){var B,z,F,$,X,K,Q,Y;const{id:s}=Xi(),t=vr(),{user:r}=As(),{toast:n}=Ea(),{data:a,isLoading:i}=U4s(s),{data:l=[]}=q4s(s),o=H4s(),c=G4s(),d=W4s(),h=K4s(),m=Y4s(),[x,g]=k.useState("");if(i)return e.jsx(_s,{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(_s,{title:"Not Found",description:"",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const v=tfe[a.request_type],j=s3s(a.event_start_at,a.event_end_at),b=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),N=(r==null?void 0:r.id)===a.requester_user_id,S=l.find(ne=>ne.claimant_user_id===(r==null?void 0:r.id)),T=l.find(ne=>ne.status==="accepted"),A=a.status==="open",P=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",D=async()=>{if(!x.trim()){n({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:x.trim()}),n({title:"You're in!",description:"The requester will review and pick someone."}),g("")}catch(ne){n({title:"Could not submit",description:ne==null?void 0:ne.message,variant:"destructive"})}};return e.jsx(_s,{title:a.title,description:`${v.emoji} ${v.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"})," Back to board"]}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ge,{variant:"secondary",children:[v.emoji," ",v.label]}),e.jsx(Ge,{variant:A?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(vn,{className:"h-7 w-7",children:[e.jsx(ga,{src:((B=a.requester)==null?void 0:B.avatar_url)||void 0}),e.jsx(bn,{children:m_e((z=a.requester)==null?void 0:z.name)})]}),e.jsx("span",{children:((F=a.requester)==null?void 0:F.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[j&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(cn,{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:j})]})]}),b&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ja,{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(_l,{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:P})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Wj,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!N&&A&&!S&&e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(ur,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:x,onChange:ne=>g(ne.target.value),rows:3,maxLength:400}),e.jsxs(G,{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"]})]})}),!N&&S&&e.jsx(Ne,{className:"border-primary/30 bg-primary/5",children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Hn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",S.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[S.status==="pending"&&"Waiting for the requester to pick.",S.status==="accepted"&&"You're confirmed — see contact info below.",S.status==="declined"&&"They went with someone else this time."]})]})]})}),T&&(N||T.claimant_user_id===(r==null?void 0:r.id))&&e.jsx(Ne,{className:"border-primary/30",children:e.jsxs(De,{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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:(($=T.claimant)==null?void 0:$.avatar_url)||void 0}),e.jsx(bn,{children:m_e((X=T.claimant)==null?void 0:X.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(K=T.claimant)==null?void 0:K.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((Q=T.claimant)==null?void 0:Q.email)&&e.jsxs("a",{href:`mailto:${T.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Qs,{className:"h-4 w-4"})," ",T.claimant.email]}),((Y=T.claimant)==null?void 0:Y.phone)&&e.jsxs("a",{href:`tel:${T.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Nn,{className:"h-4 w-4"})," ",T.claimant.phone]})]})]})}),N&&e.jsx(Ne,{children:e.jsxs(De,{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(ne=>{var de,ce,ae,ie,me;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:((de=ne.claimant)==null?void 0:de.avatar_url)||void 0}),e.jsx(bn,{children:m_e((ce=ne.claimant)==null?void 0:ce.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:((ae=ne.claimant)==null?void 0:ae.name)||"Teammate"}),e.jsx(Ge,{variant:"outline",className:"capitalize text-xs",children:ne.status})]}),ne.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',ne.note,'"']}),ne.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(G,{size:"sm",onClick:()=>c.mutate({claim_id:ne.id,request_id:a.id,claimant_user_id:ne.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Hn,{className:"h-3.5 w-3.5"})," Pick ",((me=(ie=ne.claimant)==null?void 0:ie.name)==null?void 0:me.split(" ")[0])||"them"]}),e.jsxs(G,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:ne.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(_r,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},ne.id)}),N&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Cancel request"})}),N&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(G,{size:"sm",onClick:()=>m.mutate(a.id),disabled:m.isPending,children:"Mark complete"})})]})})]})})}var pmt="Toggle",sAe=k.forwardRef((s,t)=>{const{pressed:r,defaultPressed:n,onPressedChange:a,...i}=s,[l,o]=Lh({prop:r,onChange:a,defaultProp:n??!1,caller:pmt});return e.jsx(pn.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:Or(s.onClick,()=>{s.disabled||o(!l)})})});sAe.displayName=pmt;var xmt=sAe,nN="ToggleGroup",[gmt]=yd(nN,[U2]),ymt=U2(),rAe=k.forwardRef((s,t)=>{const{type:r,...n}=s;if(r==="single"){const a=n;return e.jsx(n3s,{...a,ref:t})}if(r==="multiple"){const a=n;return e.jsx(a3s,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${nN}\``)});rAe.displayName=nN;var[vmt,bmt]=gmt(nN),n3s=k.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=Lh({prop:r,defaultProp:n??"",onChange:a,caller:nN});return e.jsx(vmt,{scope:s.__scopeToggleGroup,type:"single",value:k.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:k.useCallback(()=>o(""),[o]),children:e.jsx(_mt,{...i,ref:t})})}),a3s=k.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=Lh({prop:r,defaultProp:n??[],onChange:a,caller:nN}),c=k.useCallback(h=>o((m=[])=>[...m,h]),[o]),d=k.useCallback(h=>o((m=[])=>m.filter(x=>x!==h)),[o]);return e.jsx(vmt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(_mt,{...i,ref:t})})});rAe.displayName=nN;var[i3s,o3s]=gmt(nN),_mt=k.forwardRef((s,t)=>{const{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=ymt(r),h=$2(l),m={role:"group",dir:h,...c};return e.jsx(i3s,{scope:r,rovingFocus:a,disabled:n,children:a?e.jsx(lpe,{asChild:!0,...d,orientation:i,dir:h,loop:o,children:e.jsx(pn.div,{...m,ref:t})}):e.jsx(pn.div,{...m,ref:t})})}),sfe="ToggleGroupItem",wmt=k.forwardRef((s,t)=>{const r=bmt(sfe,s.__scopeToggleGroup),n=o3s(sfe,s.__scopeToggleGroup),a=ymt(s.__scopeToggleGroup),i=r.value.includes(s.value),l=n.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=k.useRef(null);return n.rovingFocus?e.jsx(cpe,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(aqe,{...o,ref:t})}):e.jsx(aqe,{...o,ref:t})});wmt.displayName=sfe;var aqe=k.forwardRef((s,t)=>{const{__scopeToggleGroup:r,value:n,...a}=s,i=bmt(sfe,r),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(sAe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(n):i.onItemDeactivate(n)}})}),jmt=rAe,Nmt=wmt;const kmt=V5("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"}}),l3s=k.forwardRef(({className:s,variant:t,size:r,...n},a)=>e.jsx(xmt,{ref:a,className:Bt(kmt({variant:t,size:r,className:s})),...n}));l3s.displayName=xmt.displayName;const Smt=k.createContext({size:"default",variant:"default"}),nAe=k.forwardRef(({className:s,variant:t,size:r,children:n,...a},i)=>e.jsx(jmt,{ref:i,className:Bt("flex items-center justify-center gap-1",s),...a,children:e.jsx(Smt.Provider,{value:{variant:t,size:r},children:n})}));nAe.displayName=jmt.displayName;const rfe=k.forwardRef(({className:s,children:t,variant:r,size:n,...a},i)=>{const l=k.useContext(Smt);return e.jsx(Nmt,{ref:i,className:Bt(kmt({variant:l.variant||r,size:l.size||n}),s),...a,children:t})});rfe.displayName=Nmt.displayName;const c3s=[{key:"search",label:"Search for Properties",icon:fn,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Nn,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:Qs,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:rn,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Cn,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:_l,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:ja,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:Pc,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:Dd,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function iqe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function d3s(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Cmt({html:s,onChange:t}){const{user:r}=As(),n=k.useRef(null),a=k.useRef(""),i=k.useRef(t);i.current=t;const[l,o]=k.useState("desktop"),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=k.useState(""),[g,v]=k.useState(""),j=k.useRef(null),b=()=>{var yt;const dt=(yt=n.current)==null?void 0:yt.contentDocument,Qt=dt==null?void 0:dt.getSelection();Qt&&Qt.rangeCount>0&&(dt!=null&&dt.body.contains(Qt.anchorNode))&&(j.current=Qt.getRangeAt(0).cloneRange())},N=()=>{var fs;const dt=c.current,Qt=(fs=n.current)==null?void 0:fs.contentDocument;if(!dt||!Qt)return;let yt=m.trim();yt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(yt)&&(yt="https://"+yt),dt.setAttribute("href",yt),dt.setAttribute("target","_blank");const ss=g.trim();ss&&ss!==(dt.textContent||"").trim()&&(dt.textContent=ss);const Is=` `+Qt.documentElement.outerHTML;a.current=Is,i.current(Is),h(!1)};k.useEffect(()=>{var yt,ss;const dt=n.current;if(!dt||a.current===s)return;const Qt=()=>{const Is=dt.contentDocument;if(!Is)return;Is.open(),Is.write(s||""),Is.close(),a.current=s;const fs=Is.body;if(!fs)return;fs.setAttribute("contenteditable","true"),fs.style.outline="none",fs.style.minHeight="400px",fs.style.cursor="text";const ar=()=>{const Tr=` `+Is.documentElement.outerHTML;a.current=Tr,i.current(Tr)};fs.addEventListener("input",ar),fs.addEventListener("blur",ar),fs.addEventListener("mouseup",b),fs.addEventListener("keyup",b),Is.addEventListener("selectionchange",b);const Er=Tr=>{var zn;const Lr=Tr.target,$r=Lr==null?void 0:Lr.closest("a");if($r){if(Tr.metaKey||Tr.ctrlKey||Tr.shiftKey)return;Tr.preventDefault(),Tr.stopPropagation(),c.current=$r,x($r.getAttribute("href")||""),v(($r.textContent||"").trim()),h(!0);return}const kr=Is.getSelection();if(!kr)return;const Sr=(zn=Is.caretRangeFromPoint)==null?void 0:zn.call(Is,Tr.clientX,Tr.clientY),hn=Sr==null?void 0:Sr.startContainer;if(hn&&hn.nodeType===Node.TEXT_NODE){const Xs=hn.textContent||"",Ur=Sr.startOffset,xn=Xs.lastIndexOf("[",Ur),us=Xs.indexOf("]",Ur);if(xn!==-1&&us!==-1&&us>xn){const pr=Is.createRange();pr.setStart(hn,xn),pr.setEnd(hn,us+1),kr.removeAllRanges(),kr.addRange(pr),j.current=pr.cloneRange()}}};fs.addEventListener("click",Er,!0)};((yt=dt.contentDocument)==null?void 0:yt.readyState)==="complete"||(ss=dt.contentDocument)!=null&&ss.body?Qt():dt.addEventListener("load",Qt,{once:!0})},[s]);const S=(dt,Qt)=>{var Is;const yt=(Is=n.current)==null?void 0:Is.contentDocument;if(!yt)return;yt.body.focus(),yt.execCommand(dt,!1,Qt);const ss=` `+yt.documentElement.outerHTML;a.current=ss,i.current(ss)},T=()=>{const dt=window.prompt("Enter URL (https://...)");dt&&S("createLink",dt)},A=(dt,Qt)=>{var Is;const yt=(Is=n.current)==null?void 0:Is.contentDocument;if(!yt)return;if(yt.body.focus(),Qt==="cursor"&&j.current&&yt.body.contains(j.current.startContainer)){const fs=yt.getSelection();if(fs){fs.removeAllRanges(),fs.addRange(j.current),yt.execCommand("insertHTML",!1,dt);const ar=` `+yt.documentElement.outerHTML;a.current=ar,i.current(ar);return}}Qt==="top"?yt.body.insertAdjacentHTML("afterbegin",dt):yt.body.insertAdjacentHTML("beforeend",dt);const ss=` `+yt.documentElement.outerHTML;a.current=ss,i.current(ss)},[P,D]=k.useState(!1),[B,z]=k.useState(null),[F,$]=k.useState(""),[X,K]=k.useState(""),[Q,Y]=k.useState("#406E71"),[ne,de]=k.useState("cursor"),ce=dt=>{z(dt),$(dt.defaultText),K(""),D(!0)},ae=()=>{if(!B)return;const dt=X.trim();if(!B.isForward&&!dt)return;let Qt=dt;if(B.isForward){const fs=dt||"",ar=encodeURIComponent("You should see this newsletter"),Er=encodeURIComponent(fs?`I thought you'd like this — take a look: ${fs} `:`I thought you'd like this newsletter — take a look! `);Qt=`mailto:?subject=${ar}&body=${Er}`}else B.hrefPrefix==="tel:"?Qt="tel:"+dt.replace(/[^0-9+]/g,""):B.hrefPrefix==="mailto:"?Qt="mailto:"+dt:/^https?:\/\//i.test(dt)||(Qt="https://"+dt);const yt=(F||B.defaultText).replace(/[<>]/g,""),ss=Q||"#406E71",Is=`
${yt}

 

`;A(Is,ne),D(!1)},[ie,me]=k.useState(!1),[oe,ge]=k.useState(""),[be,Oe]=k.useState(""),[Me,Pe]=k.useState(""),[Ee,$e]=k.useState("cursor"),Se=(()=>{if(be.trim())return be.trim();const dt=iqe(oe);return dt?`https://i.ytimg.com/vi/${dt}/hqdefault.jpg`:""})(),ze=()=>{ge(""),Oe(""),Pe(""),me(!0)},Te=()=>{const dt=oe.trim();if(!dt)return;let Qt=dt;/^https?:\/\//i.test(Qt)||(Qt="https://"+Qt);const yt=iqe(Qt),ss=yt?null:d3s(Qt);let Is=be.trim();!Is&&yt&&(Is=`https://i.ytimg.com/vi/${yt}/hqdefault.jpg`),!Is&&ss&&(Is=`https://vumbnail.com/${ss}.jpg`),Is||(Is="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const fs=(Me||"Watch the video").replace(/[<>]/g,""),ar=`
${fs}
▶ ${fs}

 

`.trim();A(ar,Ee),me(!1)},[ye,ct]=k.useState(!1),[ve,rt]=k.useState(""),[Re,Qe]=k.useState(""),[Ke,Ce]=k.useState("full"),[nt,$t]=k.useState("cursor"),[lt,it]=k.useState(!1),Nt=k.useRef(null),Ft=()=>{rt(""),Qe(""),Ce("full"),ct(!0)},at=async dt=>{var Qt;if(!r){ue.error("You must be signed in to upload images");return}if(dt.size>10*1024*1024){ue.error("Image must be under 10MB");return}it(!0);try{const yt=((Qt=dt.name.split(".").pop())==null?void 0:Qt.toLowerCase())||"png",ss=`${r.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${yt}`,{error:Is}=await H.storage.from("email-assets").upload(ss,dt,{cacheControl:"3600",upsert:!1,contentType:dt.type});if(Is)throw Is;const{data:fs}=H.storage.from("email-assets").getPublicUrl(ss);rt(fs.publicUrl),ue.success("Image uploaded")}catch(yt){ue.error(yt.message||"Upload failed")}finally{it(!1)}},Ie=()=>{if(!ve.trim())return;const dt=(Re||"").replace(/[<>"]/g,""),Qt=Ke==="half"?280:560,yt=`
${dt}

 

`.trim();A(yt,nt),ct(!1)},{data:et,isLoading:Dt}=gt({queryKey:["newsletter-editor-videos",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&ie,queryFn:async()=>{const{data:dt,error:Qt}=await H.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(Qt)throw Qt;return dt||[]}}),Jt=dt=>{dt.share_token&&(ge(`https://video.relevelup.com/share/video/${dt.share_token}`),Oe(`https://video.relevelup.com/thumb/${dt.share_token}`),Pe(dt.title||"Watch the video"))},cs=l==="mobile"?390:"100%",Ht=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("bold"),title:"Bold",children:e.jsx(qj,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("italic"),title:"Italic",children:e.jsx(Kj,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("underline"),title:"Underline",children:e.jsx(xM,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("insertUnorderedList"),title:"Bullet list",children:e.jsx(lm,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("insertOrderedList"),title:"Numbered list",children:e.jsx(r0,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:T,title:"Insert link",children:e.jsx(xo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("undo"),title:"Undo",children:e.jsx(s2,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("redo"),title:"Redo",children:e.jsx(e2,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Dd,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Vd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(Tue,{children:"Insert a call-to-action"}),e.jsx(y_,{}),c3s.map(dt=>{const Qt=dt.icon;return e.jsxs(Da,{onClick:()=>ce(dt),children:[e.jsx(Qt,{className:"h-4 w-4 mr-2"}),dt.label]},dt.key)})]})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:Ft,children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:ze,children:[e.jsx(sn,{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(nAe,{type:"single",value:l,onValueChange:dt=>dt&&o(dt),size:"sm",className:"h-7",children:[e.jsx(rfe,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(Zj,{className:"h-3.5 w-3.5"})}),e.jsx(rfe,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(zg,{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(Dd,{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:cs,maxWidth:Ht,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:h,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(js,{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(he,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(ke,{id:"link-edit-text",value:g,onChange:dt=>v(dt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(ke,{id:"link-edit-href",value:m,onChange:dt=>x(dt.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(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:N,disabled:!m.trim(),children:"Save link"})]})]})}),e.jsx(vs,{open:P,onOpenChange:D,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsxs(bs,{children:["Insert ",(B==null?void 0:B.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-text",children:"Button text"}),e.jsx(ke,{id:"cta-text",value:F,onChange:dt=>$(dt.target.value),placeholder:B==null?void 0:B.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-value",children:B==null?void 0:B.helper}),e.jsx(ke,{id:"cta-value",value:X,onChange:dt=>K(dt.target.value),placeholder:B==null?void 0:B.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{id:"cta-color",type:"color",value:Q,onChange:dt=>Y(dt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(ke,{value:Q,onChange:dt=>Y(dt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Position"}),e.jsxs(Vb,{value:ne,onValueChange:dt=>de(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"cursor",id:"cta-cursor"}),e.jsxs(he,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"top",id:"cta-top"}),e.jsxs(he,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Fd,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"bottom",id:"cta-bottom"}),e.jsxs(he,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ku,{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:F||(B==null?void 0:B.defaultText)})})]}),e.jsxs(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:ae,disabled:!(B!=null&&B.isForward)&&!X.trim(),children:"Insert Button"})]})]})}),e.jsx(vs,{open:ie,onOpenChange:me,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:"Insert Video Block"})}),e.jsxs(Rn,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"library",children:"My Library"}),e.jsx(Xt,{value:"url",children:"From URL"}),e.jsx(Xt,{value:"record",children:"Record New"})]}),e.jsxs(as,{value:"library",className:"space-y-3 mt-2",children:[Dt?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..."]}):!et||et.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(sn,{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:et.map(dt=>{const Qt=oe.includes(dt.share_token||"___"),yt=dt.share_token?`https://video.relevelup.com/thumb/${dt.share_token}`:dt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Jt(dt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Qt?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[yt?e.jsx("img",{src:yt,alt:dt.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(sn,{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(Ho,{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:dt.title||"Untitled"})})]},dt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(ke,{id:"vid-title-lib",value:Me,onChange:dt=>Pe(dt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(as,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(ke,{id:"vid-url",value:oe,onChange:dt=>ge(dt.target.value),placeholder:"https://youtube.com/watch?v=... or Vimeo link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"YouTube & Vimeo thumbnails are detected automatically."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(ke,{id:"vid-title",value:Me,onChange:dt=>Pe(dt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(ke,{id:"vid-thumb",value:be,onChange:dt=>Oe(dt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(as,{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(sn,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx(G,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(he,{children:"Position"}),e.jsxs(Vb,{value:Ee,onValueChange:dt=>$e(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"cursor",id:"vid-cursor"}),e.jsxs(he,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"top",id:"vid-top"}),e.jsxs(he,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Fd,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"bottom",id:"vid-bottom"}),e.jsxs(he,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ku,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Se&&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:Se,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:dt=>{dt.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(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>me(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:Te,disabled:!oe.trim(),children:"Insert Video"})]})]})}),e.jsx(vs,{open:ye,onOpenChange:ct,children:e.jsxs(ys,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:"Insert Image"})}),e.jsxs(Rn,{defaultValue:"upload",className:"space-y-3",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"upload",children:"Upload"}),e.jsx(Xt,{value:"url",children:"From URL"})]}),e.jsxs(as,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Nt,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:dt=>{var yt;const Qt=(yt=dt.target.files)==null?void 0:yt[0];Qt&&at(Qt),dt.target.value=""}}),ve?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:ve,alt:"Preview",className:"w-full max-h-48 object-contain"}),e.jsxs("div",{className:"flex justify-between items-center p-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:"Uploaded ✓"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>rt(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var dt;return(dt=Nt.current)==null?void 0:dt.click()},disabled:lt,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:lt?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(oa,{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(as,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"img-url",children:"Image URL"}),e.jsx(ke,{id:"img-url",value:ve,onChange:dt=>rt(dt.target.value),placeholder:"https://..."})]}),ve&&/^https?:\/\//i.test(ve)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:ve,alt:"Preview",className:"w-full max-h-48 object-contain",onError:dt=>{dt.target.style.opacity="0.3"}})})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(ke,{id:"img-alt",value:Re,onChange:dt=>Qe(dt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Size"}),e.jsxs(Vb,{value:Ke,onValueChange:dt=>Ce(dt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"full",id:"img-full"}),e.jsx(he,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"half",id:"img-half"}),e.jsx(he,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Position"}),e.jsxs(Vb,{value:nt,onValueChange:dt=>$t(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"cursor",id:"img-cursor"}),e.jsxs(he,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dd,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"top",id:"img-top"}),e.jsxs(he,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Fd,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Qd,{value:"bottom",id:"img-bottom"}),e.jsxs(he,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ku,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>ct(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:Ie,disabled:!ve.trim()||lt,children:"Insert Image"})]})]})})]})}function u3s({open:s,onOpenChange:t,initial:r,onSaved:n}){const{user:a,isAdmin:i,isBrokerageManager:l,brokerageId:o}=As(),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(!1),[b,N]=k.useState("private"),[S,T]=k.useState(!1),{data:A}=gt({queryKey:["my-team-leader-info",a==null?void 0:a.id],enabled:!!(a!=null&&a.id)&&s,queryFn:async()=>{const{data:z}=await H.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return z}}),P=(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)??""),g((r==null?void 0:r.html_content)??h3s()),j((r==null?void 0:r.is_template)??!1),N((r==null?void 0:r.share_scope)??"private"))},[s,r]);const B=async()=>{if(a){if(!c.trim()){ue.error("Please enter a title");return}if(!x.trim()){ue.error("Newsletter content is empty");return}T(!0);try{const z={user_id:a.id,title:c.trim(),description:h.trim()||null,html_content:x,is_template:v,share_scope:b,shared_team_id:b==="team"?D:null,shared_brokerage_id:b==="brokerage"?o:null};if(b==="team"&&!D){ue.error("You must be a team leader to share with a team"),T(!1);return}if(b==="brokerage"&&!l){ue.error("Only brokerage managers can share to a brokerage"),T(!1);return}if(b==="global"&&!i){ue.error("Only admins can publish global starter templates"),T(!1);return}let F;if(r!=null&&r.id?{error:F}=await H.from("agent_custom_newsletters").update(z).eq("id",r.id):{error:F}=await H.from("agent_custom_newsletters").insert(z),F)throw F;ue.success(r!=null&&r.id?"Saved":"Newsletter created"),n==null||n(),t(!1)}catch(z){ue.error(z.message||"Failed to save")}finally{T(!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(js,{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(he,{htmlFor:"acn-title",children:"Title *"}),e.jsx(ke,{id:"acn-title",value:c,onChange:z=>d(z.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(ke,{id:"acn-desc",value:h,onChange:z=>m(z.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(br,{id:"acn-template",checked:v,onCheckedChange:j}),e.jsx(he,{htmlFor:"acn-template",className:"cursor-pointer",children:"Save as reusable template"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Templates can be duplicated and reused for future newsletters"})]}),(P||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(he,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(Vb,{value:b,onValueChange:z=>N(z),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qd,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(he,{htmlFor:"s-private",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Private"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Only you can see this"})]})]}),P&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qd,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(he,{htmlFor:"s-team",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my team"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All members of your team can use this"})]})]}),l&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qd,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(he,{htmlFor:"s-brokerage",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my brokerage"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All agents in your brokerage can use this"})]})]}),i&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qd,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(he,{htmlFor:"s-global",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Global starter template"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Visible to all users as a starter"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"mb-2 block",children:"Content"}),e.jsx(Cmt,{html:x,onChange:g})]})]}),e.jsxs(on,{className:"px-6 py-3 border-t",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs(G,{onClick:B,disabled:S,children:[S?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-2"}),r!=null&&r.id?"Save Changes":"Create"]})]})]})})}function h3s(){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 Oh(){const{data:s,isLoading:t}=gt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:a,error:i}=await H.from("gmail_integrations").select("*").maybeSingle();if(i)throw i;return a}}),r=!!(s!=null&&s.is_active),n=(s==null?void 0:s.gmail_email)||null;return{isGmailConnected:r,gmailEmail:n,isLoading:t}}function Az(){var a;const{user:s}=As(),{data:t,isLoading:r}=gt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,h,m,x;const[i,l]=await Promise.all([H.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),H.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((h=c==null?void 0:c.email)==null?void 0:h.trim())||s.email||null,display_name:((m=o==null?void 0:o.display_name)==null?void 0:m.trim())||((x=c==null?void 0:c.name)==null?void 0:x.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:r,settings:t}}function eL(){const s=na();return gt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(r)throw r;return t},enabled:!!s})}function m3s(s){return gt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(r)throw r;return t},enabled:!!s})}function aAe(){const s=es(),t=na();return Lt({mutationFn:async({name:r,color:n})=>{const{data:a,error:i}=await H.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 f3s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 p3s(){const s=es();return Lt({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 H.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 Tmt(){const s=es();return Lt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await H.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 x3s(){const s=es();return Lt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await H.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 iAe(){const s=na();return gt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await H.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 Emt(){const{user:s}=As();return gt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function g3s(){const s=es(),{user:t}=As();return Lt({mutationFn:async({name:r,filters:n,sort_by:a})=>{const{data:i,error:l}=await H.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"]}),nn({title:"Smart filter saved"})},onError:r=>{nn({title:"Error saving smart filter",description:r.message,variant:"destructive"})}})}function y3s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("contact_smart_lists").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),nn({title:"Smart filter deleted"})}})}const oqe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function lqe(s,t,r,n){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:(r==null?void 0:r.name)||"",agent_email:(r==null?void 0:r.email)||"",agent_phone:(r==null?void 0:r.phone)||"",agent_title:(r==null?void 0:r.title)||"",brokerage:n||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,h)=>c[h]??`{{${h}}}`)}function v3s(s,t,r,n){const a=t.trim()?`
${oqe(t).replace(/\n/g,"
")}
`:"",i=r.trim()?`
${oqe(r).replace(/\n/g,"
")}
`:"",l=n?`
${n}
`:"";return`${a} ${s} ${i} ${l}`}function b3s(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 _3s=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function w3s(s,t){const r=[],n=s.trim();if(n.length>0){n.length<10&&r.push("Subject line is very short — most opened subjects are 30-60 characters."),n.length>90&&r.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=n.replace(/[^A-Za-z]/g,""),o=n.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&r.push("Subject is mostly uppercase — this often triggers spam filters."),(n.match(/!/g)||[]).length>=3&&r.push("Too many exclamation marks in the subject.");const d=n.toLowerCase(),h=_3s.filter(m=>d.includes(m));h.length>0&&r.push(`Subject contains spam-trigger words: ${h.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&r.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&r.push("Email is mostly images with little text — many spam filters block these."),r}function oAe({open:s,onOpenChange:t,newsletterId:r,newsletterTitle:n,htmlCode:a}){const{user:i}=As();Oh();const{isReady:l,settings:o}=Az(),c=na(),{data:d}=gt({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:Xs}=await H.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return Xs}}),[h,m]=k.useState("visual"),[x,g]=k.useState("all"),[v,j]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,P]=k.useState(""),[D,B]=k.useState(!0),[z,F]=k.useState([]),[$,X]=k.useState(null),[K,Q]=k.useState(new Set),[Y,ne]=k.useState(""),[de,ce]=k.useState(!1),[ae,ie]=k.useState(!1),[me,oe]=k.useState(!1),[ge,be]=k.useState({sent:0,failed:0,total:0,currentName:""}),[Oe,Me]=k.useState(!0),[Pe,Ee]=k.useState(!1),[$e,Se]=k.useState([]),[ze,Te]=k.useState(!1),[ye,ct]=k.useState(new Set),[ve,rt]=k.useState("now"),[Re,Qe]=k.useState(""),{data:Ke=[]}=eL(),{data:Ce=[]}=iAe(),{data:nt=[]}=Emt(),{data:$t=[],isLoading:lt}=gt({queryKey:["newsletter-send-contacts",c],enabled:!!c&&s,queryFn:async()=>{const Xs=[];let Ur=0;const xn=1e3;for(;;){const{data:us,error:pr}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",c).not("email","is",null).neq("email","").order("first_name").range(Ur,Ur+xn-1);if(pr)throw pr;if(!us||us.length===0||(Xs.push(...us),us.length{const{data:Xs}=await H.from("ses_suppressed_emails").select("email");return(Xs||[]).map(Ur=>Ur.email.toLowerCase())}}),{data:Nt}=gt({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:Xs}=await H.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(Xs!=null&&Xs.brokerage_id))return null;const{data:Ur}=await H.from("brokerages").select("name, city, state").eq("id",Xs.brokerage_id).maybeSingle();return Ur}}),{data:Ft}=gt({queryKey:["newsletter-active-lead-site",c],enabled:!!c&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!c)return null;const{data:Xs}=await H.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",c).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return Xs}}),at=!!(Ft!=null&&Ft.mls_provider_id),Ie=(Ft==null?void 0:Ft.mls_agent_id)||(Ft==null?void 0:Ft.mls_agent_key)||null,{data:et=[],isLoading:Dt}=gt({queryKey:["newsletter-agent-listings",c,Ie],enabled:!!c&&!!Ie&&ze,staleTime:60*1e3,queryFn:async()=>{if(!Ie)return[];const{data:Xs}=await H.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",Ie).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return Xs||[]}}),Jt=k.useMemo(()=>{const Xs=new Set(it);return $t.filter(Ur=>Ur.email&&Ur.email.includes("@")&&!Xs.has(Ur.email.toLowerCase()))},[$t,it]),cs=k.useMemo(()=>{if(z.length===0)return null;const Xs=new Set;for(const Ur of Ce)z.includes(Ur.tag_id)&&Xs.add(Ur.contact_id);return Xs},[Ce,z]),Ht=k.useMemo(()=>nt.find(Xs=>Xs.id===$)||null,[nt,$]),dt=k.useMemo(()=>{var Xs;if(x==="all")return Jt;if(x==="tags")return cs?Jt.filter(Ur=>cs.has(Ur.id)):[];if(x==="smartlists"){if(!Ht)return[];const Ur=(((Xs=Ht.filters)==null?void 0:Xs.search)||"").toLowerCase().trim();return Ur?Jt.filter(xn=>`${xn.first_name||""} ${xn.last_name||""}`.toLowerCase().includes(Ur)||(xn.email||"").toLowerCase().includes(Ur)):Jt}return Jt.filter(Ur=>K.has(Ur.id))},[x,Jt,cs,Ht,K]),Qt=k.useMemo(()=>{if(!Y.trim())return Jt;const Xs=Y.toLowerCase();return Jt.filter(Ur=>`${Ur.first_name||""} ${Ur.last_name||""}`.toLowerCase().includes(Xs))},[Jt,Y]);k.useEffect(()=>{s&&(j(""),N(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),T(`As always, reach out anytime if I can help. Talk soon!`),P(a||""),m("light"),g("all"),F([]),X(null),Q(new Set),ne(""),ce(!1),B(!0),Me(!0),Se([]),rt("now"),Qe(""),be({sent:0,failed:0,total:0,currentName:""}))},[s,n,a]);const yt=l,ss=!!(v.trim()&&yt&&dt.length>0&&!ae),Is=Xs=>{const Ur=h==="advanced"||h==="visual"?A:a,xn=D&&(d!=null&&d.email_signature)?d.email_signature:null;let us;return h==="light"?us=v3s(Ur,b,S,xn):us=xn?`${Ur}
${xn}
`:Ur,Oe&&(us+=b3s(d??null,Nt??null,Xs.email)),lqe(us,Xs,d??null,(Nt==null?void 0:Nt.name)??null)},fs=k.useMemo(()=>Is({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[h,b,S,A,a,D,d,Oe,Nt]),ar=k.useMemo(()=>w3s(v,h==="advanced"||h==="visual"?A:a),[v,h,A,a]),Er=async()=>{Ee(!0),Se([]);try{const Xs=h==="advanced"||h==="visual"?A:a,{data:Ur,error:xn}=await H.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:n,bodyHtml:Xs,currentSubject:v}});if(xn)throw xn;const us=Ur==null?void 0:Ur.subjects;if(!Array.isArray(us)||us.length===0)throw new Error("No subjects returned");Se(us)}catch(Xs){const Ur=(Xs==null?void 0:Xs.message)||"Failed to generate subjects";Ur.includes("credits exhausted")||Ur.includes("402")?ue.error("AI credits exhausted. Please add credits to your workspace."):Ur.includes("Rate limit")||Ur.includes("429")?ue.error("Rate limit hit — try again in a moment."):ue.error(Ur)}finally{Ee(!1)}},Tr=Xs=>Xs?"$"+Number(Xs).toLocaleString("en-US"):"",Lr=()=>{if(ye.size===0){ue.error("Pick at least one listing first.");return}const Xs=et.filter(Hr=>ye.has(Hr.listing_key)),Ur=(Ft==null?void 0:Ft.subdomain_slug)||"",xn=Ur?`https://${Ur}.relevelup.com`:"https://relevelup.com",pr=`

Featured Listings

${Xs.map(Hr=>{var ut,kt;const aa=Array.isArray(Hr.photos)&&Hr.photos.length>0?typeof Hr.photos[0]=="string"?Hr.photos[0]:((ut=Hr.photos[0])==null?void 0:ut.MediaURL)||((kt=Hr.photos[0])==null?void 0:kt.url)||"":"",Na=`${xn}/listings/${Hr.listing_key}`,Je=Hr.bedrooms?`${Hr.bedrooms} bd`:"",Fe=Hr.bathrooms_total?`${Hr.bathrooms_total} ba`:"",We=Hr.living_area?`${Number(Hr.living_area).toLocaleString()} sqft`:"",He=[Je,Fe,We].filter(Boolean).join(" • "),bt=`${Hr.address||""}${Hr.city?", "+Hr.city:""}`;return`
${aa?`${bt}`:""}
${Tr(Hr.list_price)}
${bt}
${He}
`.trim()}).join(` `)}
`.trim();P(Hr=>(Hr||a||"")+` `+pr),m("visual"),ct(new Set),Te(!1),ue.success(`Added ${Xs.length} listing${Xs.length===1?"":"s"} to your newsletter.`)},$r=()=>Is({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}}"),kr=()=>lqe(v,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},d??null,(Nt==null?void 0:Nt.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}}"),Sr=()=>{if(ss){if(ve==="later"){if(!Re){ue.error("Pick a date and time to schedule.");return}const Xs=new Date(Re).getTime();if(Number.isNaN(Xs)||Xs{if(!(!ss||!i)){oe(!1),ie(!0),be({sent:0,failed:0,total:dt.length,currentName:"Preparing campaign…"});try{const Ur=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,xn=$r(),us=kr(),pr=ve==="later",{data:Hr,error:aa}=await H.from("email_campaigns").insert({user_id:c||i.id,name:`Newsletter: ${n}`,subject:us,body_html:xn,from_email:Ur,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:dt.length,status:pr?"scheduled":"draft",scheduled_at:pr?new Date(Re).toISOString():null}).select("id").single();if(aa)throw aa;be(Je=>({...Je,currentName:"Adding recipients…"}));const Na=dt.map(Je=>({campaign_id:Hr.id,contact_id:Je.id,email:Je.email,name:[Je.first_name,Je.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Je=0;Je({...He,sent:Math.min(Je+Fe.length,Na.length)}))}if(pr){const{error:Je}=await H.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Hr.id}});if(Je)throw Je;ue.success(`Newsletter scheduled for ${new Date(Re).toLocaleString()}.`)}else{const{error:Je}=await H.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Hr.id}});if(Je)throw Je;ue.success(`Sending to ${dt.length} contact${dt.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(Xs){console.error("Newsletter send failed:",Xs),ue.error(`Failed to send: ${Xs.message||"Unknown error"}`)}finally{ie(!1)}}},zn=Xs=>{Q(Ur=>{const xn=new Set(Ur);return xn.has(Xs)?xn.delete(Xs):xn.add(Xs),xn})};return e.jsxs(vs,{open:s,onOpenChange:Xs=>!ae&&t(Xs),children:[e.jsxs(ys,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"})," Send Newsletter"]})}),!yt&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border-2 border-destructive/40 bg-destructive/10 p-4 text-sm",children:[e.jsx(Hi,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx(G,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Subject"}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Er,disabled:Pe,title:"Generate subject lines with AI",children:[Pe?e.jsx(ls,{className:"h-3 w-3 animate-spin"}):e.jsx(jr,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(ke,{value:v,onChange:Xs=>j(Xs.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((Xs,Ur)=>e.jsxs("button",{type:"button",onClick:()=>{j(Xs),Se([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(jr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),Xs]},Ur))]}),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}}"})]})]}),ar.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(MO,{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:ar.map((Xs,Ur)=>e.jsx("li",{children:Xs},Ur))})]}),at&&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(Cn,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:"Pick from your live MLS listings and drop them into the email."})]}),e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>Te(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Editing"}),e.jsxs(Rn,{value:h,onValueChange:Xs=>m(Xs),children:[e.jsxs(Dn,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Xt,{value:"visual",children:[e.jsx(Ag,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Xt,{value:"light",children:[e.jsx(ln,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Xt,{value:"advanced",children:[e.jsx(Mb,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(as,{value:"visual",className:"mt-3",children:e.jsx(Cmt,{html:A,onChange:P})}),e.jsxs(as,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(ur,{value:b,onChange:Xs=>N(Xs.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(ur,{value:S,onChange:Xs=>T(Xs.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(as,{value:"advanced",className:"mt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(ur,{value:A,onChange:Xs=>P(Xs.target.value),rows:14,className:"font-mono text-xs"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Append my email signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d!=null&&d.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(br,{checked:D&&!!(d!=null&&d.email_signature),disabled:!(d!=null&&d.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(br,{checked:Oe,onCheckedChange:Me})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipients"}),e.jsxs(Rn,{value:x,onValueChange:Xs=>g(Xs),children:[e.jsxs(Dn,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Xt,{value:"all",children:[e.jsx(fr,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Xt,{value:"tags",children:[e.jsx(Ah,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Xt,{value:"smartlists",children:[e.jsx(hO,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Xt,{value:"individual",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(as,{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(as,{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(ti,{className:"h-40 rounded-lg border p-2",children:Ke.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."}):Ke.map(Xs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Ei,{checked:z.includes(Xs.id),onCheckedChange:Ur=>F(xn=>Ur?[...xn,Xs.id]:xn.filter(us=>us!==Xs.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:Xs.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:Xs.name})]},Xs.id))})]}),e.jsxs(as,{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(ti,{className:"h-40 rounded-lg border p-2",children:nt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):nt.map(Xs=>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:$===Xs.id,onChange:()=>X(Xs.id)}),e.jsx("span",{className:"text-sm",children:Xs.name})]},Xs.id))})]}),e.jsxs(as,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(ke,{placeholder:"Search contacts...",value:Y,onChange:Xs=>ne(Xs.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[K.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>Q(new Set),children:"Clear"})]}),e.jsxs(ti,{className:"h-48 rounded-lg border p-2",children:[lt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!lt&&Qt.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Qt.slice(0,200).map(Xs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Ei,{checked:K.has(Xs.id),onCheckedChange:()=>zn(Xs.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[Xs.first_name," ",Xs.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Xs.email})]})]},Xs.id)),Qt.length>200&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Showing first 200 — refine search to see more."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"})," ",dt.length," recipient",dt.length===1?"":"s"]}),yt&&e.jsxs(Ge,{variant:"outline",className:"gap-1 text-xs",children:["via Mass Email",o!=null&&o.reply_to_email?` (${o.reply_to_email})`:""]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Preview"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ce(Xs=>!Xs),children:de?e.jsxs(e.Fragment,{children:[e.jsx(am,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),de?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:fs,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)."]})]})]}),ae&&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 ",ge.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[ge.sent+ge.failed," / ",ge.total]})]}),e.jsx(ri,{value:ge.total?(ge.sent+ge.failed)/ge.total*100:0}),ge.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[ge.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(cn,{className:"h-4 w-4"})," When to send"]}),e.jsxs(Vb,{value:ve,onValueChange:Xs=>rt(Xs),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Qd,{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(Qd,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Bv,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),ve==="later"&&e.jsx(ke,{type:"datetime-local",value:Re,onChange:Xs=>Qe(Xs.target.value),className:"sm:ml-2 w-full sm:w-auto",min:new Date(Date.now()+5*6e4).toISOString().slice(0,16)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:ae,children:"Cancel"}),e.jsx(G,{onClick:Sr,disabled:!ss,children:ae?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):ve==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Bv,{className:"h-4 w-4 mr-1"}),"Schedule for ",dt.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",dt.length]})})]})]})]})]}),e.jsx(Yo,{open:me,onOpenChange:oe,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:ve==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Uo,{children:[ve==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[dt.length," contact",dt.length===1?"":"s"]}),ve==="later"&&Re?` for ${new Date(Re).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:hn,children:ve==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Bv,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",dt.length]})})]})]})}),e.jsx(vs,{open:ze,onOpenChange:Te,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 of your active listings. They'll be added as an email-safe grid linking to your lead site."}),Dt&&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…"]}),!Dt&&et.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No active listings found in your MLS feed."}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:et.map(Xs=>{var us,pr;const Ur=ye.has(Xs.listing_key),xn=Array.isArray(Xs.photos)&&Xs.photos.length>0?typeof Xs.photos[0]=="string"?Xs.photos[0]:((us=Xs.photos[0])==null?void 0:us.MediaURL)||((pr=Xs.photos[0])==null?void 0:pr.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{ct(Hr=>{const aa=new Set(Hr);return aa.has(Xs.listing_key)?aa.delete(Xs.listing_key):aa.size<6?aa.add(Xs.listing_key):ue.error("Max 6 listings per newsletter"),aa})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Ur?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[xn&&e.jsx("img",{src:xn,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:Xs.list_price?`$${Number(Xs.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Xs.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Xs.city,Xs.state?`, ${Xs.state}`:""]})]}),Ur&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Mn,{className:"h-4 w-4"})})]},Xs.listing_key)})})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>Te(!1),children:"Cancel"}),e.jsxs(G,{onClick:Lr,disabled:ye.size===0,children:["Insert ",ye.size>0?ye.size:""," listing",ye.size===1?"":"s"]})]})]})})]})}function j3s(){const{user:s}=As(),t=es(),[r,n]=k.useState("starters"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState(null),[h,m]=k.useState(null),{data:x,isLoading:g}=gt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:B,error:z}=await H.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(z)throw z;return B||[]}}),v=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),j=(x==null?void 0:x.filter(B=>B.user_id===(s==null?void 0:s.id)&&!B.is_template))??[],b=(x==null?void 0:x.filter(B=>B.user_id===(s==null?void 0:s.id)&&B.is_template))??[],N=(x==null?void 0:x.filter(B=>B.user_id!==(s==null?void 0:s.id)&&B.is_template&&(B.share_scope==="team"||B.share_scope==="brokerage"||B.share_scope==="global")))??[],S=(x==null?void 0:x.filter(B=>B.share_scope==="global"&&B.is_template))??[],T=r==="starters"?S:r==="mine"?j:r==="templates"?b:N.filter(B=>B.share_scope!=="global"),A=async B=>{if(!s)return;const{error:z}=await H.from("agent_custom_newsletters").insert({user_id:s.id,title:`${B.title} (Copy)`,description:B.description,html_content:B.html_content,is_template:!1,share_scope:"private"});if(z){ue.error(z.message);return}ue.success('Duplicated to "My Newsletters"'),v(),n("mine")},P=async B=>{const{error:z}=await H.from("agent_custom_newsletters").delete().eq("id",B);if(z){ue.error(z.message);return}ue.success("Deleted"),m(null),v()},D=B=>B.share_scope==="global"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(jr,{className:"h-3 w-3"}),"Starter"]}):B.share_scope==="brokerage"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Brokerage"]}):B.share_scope==="team"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fr,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Ge,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Kc,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(G,{variant:r==="starters"?"default":"outline",size:"sm",onClick:()=>n("starters"),className:"gap-1.5",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Starter Templates (",S.length,")"]}),e.jsxs(G,{variant:r==="mine"?"default":"outline",size:"sm",onClick:()=>n("mine"),children:["My Newsletters (",j.length,")"]}),e.jsxs(G,{variant:r==="templates"?"default":"outline",size:"sm",onClick:()=>n("templates"),children:["My Templates (",b.length,")"]}),e.jsxs(G,{variant:r==="shared"?"default":"outline",size:"sm",onClick:()=>n("shared"),children:["Shared with Me (",N.filter(B=>B.share_scope!=="global").length,")"]})]}),e.jsxs(G,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),g&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((B,z)=>e.jsx(Vs,{className:"h-48 w-full"},z))}),r==="starters"&&!g&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!g&&T.length===0&&e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),r==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),r==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),r==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),r==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!g&&T.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:T.map(B=>{const z=B.user_id===(s==null?void 0:s.id);return e.jsxs(Ne,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[B.thumbnail_url?e.jsx("img",{src:B.thumbnail_url,alt:B.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:`
${B.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[B.is_template&&e.jsx(Ge,{className:"bg-primary/90",children:"Template"}),D(B)]})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:B.title}),B.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:B.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Ss(new Date(B.updated_at||B.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(G,{size:"sm",onClick:()=>d(B),className:"flex-1 min-w-[80px]",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),z?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{o(B),i(!0)},children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(B),children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>m(B.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>A(B),children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},B.id)})}),e.jsx(u3s,{open:a,onOpenChange:i,initial:l,onSaved:v}),c&&e.jsx(oAe,{open:!!c,onOpenChange:B=>!B&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Yo,{open:!!h,onOpenChange:B=>!B&&m(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete this newsletter?"}),e.jsx(Uo,{children:"This cannot be undone."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>h&&P(h),children:"Delete"})]})]})})]})}function N3s(){const s=vr(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),[i,l]=k.useState(null),{data:o,isLoading:c}=gt({queryKey:["newsletters"],queryFn:async()=>{const{data:P,error:D}=await H.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(D)throw D;return P}}),{data:d}=gt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:P}=await H.from("newsletter_likes").select("newsletter_id");return P||[]}}),{data:h}=gt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:P}=await H.from("newsletter_comments").select("newsletter_id");return P||[]}}),{data:m}=gt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[P,D,B,z]=await Promise.all([H.from("newsletter_canva_links").select("newsletter_id"),H.from("newsletter_pdfs").select("newsletter_id"),H.from("newsletter_videos").select("newsletter_id"),H.from("newsletter_drive_links").select("newsletter_id")]);return{canva:P.data||[],pdfs:D.data||[],videos:B.data||[],drives:z.data||[]}}}),x=P=>(d==null?void 0:d.filter(D=>D.newsletter_id===P).length)||0,g=P=>(h==null?void 0:h.filter(D=>D.newsletter_id===P).length)||0,v=P=>{var D;return((D=m==null?void 0:m.canva)==null?void 0:D.filter(B=>B.newsletter_id===P).length)||0},j=P=>{var D;return((D=m==null?void 0:m.pdfs)==null?void 0:D.filter(B=>B.newsletter_id===P).length)||0},b=P=>{var D;return((D=m==null?void 0:m.videos)==null?void 0:D.filter(B=>B.newsletter_id===P).length)||0},N=P=>{var D;return((D=m==null?void 0:m.drives)==null?void 0:D.filter(B=>B.newsletter_id===P).length)||0},S=P=>v(P)+j(P)+b(P)+N(P),T=o==null?void 0:o.filter(P=>{var D;return P.title.toLowerCase().includes(t.toLowerCase())||((D=P.description)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))}),A=P=>{s(`/newsletters/${P}`)};return e.jsx(_s,{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(Rn,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"custom",children:"Build & Send"}),e.jsx(Xt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(as,{value:"custom",className:"mt-2",children:e.jsx(j3s,{})}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search newsletters...",value:t,onChange:P=>r(P.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Sf,{className:"h-4 w-4"})}),e.jsx(G,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(lm,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(T==null?void 0:T.length)||0," item",(T==null?void 0:T.length)!==1?"s":""," found"]}),c&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((P,D)=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-0",children:[e.jsx(Vs,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Vs,{className:"h-5 w-3/4"}),e.jsx(Vs,{className:"h-4 w-full"})]})]})},D))}),!c&&(T==null?void 0:T.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx(G,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&T&&T.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:T.map(P=>{const D=S(P.id),B=v(P.id),z=j(P.id),F=b(P.id);return n==="grid"?e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(P.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:P.preview_image_url?e.jsx("img",{src:P.preview_image_url,alt:P.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(ln,{className:"h-16 w-16"})})}),e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:P.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(P.publish_date),"MMM d, yyyy")]})]}),P.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:P.description.replace(/<[^>]*>/g,"")}),D>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[B>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(pl,{className:"h-3 w-3"})," ",B," Template",B>1?"s":""]}),z>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Xa,{className:"h-3 w-3"})," ",z," PDF",z>1?"s":""]}),F>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ho,{className:"h-3 w-3"})," ",F," Video",F>1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-1 border-t border-border/50",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mh,{className:"h-3 w-3"})," ",x(P.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{className:"h-3 w-3"})," ",g(P.id)]})]}),P.html_code&&e.jsxs(G,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:$=>{$.stopPropagation(),l(P)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},P.id):e.jsx(Ne,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(P.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:P.preview_image_url?e.jsx("img",{src:P.preview_image_url,alt:P.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(ln,{className:"h-10 w-10"})})}),e.jsxs(De,{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:P.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(P.publish_date),"MMM d, yyyy")]})]}),P.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:P.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(Mh,{className:"h-3 w-3"})," ",x(P.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{className:"h-3 w-3"})," ",g(P.id)]})]})]}),P.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(G,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:$=>{$.stopPropagation(),l(P)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},P.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(oAe,{open:!!i,onOpenChange:P=>!P&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function k3s({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(Ne,{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(De,{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 S3s(){const{id:s}=Xi(),t=vr(),{user:r}=As(),{toast:n}=Ea(),a=es(),{trackEngagement:i}=MP(),[l,o]=k.useState(""),[c,d]=k.useState(!1),{data:h,isLoading:m}=gt({queryKey:["newsletter",s],queryFn:async()=>{const{data:B,error:z}=await H.from("newsletter_content").select("*").eq("id",s).single();if(z)throw z;return B},enabled:!!s});k.useEffect(()=>{h&&i("newsletter",h.id,h.title,"view")},[h==null?void 0:h.id]);const{data:x}=gt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return B||[]},enabled:!!s}),{data:g}=gt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return B||[]},enabled:!!s}),{data:v}=gt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return B||[]},enabled:!!s}),{data:j}=gt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return B||[]},enabled:!!s}),{data:b}=gt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_likes").select("*").eq("newsletter_id",s);return B||[]},enabled:!!s}),{data:N}=gt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:B}=await H.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return B||[]},enabled:!!s}),S=b==null?void 0:b.some(B=>B.user_id===(r==null?void 0:r.id)),T=Lt({mutationFn:async()=>{S?await H.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",r==null?void 0:r.id):await H.from("newsletter_likes").insert({newsletter_id:s,user_id:r==null?void 0:r.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=Lt({mutationFn:async B=>{const{error:z}=await H.from("newsletter_comments").insert({newsletter_id:s,user_id:r==null?void 0:r.id,content:B});if(z)throw z},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),n({title:"Comment added"})}}),P=Lt({mutationFn:async B=>{const{error:z}=await H.from("newsletter_comments").delete().eq("id",B);if(z)throw z},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),n({title:"Comment deleted"})}}),D=B=>{if(B.includes("player.mediadelivery.net")||B.includes("iframe.mediadelivery.net")){const z=B.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(z)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${z[1]}/${z[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(B.includes("youtube.com")||B.includes("youtu.be")){const z=B.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(z)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${z[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:B,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Ho,{className:"h-4 w-4"})," Watch Video"]})};return m?e.jsx(_s,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-8 w-32"}),e.jsx(Vs,{className:"h-64 w-full"}),e.jsx(Vs,{className:"h-32 w-full"})]})}):h?e.jsx(_s,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(wa,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),h.preview_image_url&&e.jsx("img",{src:h.preview_image_url,alt:h.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:h.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:Ss(new Date(h.publish_date),"MMMM d, yyyy")})]}),h.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:h.description}}),e.jsx(k3s,{rows:h.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(DP,{resourceType:"newsletter",resourceId:h.id,resourceTitle:h.title}),e.jsxs(G,{variant:S?"default":"outline",size:"sm",onClick:()=>T.mutate(),children:[e.jsx(hi,{className:`h-4 w-4 mr-1 ${S?"fill-current":""}`}),(b==null?void 0:b.length)||0," ",(b==null?void 0:b.length)===1?"Like":"Likes"]}),h.html_code&&e.jsxs(G,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),h.html_code&&e.jsx(oAe,{open:c,onOpenChange:d,newsletterId:h.id,newsletterTitle:h.title,htmlCode:h.html_code}),j&&j.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(De,{className:"space-y-2",children:j.map(B=>e.jsxs("a",{href:B.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(pl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:B.title}),e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},B.id))})]}),x&&x.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(De,{className:"space-y-2",children:x.map(B=>e.jsxs("a",{href:B.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:B.title})]},B.id))})]}),g&&g.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(De,{className:"space-y-2",children:g.map(B=>e.jsxs("a",{href:B.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(ln,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:B.name}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]},B.id))})]}),v&&v.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Videos"})}),e.jsx(De,{className:"space-y-6",children:v.map(B=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:B.title}),D(B.video_url)]},B.id))})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg",children:["Comments (",(N==null?void 0:N.length)||0,")"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ur,{placeholder:"Write a comment...",value:l,onChange:B=>o(B.target.value),className:"flex-1"}),e.jsx(G,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:N==null?void 0:N.map(B=>{var z,F,$;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{children:((F=(z=B.profiles)==null?void 0:z.name)==null?void 0:F[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:(($=B.profiles)==null?void 0:$.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(B.created_at),"MMM d, yyyy")}),B.user_id===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>P.mutate(B.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:B.content})]})]},B.id)})})]})]})]})}):e.jsx(_s,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(G,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function C3s({rows:s,onChange:t}){const[r,n]=k.useState(null),a=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},i=d=>{t(s.filter((h,m)=>m!==d))},l=(d,h,m,x)=>{const g=[...s];g[d]={...g[d],columns:g[d].columns.map((v,j)=>j===h?{...v,[m]:x}:v)},t(g)},o=async(d,h,m)=>{var v;const x=(v=m.target.files)==null?void 0:v[0];if(!x)return;const g=`${d}-${h}`;n(g);try{const j=`content-blocks/${Date.now()}-${x.name}`,{error:b}=await H.storage.from("newsletter-content").upload(j,x);if(!b){const{data:N}=H.storage.from("newsletter-content").getPublicUrl(j);l(d,h,"image_url",N.publicUrl)}}finally{n(null)}},c=(d,h)=>{l(d,h,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:a,children:[e.jsx(Ws,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((d,h)=>e.jsxs(Ne,{className:"relative",children:[e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>i(h),children:e.jsx(_r,{className:"h-4 w-4"})}),e.jsxs(De,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",h+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:d.columns.map((m,x)=>{const g=`${h}-${x}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",x+1]}),m.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:m.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(h,x),children:e.jsx(_r,{className:"h-3 w-3"})})]}):e.jsxs("div",{children:[e.jsx(ke,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${g}`,onChange:v=>o(h,x,v)}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"w-full text-xs h-8",disabled:r===g,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${g}`,className:"cursor-pointer",children:r===g?"Uploading...":e.jsxs(e.Fragment,{children:[e.jsx(fl,{className:"h-3 w-3 mr-1"})," Image"]})})})]}),e.jsx(ke,{placeholder:"Title",value:m.title,onChange:v=>l(h,x,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(ur,{placeholder:"Description",value:m.description,onChange:v=>l(h,x,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},x)})})]})]},h))]})}function T3s(){const{toast:s}=Ea(),t=es(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=k.useState(null),[h,m]=k.useState(null),[x,g]=k.useState([]),[v,j]=k.useState([]),[b,N]=k.useState([]),[S,T]=k.useState([]),[A,P]=k.useState([]),[D,B]=k.useState(""),[z,F]=k.useState([]),[$,X]=k.useState(!1),{data:K,isLoading:Q}=gt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Ee,error:$e}=await H.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if($e)throw $e;return Ee}}),Y=Lt({mutationFn:async Ee=>{const{data:$e,error:Se}=await H.from("newsletter_content").insert({title:Ee.title,description:Ee.description||null,preview_image_url:Ee.preview_image_url,publish_date:Ee.publish_date,is_published:Ee.is_published,content_blocks:Ee.content_blocks,html_code:Ee.html_code}).select().single();if(Se)throw Se;return $e},onSuccess:async Ee=>{await ce(Ee.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Ee.is_published&&wes(Ee.title,Ee.id),me()},onError:Ee=>{s({title:"Error creating newsletter",description:Ee.message,variant:"destructive"})}}),ne=Lt({mutationFn:async Ee=>{const{error:$e}=await H.from("newsletter_content").update({title:Ee.title,description:Ee.description||null,preview_image_url:Ee.preview_image_url,publish_date:Ee.publish_date,is_published:Ee.is_published,content_blocks:Ee.content_blocks,html_code:Ee.html_code}).eq("id",Ee.id);if($e)throw $e;return Ee.id},onSuccess:async Ee=>{await ce(Ee),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),me()},onError:Ee=>{s({title:"Error updating newsletter",description:Ee.message,variant:"destructive"})}}),de=Lt({mutationFn:async Ee=>{const{error:$e}=await H.from("newsletter_content").delete().eq("id",Ee);if($e)throw $e},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Ee=>{s({title:"Error deleting newsletter",description:Ee.message,variant:"destructive"})}}),ce=async Ee=>{await H.from("newsletter_drive_links").delete().eq("newsletter_id",Ee),await H.from("newsletter_pdfs").delete().eq("newsletter_id",Ee),await H.from("newsletter_videos").delete().eq("newsletter_id",Ee),await H.from("newsletter_canva_links").delete().eq("newsletter_id",Ee);for(const $e of z){const Se=`${Ee}/${Date.now()}-${$e.file.name}`,{error:ze}=await H.storage.from("newsletter-content").upload(Se,$e.file);if(!ze){const{data:Te}=H.storage.from("newsletter-content").getPublicUrl(Se);v.push({name:$e.name,file_url:Te.publicUrl,file_size:$e.file.size,sort_order:v.length})}}x.length>0&&await H.from("newsletter_drive_links").insert(x.map(($e,Se)=>({newsletter_id:Ee,title:$e.title,drive_url:$e.drive_url,sort_order:Se}))),v.length>0&&await H.from("newsletter_pdfs").insert(v.map(($e,Se)=>({newsletter_id:Ee,name:$e.name,file_url:$e.file_url,file_size:$e.file_size||null,sort_order:Se}))),b.length>0&&await H.from("newsletter_videos").insert(b.map(($e,Se)=>({newsletter_id:Ee,title:$e.title,video_url:$e.video_url,sort_order:Se}))),S.length>0&&await H.from("newsletter_canva_links").insert(S.map(($e,Se)=>({newsletter_id:Ee,title:$e.title,canva_share_link:$e.canva_share_link,sort_order:Se})))},ae=async Ee=>{i(Ee),o({title:Ee.title,description:Ee.description||"",publish_date:Ss(new Date(Ee.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Ee.is_published}),m(Ee.preview_image_url),P(Ee.content_blocks||[]),B(Ee.html_code||"");const[$e,Se,ze,Te]=await Promise.all([H.from("newsletter_drive_links").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_pdfs").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_videos").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_canva_links").select("*").eq("newsletter_id",Ee.id).order("sort_order")]);g($e.data||[]),j(Se.data||[]),N(ze.data||[]),T(Te.data||[]),F([]),n(!0)},ie=async Ee=>{const[$e,Se,ze,Te]=await Promise.all([H.from("newsletter_drive_links").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_pdfs").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_videos").select("*").eq("newsletter_id",Ee.id).order("sort_order"),H.from("newsletter_canva_links").select("*").eq("newsletter_id",Ee.id).order("sort_order")]);i(null),o({title:`${Ee.title} (Copy)`,description:Ee.description||"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),m(Ee.preview_image_url),P(Ee.content_blocks||[]),B(Ee.html_code||""),g(($e.data||[]).map(({id:ye,...ct})=>ct)),j((Se.data||[]).map(({id:ye,...ct})=>ct)),N((ze.data||[]).map(({id:ye,...ct})=>ct)),T((Te.data||[]).map(({id:ye,...ct})=>ct)),F([]),n(!0)},me=()=>{n(!1),i(null),o({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),m(null),g([]),j([]),N([]),T([]),P([]),B(""),F([])},oe=async Ee=>{var Se;const $e=(Se=Ee.target.files)==null?void 0:Se[0];$e&&(d($e),m(URL.createObjectURL($e)))},ge=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}X(!0);let Ee=h;if(c){const $e=`previews/${Date.now()}-${c.name}`,{error:Se}=await H.storage.from("newsletter-content").upload($e,c);if(!Se){const{data:ze}=H.storage.from("newsletter-content").getPublicUrl($e);Ee=ze.publicUrl}}a?ne.mutate({id:a.id,...l,preview_image_url:Ee,content_blocks:A,html_code:D||null}):Y.mutate({...l,preview_image_url:Ee,content_blocks:A,html_code:D||null}),X(!1)},be=()=>g([...x,{title:"",drive_url:"",sort_order:x.length}]),Oe=()=>N([...b,{title:"",video_url:"",sort_order:b.length}]),Me=()=>T([...S,{title:"",canva_share_link:"",sort_order:S.length}]),Pe=Ee=>{const $e=Ee.target.files;if(!$e)return;const Se=Array.from($e).map(ze=>({file:ze,name:ze.name.replace(/\.[^/.]+$/,"")}));F([...z,...Se])};return e.jsx(_s,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(K==null?void 0:K.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(K==null?void 0:K.filter(Ee=>Ee.is_published).length)||0})})]})]}),e.jsxs(vs,{open:r,onOpenChange:Ee=>!Ee&&me(),children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx(Ws,{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(js,{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(he,{children:"Title *"}),e.jsx(ke,{value:l.title,onChange:Ee=>o({...l,title:Ee.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Publish Date"}),e.jsx(ke,{type:"datetime-local",value:l.publish_date,onChange:Ee=>o({...l,publish_date:Ee.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:l.description,onChange:Ee=>o({...l,description:Ee}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:h,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),m(null)},children:e.jsx(_r,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(ke,{type:"file",accept:"image/*",onChange:oe,className:"hidden",id:"preview-upload"}),e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(oa,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{checked:l.is_published,onCheckedChange:Ee=>o({...l,is_published:Ee})}),e.jsx(he,{children:"Published"})]}),e.jsx(C3s,{rows:A,onChange:P}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:D,onChange:Ee=>B(Ee.target.value),rows:10,placeholder:"...",className:"w-full font-mono text-xs rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Supports merge tags: ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{last_name}}"}),", ",e.jsx("code",{children:"{{full_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_email}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),"."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Me,children:[e.jsx(Ws,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),S.map((Ee,$e)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ke,{placeholder:"Link title",value:Ee.title,onChange:Se=>{const ze=[...S];ze[$e].title=Se.target.value,T(ze)},className:"w-1/3"}),e.jsx(ke,{placeholder:"Canva share link",value:Ee.canva_share_link,onChange:Se=>{const ze=[...S];ze[$e].canva_share_link=Se.target.value,T(ze)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>T(S.filter((Se,ze)=>ze!==$e)),children:e.jsx(_r,{className:"h-4 w-4"})})]},$e))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx(Ws,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),x.map((Ee,$e)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ke,{placeholder:"Link title",value:Ee.title,onChange:Se=>{const ze=[...x];ze[$e].title=Se.target.value,g(ze)},className:"w-1/3"}),e.jsx(ke,{placeholder:"Google Drive URL",value:Ee.drive_url,onChange:Se=>{const ze=[...x];ze[$e].drive_url=Se.target.value,g(ze)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>g(x.filter((Se,ze)=>ze!==$e)),children:e.jsx(_r,{className:"h-4 w-4"})})]},$e))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(ke,{type:"file",accept:".pdf",multiple:!0,onChange:Pe,className:"hidden",id:"pdf-upload"}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(oa,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),v.map((Ee,$e)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Ee.name}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(v.filter((Se,ze)=>ze!==$e)),children:e.jsx(_r,{className:"h-4 w-4"})})]},`existing-${$e}`)),z.map((Ee,$e)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:Ee.name,onChange:Se=>{const ze=[...z];ze[$e].name=Se.target.value,F(ze)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>F(z.filter((Se,ze)=>ze!==$e)),children:e.jsx(_r,{className:"h-4 w-4"})})]},`pending-${$e}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Oe,children:[e.jsx(Ws,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),b.map((Ee,$e)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ke,{placeholder:"Video title",value:Ee.title,onChange:Se=>{const ze=[...b];ze[$e].title=Se.target.value,N(ze)},className:"w-1/3"}),e.jsx(ke,{placeholder:"Video URL",value:Ee.video_url,onChange:Se=>{const ze=[...b];ze[$e].video_url=Se.target.value,N(ze)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>N(b.filter((Se,ze)=>ze!==$e)),children:e.jsx(_r,{className:"h-4 w-4"})})]},$e))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(G,{variant:"outline",onClick:me,children:"Cancel"}),e.jsx(G,{onClick:ge,disabled:$||Y.isPending||ne.isPending,children:$?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:Q?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(K==null?void 0:K.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):K==null?void 0:K.map(Ee=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ee.preview_image_url?e.jsx("img",{src:Ee.preview_image_url,alt:Ee.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(ln,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ee.title}),Ee.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ee.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(ft,{children:Ss(new Date(Ee.publish_date),"MMM d, yyyy")}),e.jsx(ft,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ee.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:Ee.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ae(Ee),title:"Edit",children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ie(Ee),title:"Duplicate",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&de.mutate(Ee.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Ee.id))})]})})})]})})}const cqe={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}};function E3s(){const{user:s}=As(),{toast:t}=Ea(),r=vr(),n=es(),[a,i]=k.useState(""),[l,o]=k.useState("popular"),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(!1),{data:b=[],isLoading:N}=gt({queryKey:["wishlist-items",l,v],queryFn:async()=>{let D=H.from("wishlist_items").select("*");v&&s&&(D=D.eq("user_id",s.id)),l==="latest"?D=D.order("created_at",{ascending:!1}):l==="popular"?D=D.order("vote_count",{ascending:!1}):l==="trending"&&(D=D.order("vote_count",{ascending:!1}));const{data:B,error:z}=await D;if(z)throw z;const F=[...new Set((B==null?void 0:B.map(de=>de.user_id))||[])],{data:$}=await H.from("profiles").select("id, name").in("id",F),X=new Map(($==null?void 0:$.map(de=>[de.id,de]))||[]);let K=[];if(s){const{data:de}=await H.from("wishlist_votes").select("item_id").eq("user_id",s.id);K=(de==null?void 0:de.map(ce=>ce.item_id))||[]}const Q=(B==null?void 0:B.map(de=>de.id))||[],{data:Y}=await H.from("wishlist_comments").select("item_id").in("item_id",Q),ne=new Map;return Y==null||Y.forEach(de=>{ne.set(de.item_id,(ne.get(de.item_id)||0)+1)}),B==null?void 0:B.map(de=>{const ce=X.get(de.user_id),ae=(ce==null?void 0:ce.name)||"Unknown";return{...de,user_name:ae,user_initials:ae.split(" ").map(ie=>ie[0]).join("").toUpperCase().slice(0,2),has_voted:K.includes(de.id),comment_count:ne.get(de.id)||0}})}}),S=Lt({mutationFn:async({title:D,description:B})=>{const{error:z}=await H.from("wishlist_items").insert({user_id:s.id,title:D,description:B});if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),m(""),g(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),T=Lt({mutationFn:async({itemId:D,hasVoted:B})=>{if(B){const{error:z}=await H.from("wishlist_votes").delete().eq("item_id",D).eq("user_id",s.id);if(z)throw z;return{itemId:D,wasAdded:!1}}else{const{error:z}=await H.from("wishlist_votes").insert({item_id:D,user_id:s.id});if(z)throw z;return{itemId:D,wasAdded:!0}}},onSuccess:async D=>{if(n.invalidateQueries({queryKey:["wishlist-items"]}),D!=null&&D.wasAdded){const B=b.find(F=>F.id===D.itemId),z=((B==null?void 0:B.vote_count)||0)+1;H.functions.invoke("wishlist-notify",{body:{itemId:D.itemId,voteCount:z}}).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())),P=()=>{if(!h.trim()||!x.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}S.mutate({title:h.trim(),description:x.trim()})};return e.jsx(_s,{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(Yj,{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(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(ys,{children:[e.jsx(js,{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(he,{htmlFor:"title",children:"Title"}),e.jsx(ke,{id:"title",placeholder:"Give your idea a clear title...",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:x,onChange:D=>g(D.target.value),rows:4})]}),e.jsx(G,{onClick:P,className:"w-full",disabled:S.isPending,children:S.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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search ideas...",value:a,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Rn,{value:l,onValueChange:D=>o(D),children:e.jsxs(Dn,{children:[e.jsx(Xt,{value:"popular",children:"Most Popular"}),e.jsx(Xt,{value:"latest",children:"Latest"}),e.jsx(Xt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(G,{variant:v?"default":"outline",size:"sm",onClick:()=>j(!v),children:v?"Show All Ideas":"My Ideas"})}),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"})}):A.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(Yj,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs(G,{onClick:()=>d(!0),children:[e.jsx(Ws,{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:B=>{B.stopPropagation(),T.mutate({itemId:D.id,hasVoted:D.has_voted||!1})},className:Bt("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(Fd,{className:Bt("h-4 w-4",D.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:D.vote_count})]}),e.jsx(vn,{className:"h-10 w-10 bg-primary/20",children:e.jsx(bn,{className:"bg-primary/20 text-primary text-sm font-medium",children:D.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:D.title}),e.jsx(Ge,{className:Bt("text-xs",cqe[D.status].color),children:cqe[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(bi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:D.comment_count})]})]})},D.id))})]})})}const dqe={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 A3s(){const{itemId:s}=Xi(),t=vr(),{user:r}=As(),{toast:n}=Ea(),a=es(),[i,l]=k.useState(""),{data:o=!1}=gt({queryKey:["user-is-admin",r==null?void 0:r.id],queryFn:async()=>{if(!r)return!1;const{data:b,error:N}=await H.from("user_roles").select("role").eq("user_id",r.id).eq("role","admin").maybeSingle();return!N&&!!b},enabled:!!r}),{data:c,isLoading:d}=gt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:b,error:N}=await H.from("wishlist_items").select("*").eq("id",s).single();if(N)throw N;const{data:S}=await H.from("profiles").select("name").eq("id",b.user_id).single();let T=!1;if(r){const{data:A}=await H.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",r.id).maybeSingle();T=!!A}return{...b,user_name:(S==null?void 0:S.name)||"Unknown",user_initials:((S==null?void 0:S.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:T}}}),{data:h=[],isLoading:m}=gt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:b,error:N}=await H.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(N)throw N;const S=[...new Set((b==null?void 0:b.map(P=>P.user_id))||[])],{data:T}=await H.from("profiles").select("id, name").in("id",S),A=new Map((T==null?void 0:T.map(P=>[P.id,P]))||[]);return b==null?void 0:b.map(P=>{const D=A.get(P.user_id),B=(D==null?void 0:D.name)||"Unknown";return{...P,user_name:B,user_initials:B.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2)}})}}),x=Lt({mutationFn:async b=>{if(b){const{error:N}=await H.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",r.id);if(N)throw N;return{wasAdded:!1}}else{const{error:N}=await H.from("wishlist_votes").insert({item_id:s,user_id:r.id});if(N)throw N;return{wasAdded:!0}}},onSuccess:async b=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),b!=null&&b.wasAdded&&c){const N=(c.vote_count||0)+1;H.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:N}}).catch(console.error)}},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),g=Lt({mutationFn:async b=>{const{error:N}=await H.from("wishlist_comments").insert({item_id:s,user_id:r.id,content:b});if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),v=Lt({mutationFn:async b=>{const{error:N}=await H.from("wishlist_comments").delete().eq("id",b);if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),n({title:"Comment deleted"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),j=()=>{i.trim()&&g.mutate(i.trim())};return d?e.jsx(_s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Vs,{className:"h-8 w-32 mb-6"}),e.jsx(Vs,{className:"h-48 w-full mb-6"}),e.jsx(Vs,{className:"h-32 w-full"})]})}):c?e.jsx(_s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>x.mutate(c.has_voted),className:Bt("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(Fd,{className:Bt("h-5 w-5",c.has_voted&&"fill-current")}),e.jsx("span",{className:"text-lg font-bold",children:c.vote_count}),e.jsx("span",{className:"text-xs",children:"votes"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:c.title}),e.jsx(Ge,{className:Bt("text-xs",dqe[c.status].color),children:dqe[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(vn,{className:"h-6 w-6",children:e.jsx(bn,{className:"bg-primary/20 text-primary text-xs",children:c.user_initials})}),e.jsx("span",{children:c.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(c.created_at).toLocaleDateString()})]})]})]})}),e.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",h.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(Whe,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx(G,{onClick:j,disabled:!i.trim()||g.isPending,size:"icon",className:"h-auto",children:g.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"})})]}),m?e.jsx("div",{className:"space-y-4",children:[1,2].map(b=>e.jsx(Vs,{className:"h-20 w-full"},b))}):h.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:h.map(b=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{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(zTe,{content:b.content,className:"text-sm text-foreground"})]}),(r==null?void 0:r.id)===b.user_id&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>v.mutate(b.id),children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id))})]})]})}):e.jsx(_s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(G,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const uqe={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"}},hqe=["open","under_review","planned","in_progress","launched","declined"];function M3s(){const{toast:s}=Ea(),t=vr(),r=es(),[n,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState(!1),[d,h]=k.useState(null),{data:m=[],isLoading:x}=gt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:N,error:S}=await H.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(S)throw S;const T=[...new Set((N==null?void 0:N.map(F=>F.user_id))||[])],{data:A}=await H.from("profiles").select("id, name, email").in("id",T),P=new Map((A==null?void 0:A.map(F=>[F.id,F]))||[]),D=(N==null?void 0:N.map(F=>F.id))||[],{data:B}=await H.from("wishlist_comments").select("item_id").in("item_id",D),z=new Map;return B==null||B.forEach(F=>{z.set(F.item_id,(z.get(F.item_id)||0)+1)}),N==null?void 0:N.map(F=>{const $=P.get(F.user_id);return{...F,user_name:($==null?void 0:$.name)||"Unknown",user_email:($==null?void 0:$.email)||"",comment_count:z.get(F.id)||0}})}}),g=Lt({mutationFn:async({itemId:N,status:S})=>{const{error:T}=await H.from("wishlist_items").update({status:S}).eq("id",N);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:N=>{s({title:"Error",description:N.message,variant:"destructive"})}}),v=Lt({mutationFn:async N=>{const{error:S}=await H.from("wishlist_items").delete().eq("id",N);if(S)throw S},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),h(null),s({title:"Item deleted!"})},onError:N=>{s({title:"Error",description:N.message,variant:"destructive"})}}),j=m.filter(N=>{const S=N.title.toLowerCase().includes(n.toLowerCase())||N.description.toLowerCase().includes(n.toLowerCase())||N.user_name.toLowerCase().includes(n.toLowerCase()),T=i==="all"||N.status===i;return S&&T}),b={total:m.length,open:m.filter(N=>N.status==="open").length,inProgress:m.filter(N=>N.status==="in_progress").length,launched:m.filter(N=>N.status==="launched").length,highVotes:m.filter(N=>N.vote_count>=10).length};return e.jsx(_s,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(wa,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search ideas, users...",value:n,onChange:N=>a(N.target.value),className:"pl-10"})]}),e.jsxs(zs,{value:i,onValueChange:N=>l(N),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Statuses"}),hqe.map(N=>e.jsx(mt,{value:N,children:uqe[N].label},N))]})]})]}),x?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(N=>e.jsx(Vs,{className:"h-16 w-full"},N))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[60px]",children:"Votes"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Tt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Bn,{children:j.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):j.map(N=>e.jsxs(qs,{className:Bt(N.vote_count>=10&&"bg-primary/5"),children:[e.jsx(ft,{children:e.jsx(Ge,{variant:N.vote_count>=10?"default":"secondary",children:N.vote_count})}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:N.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:N.description})]})}),e.jsx(ft,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:N.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.user_email})]})}),e.jsx(ft,{className:"hidden sm:table-cell",children:N.comment_count}),e.jsx(ft,{children:e.jsxs(zs,{value:N.status,onValueChange:S=>g.mutate({itemId:N.id,status:S}),children:[e.jsx(Os,{className:"w-[140px] h-8",children:e.jsx(Us,{})}),e.jsx(Fs,{children:hqe.map(S=>e.jsx(mt,{value:S,children:uqe[S].label},S))})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${N.id}`,"_blank"),children:e.jsx(Yr,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{h(N.id),c(!0)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},N.id))})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsx(js,{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(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:()=>d&&v.mutate(d),disabled:v.isPending,children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function I3s(){const{user:s}=As(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(null),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState(""),[B,z]=k.useState(!1),[F,$]=k.useState(""),[X,K]=k.useState("once"),[Q,Y]=k.useState([]),[ne,de]=k.useState([]),[ce,ae]=k.useState(!1),[ie,me]=k.useState(!1),[oe,ge]=k.useState([]),[be,Oe]=k.useState({total:0,dismissed:0});k.useEffect(()=>{Me()},[]);const Me=async()=>{const{data:it,error:Nt}=await H.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Nt?(ue.error("Failed to fetch briefs"),console.error(Nt)):r(it||[]),a(!1)},Pe=()=>{v(""),b(""),S(""),A(""),D(""),z(!1),$(new Date().toISOString().slice(0,16)),K("once"),Y([]),de([]),c(null)},Ee=()=>{Pe(),l(!0)},$e=async it=>{c(it),v(it.title),b(it.description||""),S(it.video_url||""),A(it.graphic_url||""),D(it.graphic_link_url||""),z(it.is_published),$(it.publish_date.slice(0,16)),K(it.show_frequency);const{data:Nt}=await H.from("levelup_brief_links").select("*").eq("brief_id",it.id).order("sort_order");Y((Nt==null?void 0:Nt.map(at=>({title:at.title,url:at.url})))||[]);const{data:Ft}=await H.from("levelup_brief_polls").select("*").eq("brief_id",it.id).order("sort_order");if(Ft){const at=[];for(const Ie of Ft){const{data:et}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",Ie.id).order("sort_order");at.push({question:Ie.question,poll_type:Ie.poll_type,options:(et==null?void 0:et.map(Dt=>Dt.option_text))||[]})}de(at)}l(!0)},Se=async it=>{var Ft;const Nt=(Ft=it.target.files)==null?void 0:Ft[0];if(Nt){ae(!0);try{const at=await H.functions.invoke("bunny-upload",{body:{action:"create",title:Nt.name.replace(/\.[^/.]+$/,"")}});if(at.error)throw at.error;const{videoId:Ie,libraryId:et}=at.data,Dt=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ie}});if(Dt.error)throw Dt.error;const{uploadUrl:Jt,apiKey:cs}=Dt.data,Ht=new XMLHttpRequest;await new Promise((Qt,yt)=>{Ht.upload.addEventListener("progress",ss=>{if(ss.lengthComputable){const Is=Math.round(ss.loaded/ss.total*100);console.log("Upload progress:",Is)}}),Ht.addEventListener("load",()=>{Ht.status>=200&&Ht.status<300?Qt():yt(new Error(`Upload failed with status ${Ht.status}`))}),Ht.addEventListener("error",()=>yt(new Error("Upload failed"))),Ht.open("PUT",Jt),Ht.setRequestHeader("AccessKey",cs),Ht.send(Nt)});const dt=`https://player.mediadelivery.net/embed/${et}/${Ie}`;S(dt),ue.success("Video uploaded successfully! It may take a few minutes to process.")}catch(at){console.error("Upload error:",at),ue.error("Failed to upload video")}finally{ae(!1)}}},ze=async()=>{if(!g.trim()){ue.error("Title is required");return}try{let it;if(o){const{error:Nt}=await H.from("levelup_briefs").update({title:g,description:j||null,video_url:N||null,graphic_url:T||null,graphic_link_url:P||null,is_published:B,publish_date:F,show_frequency:X}).eq("id",o.id);if(Nt)throw Nt;it=o.id,await H.from("levelup_brief_links").delete().eq("brief_id",it);const{data:Ft}=await H.from("levelup_brief_polls").select("id").eq("brief_id",it);if(Ft)for(const at of Ft)await H.from("levelup_brief_poll_options").delete().eq("poll_id",at.id);await H.from("levelup_brief_polls").delete().eq("brief_id",it)}else{const{data:Nt,error:Ft}=await H.from("levelup_briefs").insert({title:g,description:j||null,video_url:N||null,graphic_url:T||null,graphic_link_url:P||null,is_published:B,publish_date:F,show_frequency:X,created_by:s==null?void 0:s.id}).select().single();if(Ft)throw Ft;it=Nt.id}if(Q.length>0){const Nt=Q.map((Ft,at)=>({brief_id:it,title:Ft.title,url:Ft.url,sort_order:at}));await H.from("levelup_brief_links").insert(Nt)}for(let Nt=0;Nt0){const et=Ft.options.map((Dt,Jt)=>({poll_id:at.id,option_text:Dt,sort_order:Jt}));await H.from("levelup_brief_poll_options").insert(et)}}ue.success(o?"Brief updated":"Brief created"),l(!1),Pe(),Me()}catch(it){console.error("Error saving brief:",it),ue.error("Failed to save brief")}},Te=async it=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:Nt}=await H.from("levelup_briefs").delete().eq("id",it);if(Nt)throw Nt;ue.success("Brief deleted"),Me()}catch(Nt){console.error("Error deleting brief:",Nt),ue.error("Failed to delete brief")}},ye=async it=>{x(it);const{count:Nt}=await H.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",it.id),{count:Ft}=await H.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",it.id).not("dismissed_at","is",null);Oe({total:Nt||0,dismissed:Ft||0});const{data:at}=await H.from("levelup_brief_polls").select("*").eq("brief_id",it.id).order("sort_order");if(at){const Ie=[];for(const et of at){const{data:Dt}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",et.id).order("sort_order"),{data:Jt}=await H.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",et.id),cs=[...new Set((Jt==null?void 0:Jt.map(ss=>ss.user_id))||[])];let Ht={};if(cs.length>0){const{data:ss}=await H.from("profiles").select("id, name, email").in("id",cs);ss&&ss.forEach(Is=>{Ht[Is.id]=Is.name||Is.email||"Unknown"})}const dt=(Jt||[]).map(ss=>({optionId:ss.option_id,userName:Ht[ss.user_id]||"Unknown",userId:ss.user_id})),Qt={};let yt=0;Dt&&Dt.forEach(ss=>{const Is=(Jt==null?void 0:Jt.filter(fs=>fs.option_id===ss.id).length)||0;Qt[ss.id]=Is,yt+=Is}),Ie.push({...et,options:Dt||[],results:Qt,respondents:dt,totalResponses:et.poll_type==="single"?new Set(Jt==null?void 0:Jt.map(ss=>ss.user_id)).size:yt})}ge(Ie)}h(!0)},ct=()=>{Y([...Q,{title:"",url:""}])},ve=(it,Nt,Ft)=>{const at=[...Q];at[it][Nt]=Ft,Y(at)},rt=it=>{Y(Q.filter((Nt,Ft)=>Ft!==it))},Re=()=>{de([...ne,{question:"",poll_type:"single",options:["",""]}])},Qe=(it,Nt)=>{const Ft=[...ne];Ft[it].question=Nt,de(Ft)},Ke=(it,Nt)=>{const Ft=[...ne];Ft[it].poll_type=Nt,de(Ft)},Ce=it=>{const Nt=[...ne];Nt[it].options.push(""),de(Nt)},nt=(it,Nt,Ft)=>{const at=[...ne];at[it].options[Nt]=Ft,de(at)},$t=(it,Nt)=>{const Ft=[...ne];Ft[it].options=Ft[it].options.filter((at,Ie)=>Ie!==Nt),de(Ft)},lt=it=>{de(ne.filter((Nt,Ft)=>Ft!==it))};return e.jsxs(_s,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(G,{onClick:Ee,children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Frequency"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:n?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(it=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:it.title}),e.jsx(ft,{children:e.jsx(Ge,{variant:it.is_published?"default":"secondary",children:it.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"capitalize",children:it.show_frequency.replace("_"," ")}),e.jsx(ft,{children:Ss(new Date(it.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ye(it),children:e.jsx(ao,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>$e(it),children:e.jsx(nd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Te(it.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},it.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(js,{children:e.jsx(bs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(Rn,{defaultValue:"content",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-4",children:[e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"media",children:"Media"}),e.jsx(Xt,{value:"links",children:"Links"}),e.jsx(Xt,{value:"polls",children:"Polls"})]}),e.jsxs(as,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Title *"}),e.jsx(ke,{value:g,onChange:it=>v(it.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:j,onChange:it=>b(it),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Publish Date"}),e.jsx(ke,{type:"datetime-local",value:F,onChange:it=>$(it.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Show Frequency"}),e.jsxs(zs,{value:X,onValueChange:K,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"once",children:"Once (until dismissed)"}),e.jsx(mt,{value:"every_login",children:"Every login"}),e.jsx(mt,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(br,{checked:B,onCheckedChange:z}),e.jsx(he,{children:"Publish immediately"})]})]}),e.jsxs(as,{value:"media",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Video (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ke,{type:"file",accept:"video/*",onChange:Se,disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Or paste embed URL"}),e.jsx(ke,{value:N,onChange:it=>S(it.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),N&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:N,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ke,{type:"file",accept:"image/*",onChange:async it=>{var Ft;const Nt=(Ft=it.target.files)==null?void 0:Ft[0];if(Nt){me(!0);try{const at=Nt.name.split(".").pop(),Ie=`brief-graphics/${Date.now()}.${at}`,{error:et}=await H.storage.from("banner-images").upload(Ie,Nt,{upsert:!0});if(et)throw et;const{data:Dt}=H.storage.from("banner-images").getPublicUrl(Ie);A(Dt.publicUrl),ue.success("Image uploaded!")}catch(at){console.error(at),ue.error("Failed to upload image")}finally{me(!1)}}},disabled:ie})}),ie&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Or paste Image URL"}),e.jsx(ke,{value:T,onChange:it=>A(it.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Click-through Link (optional)"}),e.jsx(ke,{value:P,onChange:it=>D(it.target.value),placeholder:"https://example.com/landing-page"})]}),T&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:T,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(as,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Quick Links"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ct,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),Q.map((it,Nt)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(ke,{value:it.title,onChange:Ft=>ve(Nt,"title",Ft.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(ke,{value:it.url,onChange:Ft=>ve(Nt,"url",Ft.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>rt(Nt),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]},Nt)),Q.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(as,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Polls"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:Re,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),ne.map((it,Nt)=>e.jsx(Ne,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ke,{value:it.question,onChange:Ft=>Qe(Nt,Ft.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(zs,{value:it.poll_type,onValueChange:Ft=>Ke(Nt,Ft),children:[e.jsx(Os,{className:"w-32",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"single",children:"Single"}),e.jsx(mt,{value:"multi",children:"Multi-select"})]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>lt(Nt),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[it.options.map((Ft,at)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:Ft,onChange:Ie=>nt(Nt,at,Ie.target.value),placeholder:`Option ${at+1}`}),it.options.length>2&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>$t(Nt,at),children:e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"})})]},at)),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Ce(Nt),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Nt)),ne.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:ze,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(vs,{open:d,onOpenChange:h,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:be.total})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:be.dismissed})})]})]}),oe.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),oe.map(it=>e.jsxs(Ne,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:it.question}),e.jsx("div",{className:"space-y-2",children:it.options.map(Nt=>{const Ft=it.results[Nt.id]||0,at=it.totalResponses>0?Math.round(Ft/it.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:Nt.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[Ft," (",at,"%)"]})]}),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:`${at}%`}})}),Ft>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(it.respondents||[]).filter(Ie=>Ie.optionId===Nt.id).map((Ie,et)=>e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:Ie.userName},et))})]},Nt.id)})})]},it.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const P3s=()=>{const{user:s}=As(),{toast:t}=Ea(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=k.useState(null),[m,x]=k.useState(""),{data:g=[],isLoading:v}=gt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:P,error:D}=await H.from("additional_services").select("*").order("publish_date",{ascending:!1});if(D)throw D;return P}}),j=Lt({mutationFn:async P=>{let D=P.existingImageUrl;if(P.image){const z=P.image.name.split(".").pop(),F=`${Date.now()}-${Math.random().toString(36).substring(7)}.${z}`,{error:$}=await H.storage.from("service-images").upload(F,P.image);if($)throw $;const{data:X}=H.storage.from("service-images").getPublicUrl(F);D=X.publicUrl}const B={name:P.item.name,description:P.item.description||null,preview_image_url:D,signup_link_url:P.item.signup_link_url,publish_date:P.item.publish_date?new Date(P.item.publish_date).toISOString():new Date().toISOString(),is_published:P.item.is_published,created_by:s==null?void 0:s.id};if(P.itemId){const{error:z}=await H.from("additional_services").update(B).eq("id",P.itemId);if(z)throw z}else{const{error:z}=await H.from("additional_services").insert(B);if(z)throw z}},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),N()},onError:P=>{t({title:"Error saving service",description:P.message,variant:"destructive"})}}),b=Lt({mutationFn:async P=>{const{error:D}=await H.from("additional_services").delete().eq("id",P);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:P=>{t({title:"Error deleting service",description:P.message,variant:"destructive"})}}),N=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),x(""),l(null)},S=P=>{l(P),c({name:P.name,description:P.description||"",signup_link_url:P.signup_link_url,publish_date:P.publish_date?new Date(P.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:P.is_published}),x(P.preview_image_url||""),a(!0)},T=P=>{var B;const D=(B=P.target.files)==null?void 0:B[0];D&&(h(D),x(URL.createObjectURL(D)))},A=P=>{if(P.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}j.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(_s,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:g.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:g.filter(P=>P.is_published).length})})]})]}),e.jsxs(vs,{open:n,onOpenChange:P=>{a(P),P||N()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{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(he,{htmlFor:"name",children:"Name *"}),e.jsx(ke,{id:"name",value:o.name,onChange:P=>c({...o,name:P.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(y0,{content:o.description,onChange:P=>c({...o,description:P}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(ke,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:P=>c({...o,signup_link_url:P.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ke,{id:"publish_date",type:"date",value:o.publish_date,onChange:P=>c({...o,publish_date:P.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(br,{id:"is_published",checked:o.is_published,onCheckedChange:P=>c({...o,is_published:P})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),x("")},children:e.jsx(_r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(fl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ke,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:j.isPending,children:j.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:v?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):g.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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Signup Link"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:g.map(P=>e.jsxs(qs,{children:[e.jsx(ft,{children:P.preview_image_url?e.jsx("img",{src:P.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(fl,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(ft,{className:"font-medium",children:P.name}),e.jsx(ft,{children:e.jsxs("a",{href:P.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(ft,{children:new Date(P.publish_date).toLocaleDateString()}),e.jsx(ft,{children:e.jsx(Ge,{variant:P.is_published?"default":"secondary",children:P.is_published?"Published":"Draft"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S(P),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&b.mutate(P.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},P.id))})]})})})]})})};function L3s(){const{toast:s}=Ea(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:b,error:N}=await H.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(N)throw N;r(b.coupons||[])}catch(b){console.error("Error fetching coupons:",b),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},x=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const b={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?b.percent_off=parseFloat(d.percentOff):(b.amount_off=Math.round(parseFloat(d.amountOff)*100),b.currency="usd"),d.duration==="repeating"&&(b.duration_in_months=parseInt(d.durationInMonths));const{data:N,error:S}=await H.functions.invoke("stripe-manage-coupons",{body:b});if(S)throw S;s({title:"Success",description:"Coupon created successfully"}),c(!1),h({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),m()}catch(b){console.error("Error creating coupon:",b),s({title:"Error",description:b.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},g=async b=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:N}=await H.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:b}});if(N)throw N;s({title:"Success",description:"Coupon deleted successfully"}),m()}catch(N){console.error("Error deleting coupon:",N),s({title:"Error",description:N.message||"Failed to delete coupon",variant:"destructive"})}},v=b=>b.percent_off?`${b.percent_off}% off`:b.amount_off?`$${(b.amount_off/100).toFixed(2)} off`:"N/A",j=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(_s,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Create New Coupon"}),e.jsx(Fr,{children:"Create a discount coupon that can be applied to subscriptions"})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Promotion Code (what users will type)"}),e.jsx(ke,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:b=>h({...d,promotionCode:b.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Coupon Name (internal label)"}),e.jsx(ke,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:b=>h({...d,name:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Discount Type"}),e.jsxs(zs,{value:d.discountType,onValueChange:b=>{const N=b==="amount"&&d.duration==="forever"?"once":d.duration;h({...d,discountType:b,duration:N})},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(F3,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(mt,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(_l,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:b=>h({...d,percentOff:b.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ke,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:b=>h({...d,amountOff:b.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Duration"}),e.jsxs(zs,{value:d.duration,onValueChange:b=>h({...d,duration:b}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"once",children:"Once (first payment only)"}),e.jsx(mt,{value:"repeating",children:"Multiple months"}),e.jsxs(mt,{value:"forever",disabled:d.discountType==="amount",children:["Forever ",d.discountType==="amount"&&"(% discounts only)"]})]})]}),d.discountType==="amount"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),d.duration==="repeating"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Number of Months"}),e.jsx(ke,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:b=>h({...d,durationInMonths:b.target.value})})]}),e.jsx(G,{onClick:x,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Active Coupons"}),e.jsx(Nr,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Promo Code"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Redemptions"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:t.map(b=>{var N;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-mono font-medium",children:((N=b.promotion_codes)==null?void 0:N.length)>0?b.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(ft,{children:b.name||"-"}),e.jsx(ft,{children:v(b)}),e.jsx(ft,{children:j(b)}),e.jsx(ft,{children:b.times_redeemed}),e.jsx(ft,{children:e.jsx(Ge,{variant:b.valid?"default":"secondary",children:b.valid?"Active":"Inactive"})}),e.jsx(ft,{className:"text-right",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>g(b.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})})]},b.id)})})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"How to Use Coupons"})}),e.jsxs(De,{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 f_e={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 D3s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),[l,o]=k.useState(null),{data:c,isLoading:d,refetch:h}=gt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await H.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(S)throw S;return N}}),{data:m}=gt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await H.from("brokerages").select("*").order("name");if(S)throw S;return await Promise.all((N||[]).map(async A=>{const{data:P}=await H.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:D}=await H.from("user_roles").select("user_id").eq("role","brokerage_manager"),B=(D==null?void 0:D.map($=>$.user_id))||[],z=(P==null?void 0:P.filter($=>B.includes($.id)))||[],F=(P==null?void 0:P.length)||0;return{...A,managers:z,agentCount:F}}))}}),{data:x}=gt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await H.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(S)throw S;return N}}),g=N=>{if(N.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(N.brokerage_id&&!N.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(N.is_trial&&N.trial_expires_at)return new Date(N.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(N.subscription_status==="active"||N.subscription_status==="trialing"){const S=f_e[N.subscription_product_id];return{status:(S==null?void 0:S.name)||"Active",badge:N.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return N.subscription_status==="canceled"||N.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},v=c==null?void 0:c.filter(N=>{var T,A;if(!(((T=N.name)==null?void 0:T.toLowerCase().includes(s.toLowerCase()))||((A=N.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const P=N.subscription_source||"platform";if(a==="platform"&&P==="local_move_website"||a==="local_move_website"&&P!=="local_move_website")return!1}switch(g(N),r){case"active":return N.subscription_status==="active";case"trialing":return N.subscription_status==="trialing"||N.is_trial&&new Date(N.trial_expires_at)>new Date;case"grandfathered":return N.is_grandfathered;case"brokerage":return N.brokerage_id&&!N.subscription_product_id&&!N.is_grandfathered;case"expired":return N.subscription_status==="canceled"||N.subscription_status==="past_due"||N.is_trial&&new Date(N.trial_expires_at)<=new Date;case"none":return!N.subscription_status||N.subscription_status==="none";default:return!0}}),j={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(N=>N.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(N=>N.subscription_status==="trialing"||N.is_trial&&new Date(N.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(N=>N.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(N=>N.brokerage_id&&!N.subscription_product_id&&!N.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(N=>N.subscription_status==="active"&&N.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(N=>N.subscription_status==="active"&&(N.subscription_product_id==="prod_Tc08MupgoVySDG"||N.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},b=N=>{window.open(`https://dashboard.stripe.com/customers/${N}`,"_blank")};return e.jsx(_s,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(G,{onClick:()=>h(),variant:"outline",size:"sm",children:[e.jsx(Di,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{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:j.totalUsers})]})}),e.jsx(Ne,{className:"border-green-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gx,{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:j.activeSubscriptions})]})}),e.jsx(Ne,{className:"border-blue-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{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:j.trials})]})}),e.jsx(Ne,{className:"border-purple-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nm,{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:j.grandfathered})]})}),e.jsx(Ne,{className:"border-orange-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:j.brokerageMembers})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yv,{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:j.individualSubscribers})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:j.brokerageSubscribers})]})})]}),e.jsxs(Rn,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"users",children:"All Users"}),e.jsx(Xt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Xt,{value:"websites",className:"gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Website Subscriptions",x&&x.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:x.length})]})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:s,onChange:N=>t(N.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:a,onValueChange:N=>i(N),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Source"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Sources"}),e.jsx(mt,{value:"platform",children:"Platform"}),e.jsx(mt,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(zs,{value:r,onValueChange:N=>n(N),children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Statuses"}),e.jsx(mt,{value:"active",children:"Active Subscriptions"}),e.jsx(mt,{value:"trialing",children:"Trials"}),e.jsx(mt,{value:"grandfathered",children:"Grandfathered"}),e.jsx(mt,{value:"brokerage",children:"Brokerage Members"}),e.jsx(mt,{value:"expired",children:"Expired/Canceled"}),e.jsx(mt,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Plan"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"End Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:d?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(v==null?void 0:v.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):v==null?void 0:v.map(N=>{var A,P;const S=g(N),T=f_e[N.subscription_product_id];return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.email})]})}),e.jsx(ft,{children:e.jsx(Ge,{variant:S.variant,children:S.badge})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm",children:N.is_grandfathered?"Legacy Access":N.brokerage_id&&!N.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||S.status})}),e.jsx(ft,{children:(A=N.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:N.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ft,{children:N.subscription_end_date?e.jsx("span",{className:"text-sm",children:Ss(new Date(N.subscription_end_date),"MMM d, yyyy")}):N.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Ss(new Date(N.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[N.stripe_customer_id&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.stripe_customer_id),children:e.jsx(Yr,{className:"h-4 w-4"})}),e.jsxs(vs,{children:[e.jsx(Ni,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",onClick:()=>o(N),children:"Details"})}),e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Subscription Details"}),e.jsxs(Fr,{children:[N.name," (",N.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(Ge,{variant:S.variant,className:"mt-1",children:S.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:N.is_grandfathered?"Grandfathered (Legacy)":N.brokerage_id&&!N.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||"None"})]}),N.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((P=N.brokerages)==null?void 0:P.name)||"Unknown"})]}),N.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:Ss(new Date(N.subscription_end_date),"MMMM d, yyyy")})]}),N.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:Ss(new Date(N.trial_expires_at),"MMMM d, yyyy")})]}),N.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:N.stripe_customer_id})]})]}),N.stripe_customer_id&&e.jsxs(G,{className:"w-full",onClick:()=>b(N.stripe_customer_id),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},N.id)})})]})})})]}),e.jsx(as,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:m==null?void 0:m.map(N=>{var T,A;const S=(T=N.managers)==null?void 0:T.some(P=>P.subscription_status==="active"&&(P.subscription_product_id==="prod_Tc08MupgoVySDG"||P.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Sa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:N.name}),e.jsxs(Nr,{children:[N.agentCount," agents"]})]})]}),e.jsx(Ge,{variant:S?"default":"outline",children:S?"Active Subscription":"No Active Subscription"})]})}),e.jsx(De,{children:((A=N.managers)==null?void 0:A.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),N.managers.map(P=>{const D=f_e[P.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:P.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P.email})]}),e.jsx("div",{className:"text-right",children:D?e.jsxs("div",{children:[e.jsx(Ge,{variant:"default",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.price})]}):e.jsx(Ge,{variant:"outline",children:"No Subscription"})})]},P.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},N.id)})})}),e.jsx(as,{value:"websites",className:"space-y-4",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(gc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Nr,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Setup Fee"}),e.jsx(Tt,{children:"Monthly"}),e.jsx(Tt,{children:"Next Renewal"}),e.jsx(Tt,{children:"Started"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:x?x.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):x.map(N=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.agent_email})]})}),e.jsx(ft,{children:e.jsx(Ge,{variant:N.status==="active"?"default":N.status==="canceled"?"destructive":"outline",children:N.status})}),e.jsx(ft,{children:N.setup_fee_paid?e.jsxs(Ge,{variant:"secondary",children:["Paid · $",(N.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Ge,{variant:"outline",children:"Unpaid"})}),e.jsxs(ft,{className:"font-medium",children:["$",(N.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(ft,{children:N.current_period_end?e.jsx("span",{className:"text-sm",children:Ss(new Date(N.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm",children:Ss(new Date(N.created_at),"MMM d, yyyy")})}),e.jsx(ft,{className:"text-right",children:N.stripe_customer_id&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.stripe_customer_id),children:e.jsx(Yr,{className:"h-4 w-4"})})})]},N.id)):e.jsx(qs,{children:e.jsx(ft,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function R3s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:j}=await H.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(j)throw j;t(v||[]);const b=(v==null?void 0:v.filter(T=>T.status==="qualified").length)||0,N=(v==null?void 0:v.filter(T=>T.status==="pending").length)||0,S=(v==null?void 0:v.filter(T=>T.status==="cancelled").length)||0;d({total:(v==null?void 0:v.length)||0,qualified:b,pending:N,cancelled:S,totalDiscounts:b*25})}catch(v){console.error("Error fetching referrals:",v),ue.error("Failed to load referrals")}finally{n(!1)}},m=async()=>{try{ue.loading("Processing qualifications...");const{error:v}=await H.functions.invoke("process-referral-qualifications");if(v)throw v;ue.dismiss(),ue.success("Qualifications processed successfully"),h()}catch(v){ue.dismiss(),console.error("Error processing qualifications:",v),ue.error("Failed to process qualifications")}},x=s.filter(v=>{var N,S,T,A,P,D;const j=((S=(N=v.referrer_brokerage)==null?void 0:N.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((A=(T=v.referred_brokerage)==null?void 0:T.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((D=(P=v.referred_user)==null?void 0:P.email)==null?void 0:D.toLowerCase().includes(a.toLowerCase())),b=l==="all"||v.status===l;return j&&b}),g=v=>{switch(v){case"qualified":return e.jsxs(Ge,{className:"bg-green-100 text-green-800",children:[e.jsx(mi,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Ge,{variant:"secondary",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Mc,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Ge,{children:v})}};return e.jsx(_s,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(G,{onClick:m,variant:"outline",children:[e.jsx(Di,{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(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{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(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mi,{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(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{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(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mc,{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(Ne,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_l,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"All Referrals"}),e.jsx(Nr,{children:"View and manage all referral relationships"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by brokerage or email...",value:a,onChange:v=>i(v.target.value),className:"pl-10"})]}),e.jsxs(zs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Statuses"}),e.jsx(mt,{value:"pending",children:"Pending"}),e.jsx(mt,{value:"qualified",children:"Qualified"}),e.jsx(mt,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Referrer"}),e.jsx(Tt,{children:"Referred"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Qualified Date"}),e.jsx(Tt,{children:"Discount"})]})}),e.jsx(Bn,{children:x.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):x.map(v=>{var j,b,N,S;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:((j=v.referrer_brokerage)==null?void 0:j.name)||"Unknown"}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{children:((b=v.referred_brokerage)==null?void 0:b.name)||((N=v.referred_user)==null?void 0:N.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(S=v.referred_user)==null?void 0:S.email})]})}),e.jsx(ft,{children:Ss(new Date(v.signup_date),"MMM d, yyyy")}),e.jsx(ft,{children:g(v.status)}),e.jsx(ft,{children:v.qualified_date?Ss(new Date(v.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(ft,{children:v.discount_applied?e.jsx(Ge,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},v.id)})})]})]})]})]})})}const p_e=[{value:"add_agent",label:"Add Agent"},{value:"share_resource",label:"Share Resource"},{value:"post_community",label:"Post in Community"},{value:"register_event",label:"Register for Event"},{value:"view_template",label:"View Template"},{value:"watch_academy",label:"Watch Academy Video"},{value:"use_toolbox",label:"Use Toolbox"},{value:"launch_app",label:"Launch App"},{value:"add_contact",label:"Add Contact"},{value:"add_plan",label:"Add Touchpoint Plan"},{value:"create_video",label:"Create Video"},{value:"complete_touch",label:"Complete Touch"},{value:"add_transaction",label:"Add Transaction"},{value:"add_listing",label:"Add Listing"},{value:"schedule_popby",label:"Schedule Pop-by"}],O3s=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function F3s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:S,error:T}=await H.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(T)throw T;t(S||[])}catch(S){console.error("Error fetching checklist items:",S),ue.error("Failed to load checklist items")}finally{n(!1)}},m=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},x=S=>{o(S),d({title:S.title,description:S.description||"",action_type:S.action_type,target_role:S.target_role,is_active:S.is_active}),i(!0)},g=async()=>{if(!c.title.trim()){ue.error("Title is required");return}try{if(l){const{error:S}=await H.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(S)throw S;ue.success("Checklist item updated")}else{const S=s.filter(A=>A.target_role===c.target_role).reduce((A,P)=>Math.max(A,P.sort_order),-1),{error:T}=await H.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:S+1});if(T)throw T;ue.success("Checklist item created")}i(!1),h()}catch(S){console.error("Error saving checklist item:",S),ue.error("Failed to save checklist item")}},v=async S=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:T}=await H.from("onboarding_checklist_items").delete().eq("id",S);if(T)throw T;ue.success("Checklist item deleted"),h()}catch(T){console.error("Error deleting checklist item:",T),ue.error("Failed to delete checklist item")}},j=async S=>{try{const{error:T}=await H.from("onboarding_checklist_items").update({is_active:!S.is_active}).eq("id",S.id);if(T)throw T;ue.success(S.is_active?"Item deactivated":"Item activated"),h()}catch(T){console.error("Error toggling item:",T),ue.error("Failed to update item")}},b=s.filter(S=>S.target_role==="brokerage_manager"),N=s.filter(S=>S.target_role==="agent");return e.jsxs(_s,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(G,{onClick:m,className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(De,{children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:b.map((S,T)=>{var A;return e.jsxs(qs,{children:[e.jsx(ft,{className:"text-muted-foreground",children:T+1}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:S.title}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:S.description})]})}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",children:((A=p_e.find(P=>P.value===S.action_type))==null?void 0:A.label)||S.action_type})}),e.jsx(ft,{children:e.jsx(br,{checked:S.is_active,onCheckedChange:()=>j(S)})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(S),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},S.id)})})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(De,{children:N.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:N.map((S,T)=>{var A;return e.jsxs(qs,{children:[e.jsx(ft,{className:"text-muted-foreground",children:T+1}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:S.title}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:S.description})]})}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",children:((A=p_e.find(P=>P.value===S.action_type))==null?void 0:A.label)||S.action_type})}),e.jsx(ft,{children:e.jsx(br,{checked:S.is_active,onCheckedChange:()=>j(S)})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(S),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},S.id)})})]})})]})]}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{children:[e.jsx(js,{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(he,{htmlFor:"title",children:"Title *"}),e.jsx(ke,{id:"title",value:c.title,onChange:S=>d({...c,title:S.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",value:c.description,onChange:S=>d({...c,description:S.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Target Role"}),e.jsxs(zs,{value:c.target_role,onValueChange:S=>d({...c,target_role:S}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:O3s.map(S=>e.jsx(mt,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Action Type"}),e.jsxs(zs,{value:c.action_type,onValueChange:S=>d({...c,action_type:S}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:p_e.map(S=>e.jsx(mt,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"is_active",checked:c.is_active,onCheckedChange:S=>d({...c,is_active:S})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(G,{onClick:g,children:l?"Save Changes":"Create Item"})]})]})})]})}function B3s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("name"),[l,o]=k.useState("asc"),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState(""),{data:b}=gt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:$,error:X}=await H.from("brokerages").select("id, name").order("name");if(X)throw X;return $}}),N=async $=>{let K=[],Q=0,Y=!0;for(;Y;){const{data:ne,error:de}=await $(Q,Q+1e3-1);if(de)throw de;ne&&ne.length>0?(K=[...K,...ne],Q+=1e3,Y=ne.length===1e3):Y=!1}return K},{data:S,isLoading:T}=gt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const $=await N(($e,Se)=>H.from("profiles").select("id, name, email, brokerage_id, created_at").range($e,Se)),{data:X}=await H.from("brokerages").select("id, name"),K=new Map((X==null?void 0:X.map($e=>[$e.id,$e.name]))||[]),[{data:Q},{data:Y},{data:ne},{data:de},{data:ce},{data:ae},{data:ie}]=await Promise.all([H.rpc("get_admin_contact_counts"),H.rpc("get_admin_video_counts"),H.rpc("get_admin_popby_counts"),H.rpc("get_admin_listing_counts"),H.rpc("get_admin_deal_counts"),H.rpc("get_admin_portal_counts"),H.rpc("get_admin_sendable_card_counts")]),me=new Map;Q==null||Q.forEach($e=>me.set($e.owner_user_id,$e.contact_count));const oe=new Map;Y==null||Y.forEach($e=>oe.set($e.owner_user_id,$e.video_count));const ge=new Map;ne==null||ne.forEach($e=>ge.set($e.owner_user_id,$e.popby_count));const be=new Map;de==null||de.forEach($e=>be.set($e.agent_id,$e.listing_count));const Oe=new Map;ce==null||ce.forEach($e=>Oe.set($e.owner_user_id,$e.deal_count));const Me=new Map;ae==null||ae.forEach($e=>Me.set($e.owner_user_id,{total:$e.portal_count,active:$e.active_portal_count}));const Pe=new Map;return ie==null||ie.forEach($e=>Pe.set($e.owner_user_id,{total:$e.card_count,sent:$e.sent_card_count,views:$e.total_card_views})),$.map($e=>{const Se=Me.get($e.id),ze=Pe.get($e.id);return{id:$e.id,name:$e.name||"Unknown",email:$e.email||"",brokerage_id:$e.brokerage_id,brokerage_name:$e.brokerage_id&&K.get($e.brokerage_id)||null,contact_count:me.get($e.id)||0,video_count:oe.get($e.id)||0,popby_count:ge.get($e.id)||0,listing_count:be.get($e.id)||0,deal_count:Oe.get($e.id)||0,portal_count:(Se==null?void 0:Se.total)||0,active_portal_count:(Se==null?void 0:Se.active)||0,card_count:(ze==null?void 0:ze.total)||0,sent_card_count:(ze==null?void 0:ze.sent)||0,total_card_views:(ze==null?void 0:ze.views)||0,created_at:$e.created_at}})}}),A=k.useMemo(()=>{if(!S)return[];let $=S.filter(X=>{const K=s.toLowerCase(),Q=!s||X.name.toLowerCase().includes(K)||X.email.toLowerCase().includes(K),Y=r==="all"||r==="none"&&!X.brokerage_id||X.brokerage_id===r,ne=parseInt(c)||0,de=parseInt(h)||0,ce=parseInt(x)||0,ae=parseInt(v)||0,ie=X.contact_count>=ne&&X.video_count>=de&&X.popby_count>=ce&&X.listing_count>=ae;return Q&&Y&&ie});return $.sort((X,K)=>{let Q=0;return a==="name"?Q=X.name.localeCompare(K.name):Q=X[a]-K[a],l==="asc"?Q:-Q}),$},[S,s,r,a,l,c,h,x,v]),P=$=>{a===$?o(l==="asc"?"desc":"asc"):(i($),o("desc"))},D=()=>{const $=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],X=A.map(de=>[de.name,de.email,de.brokerage_name||"None",de.contact_count,de.video_count,de.popby_count,de.listing_count,de.deal_count,`${de.portal_count} (${de.active_portal_count})`,de.card_count,de.sent_card_count,de.total_card_views]),K=[$.join(","),...X.map(de=>de.map(ce=>`"${ce}"`).join(","))].join(` `),Q=new Blob([K],{type:"text/csv"}),Y=URL.createObjectURL(Q),ne=document.createElement("a");ne.href=Y,ne.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,ne.click(),URL.revokeObjectURL(Y)},B=k.useMemo(()=>A.length?A.reduce(($,X)=>({contacts:$.contacts+X.contact_count,videos:$.videos+X.video_count,popbys:$.popbys+X.popby_count,listings:$.listings+X.listing_count,deals:$.deals+X.deal_count,portals:$.portals+X.portal_count,activePortals:$.activePortals+X.active_portal_count,cards:$.cards+X.card_count,sentCards:$.sentCards+X.sent_card_count,cardViews:$.cardViews+X.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]),z=k.useMemo(()=>A.length?{portals:A.filter($=>$.portal_count>0).length,cards:A.filter($=>$.card_count>0).length}:{portals:0,cards:0},[A]),F=({field:$,children:X})=>e.jsx(Tt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>P($),children:e.jsxs("div",{className:"flex items-center gap-1",children:[X,e.jsx(Rd,{className:`h-3 w-3 ${a===$?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(A_,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Ne,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zv,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(De,{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:z.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:B.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:B.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(Ne,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(De,{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:z.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:B.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:B.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:B.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Nr,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:D,children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(De,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:s,onChange:$=>t($.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(zs,{value:r,onValueChange:n,children:[e.jsxs(Os,{children:[e.jsx(Sa,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Us,{placeholder:"Brokerage"})]}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Brokerages"}),e.jsx(mt,{value:"none",children:"No Brokerage"}),b==null?void 0:b.map($=>e.jsx(mt,{value:$.id,children:$.name},$.id))]})]})}),e.jsx("div",{children:e.jsx(ke,{type:"number",placeholder:"Min contacts",value:c,onChange:$=>d($.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ke,{type:"number",placeholder:"Min videos",value:h,onChange:$=>m($.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ke,{type:"number",placeholder:"Min popbys",value:x,onChange:$=>g($.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:B.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:B.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:B.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:B.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:B.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:B.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:B.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),T?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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(F,{field:"name",children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(F,{field:"contact_count",children:"Contacts"}),e.jsx(F,{field:"video_count",children:"Videos"}),e.jsx(F,{field:"popby_count",children:"Popbys"}),e.jsx(F,{field:"listing_count",children:"Listings"}),e.jsx(F,{field:"deal_count",children:"Deals"}),e.jsx(F,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zv,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(F,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qs,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(Bn,{children:A.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map($=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:$.name}),e.jsx(ft,{className:"text-muted-foreground",children:$.email}),e.jsx(ft,{children:$.brokerage_name?e.jsx(Ge,{variant:"secondary",children:$.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.contact_count>0?"default":"outline",children:$.contact_count})}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.video_count>0?"default":"outline",children:$.video_count})}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.popby_count>0?"default":"outline",children:$.popby_count})}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.listing_count>0?"default":"outline",children:$.listing_count})}),e.jsx(ft,{children:e.jsx(Ge,{variant:$.deal_count>0?"default":"outline",children:$.deal_count})}),e.jsx(ft,{children:$.portal_count>0?e.jsxs(hc,{children:[e.jsx(mc,{children:e.jsxs(Ge,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[$.portal_count,$.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",$.active_portal_count," active)"]})]})}),e.jsxs(Wl,{children:[e.jsxs("p",{children:[$.portal_count," total portals"]}),e.jsxs("p",{children:[$.active_portal_count," currently active"]})]})]}):e.jsx(Ge,{variant:"outline",children:"0"})}),e.jsx(ft,{children:$.card_count>0?e.jsxs(hc,{children:[e.jsx(mc,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:$.card_count}),$.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Zr,{className:"h-3 w-3"}),$.sent_card_count]}),$.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(jn,{className:"h-3 w-3"}),$.total_card_views]})]})}),e.jsxs(Wl,{children:[e.jsxs("p",{children:[$.card_count," cards created"]}),e.jsxs("p",{children:[$.sent_card_count," sent"]}),e.jsxs("p",{children:[$.total_card_views," total views"]})]})]}):e.jsx(Ge,{variant:"outline",children:"0"})})]},$.id))})]})})]})]})]})})}function z3s(){Ea(),es();const[s,t]=k.useState("user-analytics"),{data:r}=gt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:g,error:v}=await H.from("feature_flags").select("*").order("key");if(v)throw v;return g}}),{data:n,isLoading:a}=gt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:g,error:v}=await H.from("relationship_types").select("*").order("sort_order");if(v)throw v;return g}}),{data:i,isLoading:l}=gt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:g,error:v}=await H.from("action_types").select("*").order("sort_order");if(v)throw v;return g}}),{data:o,isLoading:c}=gt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:g,error:v}=await H.from("action_scripts").select("*, action_type:action_types(*)");if(v)throw v;return g}}),{data:d,isLoading:h}=gt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:g,error:v}=await H.from("touchpoint_plans").select("*").order("name");if(v)throw v;return g}}),{data:m,isLoading:x}=gt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:g,error:v}=await H.from("popby_items").select("*").is("owner_user_id",null).order("name");if(v)throw v;return g}});return e.jsx(_s,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(Rn,{value:s,onValueChange:t,children:[e.jsxs(Dn,{className:"grid w-full grid-cols-9",children:[e.jsxs(Xt,{value:"user-analytics",className:"gap-2",children:[e.jsx(ao,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Xt,{value:"relationship-types",className:"gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Xt,{value:"action-types",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Xt,{value:"scripts",className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Xt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Nh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Xt,{value:"plans",className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Xt,{value:"popbys",className:"gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Xt,{value:"settings",className:"gap-2",children:[e.jsx(lo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Xt,{value:"feature-flags",className:"gap-2",children:[e.jsx(e_,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(as,{value:"user-analytics",className:"mt-6",children:e.jsx(B3s,{})}),e.jsx(as,{value:"relationship-types",className:"mt-6",children:e.jsx($3s,{types:n||[],isLoading:a})}),e.jsx(as,{value:"action-types",className:"mt-6",children:e.jsx(U3s,{types:i||[],isLoading:l})}),e.jsx(as,{value:"scripts",className:"mt-6",children:e.jsx(q3s,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(as,{value:"video-scripts",className:"mt-6",children:e.jsx(W3s,{})}),e.jsx(as,{value:"plans",className:"mt-6",children:e.jsx(V3s,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:h})}),e.jsx(as,{value:"popbys",className:"mt-6",children:e.jsx(G3s,{items:m||[],isLoading:x})}),e.jsx(as,{value:"settings",className:"mt-6",children:e.jsx(K3s,{})}),e.jsx(as,{value:"feature-flags",className:"mt-6",children:e.jsx(H3s,{flags:r||[]})})]})]})})}function $3s({types:s,isLoading:t}){const{toast:r}=Ea(),n=es(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Lt({mutationFn:async h=>{if(h.id){const{error:m}=await H.from("relationship_types").update({name:h.name,description:h.description,icon:h.icon}).eq("id",h.id);if(m)throw m}else{const{error:m}=await H.from("relationship_types").insert([{name:h.name,description:h.description,icon:h.icon,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await H.from("relationship_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Relationship Types"}),e.jsx(Nr,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-12"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(h=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx(Su,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(ft,{className:"font-medium",children:h.name}),e.jsx(ft,{className:"text-muted-foreground",children:h.description}),e.jsx(ft,{children:e.jsx(br,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(ft,{children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"icon",children:"Icon"}),e.jsx(ke,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function U3s({types:s,isLoading:t}){const{toast:r}=Ea(),n=es(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Lt({mutationFn:async h=>{if(h.id){const{error:m}=await H.from("action_types").update({name:h.name,description:h.description,icon:h.icon,color:h.color}).eq("id",h.id);if(m)throw m}else{const{error:m}=await H.from("action_types").insert([{name:h.name,description:h.description,icon:h.icon,color:h.color,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await H.from("action_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Action Types"}),e.jsx(Nr,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Color"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(h=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:h.name}),e.jsx(ft,{className:"text-muted-foreground",children:h.description}),e.jsx(ft,{children:h.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:h.color}})}),e.jsx(ft,{children:e.jsx(br,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(ft,{children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon"),color:m.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"icon",children:"Icon"}),e.jsx(ke,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"color",children:"Color"}),e.jsx(ke,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function q3s({scripts:s,actionTypes:t,isLoading:r}){const{toast:n}=Ea(),a=es(),[i,l]=k.useState(null),[o,c]=k.useState(!1),d=Lt({mutationFn:async m=>{if(m.id){const{error:x}=await H.from("action_scripts").update({title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:m.active}).eq("id",m.id);if(x)throw x}else{const{error:x}=await H.from("action_scripts").insert([{title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:!0}]);if(x)throw x}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),n({title:"Saved successfully"})},onError:m=>{n({title:"Error",description:m.message,variant:"destructive"})}}),h=Lt({mutationFn:async m=>{const{error:x}=await H.from("action_scripts").delete().eq("id",m);if(x)throw x},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),n({title:"Deleted successfully"})}});return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Script Library"}),e.jsx(Nr,{children:"Create and manage scripts for each action type"})]}),e.jsxs(G,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(m=>{var x;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:m.title}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",children:((x=m.action_type)==null?void 0:x.name)||"Unknown"})}),e.jsx(ft,{className:"text-muted-foreground",children:m.tone}),e.jsx(ft,{children:e.jsx(Ge,{variant:m.active?"default":"secondary",children:m.active?"Active":"Inactive"})}),e.jsxs(ft,{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{l(m),c(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h.mutate(m.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]},m.id)})})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(bs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const x=new FormData(m.currentTarget);d.mutate({id:i==null?void 0:i.id,title:x.get("title"),action_type_id:x.get("action_type_id"),tone:x.get("tone"),script_body:x.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(ke,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(zs,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select action type"})}),e.jsx(Fs,{children:t.map(m=>e.jsx(mt,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(ke,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_body",children:"Script Body"}),e.jsx(ur,{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(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function V3s({plans:s,actionTypes:t,scripts:r,isLoading:n}){const{toast:a}=Ea(),i=es(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,g]=k.useState(!1),[v,j]=k.useState(null),[b,N]=k.useState(null),{data:S}=gt({queryKey:["plan-items",h],queryFn:async()=>{if(!h)return[];const{data:F,error:$}=await H.from("touchpoint_plan_items").select("*").eq("plan_id",h).order("month_number");if($)throw $;return F},enabled:!!h}),T=Lt({mutationFn:async F=>{if(F.id){const{error:$}=await H.from("touchpoint_plans").update({name:F.name,description:F.description,active:F.active}).eq("id",F.id);if($)throw $}else{const{error:$}=await H.from("touchpoint_plans").insert([{name:F.name,description:F.description,active:!0}]);if($)throw $}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),A=Lt({mutationFn:async F=>{if(F.id){const{error:$}=await H.from("touchpoint_plan_items").update({action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}).eq("id",F.id);if($)throw $}else{const{error:$}=await H.from("touchpoint_plan_items").insert([{plan_id:F.plan_id,month_number:F.month_number,action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}]);if($)throw $}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",h]}),a({title:"Item saved"})}}),P=Lt({mutationFn:async F=>{const{error:$}=await H.from("touchpoint_plan_items").delete().eq("id",F);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",h]})}}),D=Lt({mutationFn:async F=>{const{data:$,error:X}=await H.from("action_scripts").insert([{...F,active:!0}]).select().single();if(X)throw X;return $},onSuccess:async F=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),v&&await A.mutateAsync({id:v.itemId,plan_id:h,month_number:v.month,action_type_id:v.actionTypeId,default_script_id:F.id}),g(!1),j(null),a({title:"Script created and assigned"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),B=(F,$,X)=>{j({month:F,actionTypeId:$,itemId:X}),g(!0)},z=F=>r.find($=>$.id===F);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Touchpoint Plans"}),e.jsx(Nr,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(G,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(De,{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(F=>e.jsxs(Ne,{className:`cursor-pointer transition-colors ${h===F.id?"border-primary":""}`,onClick:()=>m(F.id),children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:F.name}),e.jsx(G,{variant:"ghost",size:"icon",onClick:$=>{$.stopPropagation(),o(F),d(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:F.description}),e.jsx(Ge,{variant:F.active?"default":"secondary",className:"mt-2",children:F.active?"Active":"Inactive"})]})]},F.id))})})]}),h&&e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Plan Schedule"}),e.jsx(Nr,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(F,$)=>$+1).map(F=>{const $=S==null?void 0:S.find(Q=>Q.month_number===F),X=$!=null&&$.default_script_id?z($.default_script_id):null,K=r.filter(Q=>Q.action_type_id===($==null?void 0:$.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 ",F]}),e.jsxs(zs,{value:($==null?void 0:$.action_type_id)||"none",onValueChange:Q=>{Q==="none"&&$?P.mutate($.id):Q!=="none"&&A.mutate({id:$==null?void 0:$.id,plan_id:h,month_number:F,action_type_id:Q,default_script_id:null})},children:[e.jsx(Os,{className:"w-40",children:e.jsx(Us,{placeholder:"No action"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No action"}),t.filter(Q=>Q.active).map(Q=>e.jsx(mt,{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))]})]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(zs,{value:$.default_script_id||"none",onValueChange:Q=>{N(null),A.mutate({id:$.id,default_script_id:Q==="none"?null:Q})},children:[e.jsx(Os,{className:"w-56",children:e.jsx(Us,{placeholder:"Select script"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No default script"}),K.map(Q=>e.jsxs(mt,{value:Q.id,children:[Q.title," ",Q.tone&&`(${Q.tone})`]},Q.id))]})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>B(F,$.action_type_id,$.id),children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"}),"New Script"]}),X&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N((b==null?void 0:b.id)===X.id?null:X),children:(b==null?void 0:b.id)===X.id?"Hide":"Preview"})]})]}),b&&($==null?void 0:$.default_script_id)===b.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ge,{variant:"outline",children:b.title}),b.tone&&e.jsx(Ge,{variant:"secondary",children:b.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:b.script_body})]})]},F)})})})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsxs(bs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const $=new FormData(F.currentTarget);T.mutate({id:l==null?void 0:l.id,name:$.get("name"),description:$.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:T.isPending,children:[T.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(vs,{open:x,onOpenChange:g,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Create New Script"}),e.jsxs(Fr,{children:["Create a script for Month ",v==null?void 0:v.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const $=new FormData(F.currentTarget);D.mutate({title:$.get("title"),action_type_id:v.actionTypeId,tone:$.get("tone"),script_body:$.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_title",children:"Title"}),e.jsx(ke,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_tone",children:"Tone"}),e.jsx(ke,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_body",children:"Script Body"}),e.jsx(ur,{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(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:D.isPending,children:[D.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function H3s({flags:s}){const{toast:t}=Ea(),r=es(),n=async(a,i)=>{const{error:l}=await H.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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Feature Flags"}),e.jsx(Nr,{children:"Control which features are enabled for members"})]}),e.jsx(De,{children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Flag"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Notes"}),e.jsx(Tt,{children:"Last Updated"})]})}),e.jsx(Bn,{children:s.map(a=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-mono text-sm",children:a.key}),e.jsx(ft,{children:e.jsx(br,{checked:a.enabled,onCheckedChange:i=>n(a,{enabled:i})})}),e.jsx(ft,{children:e.jsx(ke,{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(ft,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function G3s({items:s,isLoading:t}){const{toast:r}=Ea(),n=es(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Lt({mutationFn:async m=>{if(m.id){const{error:x}=await H.from("popby_items").update({name:m.name,description:m.description}).eq("id",m.id);if(x)throw x}else{const{error:x}=await H.from("popby_items").insert([{name:m.name,description:m.description,owner_user_id:null}]);if(x)throw x}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:m=>{r({title:"Error",description:m.message,variant:"destructive"})}}),d=async m=>{await H.from("popby_items").update({is_active:!m.is_active}).eq("id",m.id),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]})},h=async m=>{await H.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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Popby Ideas"}),e.jsx(Nr,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(De,{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(li,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(m=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:m.name}),e.jsx(ft,{className:"text-muted-foreground",children:m.description}),e.jsx(ft,{children:e.jsx(br,{checked:m.is_active,onCheckedChange:()=>d(m)})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(m),o(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h(m.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},m.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const x=new FormData(m.currentTarget);c.mutate({id:a==null?void 0:a.id,name:x.get("name"),description:x.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function W3s(){var g;const{toast:s}=Ea(),t=es(),[r,n]=k.useState(null),[a,i]=k.useState(!1),{data:l,isLoading:o}=gt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:v,error:j}=await H.from("video_script_categories").select("*").order("sort_order");if(j)throw j;return v}}),{data:c,isLoading:d}=gt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:v,error:j}=await H.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(j)throw j;return v}}),h=Lt({mutationFn:async v=>{var j,b;if(v.id){const{error:N}=await H.from("video_scripts").update({title:v.title,script_text:v.script_text,category_id:v.category_id,tags:((j=v.tags)==null?void 0:j.split(",").map(S=>S.trim()).filter(Boolean))||[]}).eq("id",v.id);if(N)throw N}else{const{error:N}=await H.from("video_scripts").insert([{title:v.title,script_text:v.script_text,category_id:v.category_id||null,tags:((b=v.tags)==null?void 0:b.split(",").map(S=>S.trim()).filter(Boolean))||[]}]);if(N)throw N}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),n(null),s({title:"Video script saved!"})},onError:v=>s({title:"Error",description:v.message,variant:"destructive"})}),m=async v=>{await H.from("video_scripts").update({is_active:!v.is_active}).eq("id",v.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},x=async v=>{confirm("Delete this video script?")&&(await H.from("video_scripts").delete().eq("id",v),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Video Scripts"}),e.jsx(Nr,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(G,{onClick:()=>{n(null),i(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(De,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Bn,{children:c==null?void 0:c.map(v=>{var j;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:v.title}),e.jsx(ft,{className:"text-muted-foreground",children:((j=v.category)==null?void 0:j.name)||"Uncategorized"}),e.jsx(ft,{children:e.jsx(br,{checked:v.is_active,onCheckedChange:()=>m(v)})}),e.jsxs(ft,{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{n(v),i(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})]},v.id)})})]})}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(bs,{children:[r?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault();const j=new FormData(v.currentTarget);h.mutate({id:r==null?void 0:r.id,title:j.get("title"),script_text:j.get("script_text"),category_id:j.get("category_id")||null,tags:j.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(ke,{id:"title",name:"title",defaultValue:r==null?void 0:r.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"category_id",children:"Category"}),e.jsxs(zs,{name:"category_id",defaultValue:(r==null?void 0:r.category_id)||"",children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:l==null?void 0:l.map(v=>e.jsx(mt,{value:v.id,children:v.name},v.id))})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_text",children:"Script Text"}),e.jsx(ur,{id:"script_text",name:"script_text",defaultValue:r==null?void 0:r.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(ke,{id:"tags",name:"tags",defaultValue:((g=r==null?void 0:r.tags)==null?void 0:g.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(on,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:h.isPending,children:[h.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function K3s(){const{toast:s}=Ea(),[t,r]=k.useState(""),[n,a]=k.useState(!0),[i,l]=k.useState(!1);k.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await H.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 H.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(Ne,{children:e.jsx(De,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(ja,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Nr,{children:"Configure the map feature for popbys"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(ke,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>r(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs(G,{onClick:o,disabled:i,children:[i&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Ge,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const Y3s=()=>{const[s,t]=k.useState(""),[r,n]=k.useState("grid"),a=vr(),{data:i=[],isLoading:l}=gt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await H.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var h;return c.name.toLowerCase().includes(s.toLowerCase())||((h=c.description)==null?void 0:h.toLowerCase().includes(s.toLowerCase()))});return e.jsx(_s,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>n("grid"),className:"rounded-full",children:e.jsx(Sf,{className:"h-4 w-4"})}),e.jsx(G,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>n("list"),className:"rounded-full",children:e.jsx(lm,{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(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(Vs,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Vs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Vs,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx(G,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(jr,{className:"h-8 w-8"})})}),e.jsxs(De,{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:H8(c.description)})]})]},c.id))})]})})},Z3s=()=>{const{serviceId:s}=Xi(),t=vr(),{data:r,isLoading:n}=gt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await H.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return n?e.jsx(_s,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Vs,{className:"h-8 w-48"}),e.jsx(Vs,{className:"h-64 w-full rounded-lg"}),e.jsx(Vs,{className:"h-24 w-full"})]})}):r?e.jsx(_s,{title:r.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(Ne,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:r.preview_image_url?e.jsx("img",{src:r.preview_image_url,alt:r.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(jr,{className:"h-16 w-16"})})})}),e.jsx(Ne,{children:e.jsxs(De,{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(rn,{className:"h-4 w-4 mr-1"}),"Published ",Ss(new Date(r.publish_date),"MMMM d, yyyy")]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:r.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(G,{size:"lg",className:"gap-2",onClick:()=>window.open(r.signup_link_url,"_blank"),children:[e.jsx(Yr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(_s,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(G,{onClick:()=>t("/additional-services"),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},nR=[{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 X3s(){const[s,t]=k.useState(nR[0].id),r=nR.find(n=>n.id===s)||nR[0];return e.jsx(_s,{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(XA,{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(zs,{value:s,onValueChange:t,children:[e.jsx(Os,{className:"w-full",children:e.jsx(Us,{placeholder:"Select a tool"})}),e.jsx(Fs,{children:nR.map(n=>e.jsx(mt,{value:n.id,children:n.name},n.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Rn,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Dn,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:nR.map(n=>e.jsx(Xt,{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 mqe="agent-os-onboarding-completed",VU=[{icon:Gv,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:Xu,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:fr,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:pd,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:li,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:ao,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"]}],Q3s=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(0),[a,i]=k.useState(!1);k.useEffect(()=>{if(!localStorage.getItem(mqe)){const v=setTimeout(()=>t(!0),500);return()=>clearTimeout(v)}},[]);const l=()=>{r{n(r+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(mqe,"true"),t(!1)},d=VU[r],h=d.icon,m=r===VU.length-1,x=g=>{g||c(),t(g)};return e.jsx(vs,{open:s,onOpenChange:x,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(h,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),r===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(jr,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(js,{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(Fr,{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((g,v)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+v*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(Hn,{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:g})]},v))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:VU.map((g,v)=>e.jsx("button",{onClick:()=>{v!==r&&(i(!0),setTimeout(()=>{n(v),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${v===r?"w-8 bg-gradient-to-r "+d.bgGradient:v{const{user:s}=As();return gt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(r)throw r;return t},enabled:!!s})},e5s=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async({contactId:r,days:n})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Hl(new Date,n);await H.from("contact_snoozes").delete().eq("contact_id",r);const{error:i}=await H.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"]}),nn({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:r=>{nn({title:"Error snoozing contact",description:r.message,variant:"destructive"})}})},t5s=()=>{const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("contact_snoozes").delete().eq("contact_id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),nn({title:"Snooze cancelled"})},onError:t=>{nn({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},s5s=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function Sge({open:s,onOpenChange:t,contactId:r,contactName:n}){const[a,i]=k.useState(null),l=e5s(),o=async()=>{a&&(await l.mutateAsync({contactId:r,days:a}),i(null),t(!1))},c=d=>Ss(Hl(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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Fr,{children:["Postpone the next scheduled touch for ",n,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:s5s.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Bt("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(rn,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const r5s={Crown:nm,FileText:ln,Users:fr,Globe:gc,Star:Qn,Phone:Nn,MessageSquare:bi,PenTool:Qj,Video:sn,Gift:li};function n5s({actions:s,onMarkComplete:t,onViewScript:r,isLoading:n,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=vr(),[c,d]=k.useState("name"),[h,m]=k.useState("asc"),[x,g]=k.useState(null),[v,j]=k.useState(""),b=P=>{c===P?m(D=>D==="asc"?"desc":"asc"):(d(P),m("asc"))},N=k.useMemo(()=>[...s].sort((P,D)=>{var z,F;let B=0;switch(c){case"name":{const $=`${P.contact.first_name} ${P.contact.last_name||""}`.toLowerCase(),X=`${D.contact.first_name} ${D.contact.last_name||""}`.toLowerCase();B=$.localeCompare(X);break}case"relationship_type":B=(P.relationshipTypeName||"").localeCompare(D.relationshipTypeName||"");break;case"action_type":B=(((z=P.actionType)==null?void 0:z.name)||"").localeCompare(((F=D.actionType)==null?void 0:F.name)||"");break;case"last_touch":B=(P.monthNumber||0)-(D.monthNumber||0);break}return h==="asc"?B:-B}),[s,c,h]),S=P=>r5s[P||"Phone"]||Nn,T=({field:P,children:D})=>e.jsxs(G,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>b(P),children:[D,c===P?h==="asc"?e.jsx(Fd,{className:"ml-2 h-4 w-4"}):e.jsx(Ku,{className:"ml-2 h-4 w-4"}):e.jsx(Rd,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(P,D,B)=>{g(P),j(`${D} ${B||""}`.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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[180px]",children:e.jsx(T,{field:"name",children:"Contact"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(T,{field:"relationship_type",children:"Type"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(T,{field:"action_type",children:"Action"})}),e.jsx(Tt,{className:"w-[130px]",children:"Phone"}),e.jsx(Tt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(Bn,{children:N.map((P,D)=>{var K,Q,Y,ne,de,ce;const B=P.isSpecialDate,z=P.specialDateType,F=B?z==="birthday"?Eh:Cn:S(((K=P.actionType)==null?void 0:K.icon)||null),$=P.contact.phone,X=P.contact.email;return e.jsxs(qs,{className:Bt("hover:bg-muted/50 transition-colors",B&&z==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",B&&z==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(ft,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${P.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[P.contact.first_name," ",P.contact.last_name]})})}),e.jsx(ft,{children:P.relationshipTypeName?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:P.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ft,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:B?e.jsx(Ge,{className:Bt("gap-1",z==="birthday"&&"bg-pink-500 hover:bg-pink-600",z==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:z==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Eh,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Cn,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(F,{className:"h-3 w-3"}),(Q=P.actionType)==null?void 0:Q.name]})})}),e.jsx(ft,{children:$?e.jsx("span",{className:"text-sm font-mono",children:P.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[$&&e.jsx("a",{href:`tel:${P.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Nn,{className:"h-3.5 w-3.5"})}),$&&e.jsx("a",{href:a(P.contact.phone,(Y=P.script)==null?void 0:Y.script_body,P.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(bi,{className:"h-3.5 w-3.5"})}),X&&(l?e.jsx("button",{onClick:()=>l({id:P.contact.id,first_name:P.contact.first_name,last_name:P.contact.last_name,email:P.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(Qs,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(P.contact.email,(ne=P.script)==null?void 0:ne.script_body,(de=P.script)==null?void 0:de.email_subject,(ce=P.actionType)==null?void 0:ce.name,P.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(Qs,{className:"h-3.5 w-3.5"})})),B&&e.jsxs("button",{onClick:()=>{const ae=`${P.contact.first_name}${P.contact.last_name?" "+P.contact.last_name:""}`,ie=z==="birthday"?"birthday":"home_anniversary",me=new URLSearchParams({cardType:ie,contactId:P.contact.id,name:ae,...P.contact.address?{address:P.contact.address}:{},...z==="anniversary"&&P.contact.home_anniversary?{date:P.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${me.toString()}`)},className:Bt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",z==="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 ${z==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>A(P.contact.id,P.contact.first_name,P.contact.last_name),title:"Snooze",children:e.jsx(cm,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ae;return t(P.contact.id,P.actionType.id,(ae=P.script)==null?void 0:ae.id)},disabled:n,children:[e.jsx(Mn,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${P.contact.id}-${D}`)})})]})}),e.jsx(Sge,{open:!!x,onOpenChange:P=>!P&&g(null),contactId:x||"",contactName:v})]})}function a5s({onSelect:s}){const[t,r]=k.useState(null),{data:n=[],isLoading:a}=gt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:c,error:d}=await H.from("email_template_categories").select("*").order("sort_order");if(d)throw d;return c}}),{data:i=[],isLoading:l}=gt({queryKey:["agent-email-templates",t],queryFn:async()=>{let c=H.from("agent_email_templates").select("*").eq("is_active",!0).order("sort_order");t&&(c=c.eq("category_id",t));const{data:d,error:h}=await c;if(h)throw h;return d}}),o=n.find(c=>c.id===t);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>r(null),className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Vo,{className:"h-3.5 w-3.5"}),"Back to categories"]}),e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:o==null?void 0:o.icon})," ",o==null?void 0:o.name]}),l?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(ti,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:i.map(c=>e.jsxs("button",{onClick:()=>s(c),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:c.title}),c.tone&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] shrink-0",children:c.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:c.subject})]},c.id))})})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-2",children:"Select a category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:n.map(c=>e.jsxs("button",{onClick:()=>r(c.id),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:c.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.name}),c.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:c.description})]})]}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},c.id))})]})}function Cge(){const{user:s}=As(),t=es(),{data:r,isLoading:n}=gt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:h}=await H.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),a=Lt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:h,error:m}=await H.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ue.success("Connect page created!")},onError:d=>{var h;(h=d.message)!=null&&h.includes("duplicate")?ue.error("That slug is already taken. Try another."):ue.error("Failed to create page")}}),i=Lt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page");const{error:h}=await H.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",r.id);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ue.success("Page updated!")},onError:()=>ue.error("Failed to update page")}),{data:l=[],isLoading:o}=gt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:h}=await H.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),c=Lt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page. Create your Connect page first.");const{data:h,error:m}=await H.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:r.id}).select("token").single();if(m)throw m;return`${window.location.origin}/connect/${r.slug}?t=${h.token}`}});return{intakePage:r,isLoading:n,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function i5s({value:s,onChange:t,userId:r,placeholder:n}){const[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(!1),[h,m]=k.useState(0),x=k.useRef(null),g=k.useRef(null);k.useEffect(()=>{const j=b=>{x.current&&!x.current.contains(b.target)&&i(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]),k.useEffect(()=>{g.current&&clearTimeout(g.current);const j=s.trim();if(!r||j.length<1||j.includes("@")&&j.indexOf("@")>0&&/\S+@\S+\.\S+/.test(j)){o([]);return}return g.current=setTimeout(async()=>{d(!0);const b=`%${j}%`,N=H,{data:S,error:T}=await N.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r).not("email","is",null).or(`first_name.ilike.${b},last_name.ilike.${b},email.ilike.${b}`).order("first_name",{ascending:!0}).limit(8);d(!1),!T&&S&&(o(S),m(0),i(S.length>0))},180),()=>{g.current&&clearTimeout(g.current)}},[s,r]);const v=j=>{j.email&&(t(j.email),i(!1))};return e.jsxs("div",{ref:x,className:"relative",children:[e.jsx(ke,{id:"gmail-to",value:s,onChange:j=>t(j.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:j=>{!a||l.length===0||(j.key==="ArrowDown"?(j.preventDefault(),m(b=>Math.min(b+1,l.length-1))):j.key==="ArrowUp"?(j.preventDefault(),m(b=>Math.max(b-1,0))):j.key==="Enter"?(j.preventDefault(),v(l[h])):j.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((j,b)=>{const N=[j.first_name,j.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>m(b),onClick:()=>v(j),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${b===h?"bg-accent":"bg-popover"}`,children:[e.jsx(Bi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:N}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:j.email})]})]},j.id)})})]})}const o5s=5*1024*1024,xb=50,l5s=["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 c5s(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function d5s(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 Dw(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 j1({open:s,onOpenChange:t,contact:r,bulkContacts:n,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o}){const{user:c}=As(),d=es(),{isReady:h,settings:m}=Az(),{intakePage:x}=Cge(),g=x?`https://contacts.relevelup.com/${x.slug}`:null,v=!!n&&n.length>0,j=h&&(v||!l),b=v?n:r?[r]:[],N=b[0],S=v?Math.ceil(b.length/xb):1,T=v&&b.length>xb,[A,P]=k.useState((N==null?void 0:N.email)||""),[D,B]=k.useState(a),[z,F]=k.useState(i),[$,X]=k.useState(!1),[K,Q]=k.useState(!1),[Y,ne]=k.useState([]),[de,ce]=k.useState(a),[ae,ie]=k.useState(i),[me,oe]=k.useState("composing"),[ge,be]=k.useState(0),[Oe,Me]=k.useState(0),[Pe,Ee]=k.useState(0),[$e,Se]=k.useState(0),ze=k.useRef(!1),[Te,ye]=k.useState(null);k.useEffect(()=>{s&&(P((N==null?void 0:N.email)||""),ce(a),ie(i),B(Dw(a,N||{first_name:""})),F(Dw(i,N||{first_name:""})),Q(!a&&!i),ne([]),oe("composing"),be(0),Me(0),Ee(0),Se(0),ze.current=!1,ye(null))},[s,N,a,i]);const ct=async at=>{const Ie=at.target.files;if(!Ie)return;const et=Y.reduce((Jt,cs)=>Jt+cs.size,0),Dt=[];for(const Jt of Array.from(Ie)){if(!l5s.includes(Jt.type)){ue.error(`${Jt.name}: Unsupported file type`);continue}if(et+Jt.size>o5s){ue.error("Total attachments exceed 5MB limit");break}try{const cs=await d5s(Jt);Dt.push({name:Jt.name,type:Jt.type,size:Jt.size,data:cs})}catch{ue.error(`Failed to read ${Jt.name}`)}}ne(Jt=>[...Jt,...Dt]),at.target.value=""},ve=at=>{ne(Ie=>Ie.filter((et,Dt)=>Dt!==at))},rt=at=>{ce(at.subject),ie(at.body),B(Dw(at.subject,N||{first_name:""})),F(Dw(at.body,N||{first_name:""})),Q(!1)},Re=at=>at.split(/\n\n+/).map(Ie=>`

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

`).join(""),Qe=async at=>{if(!(at!=null&&at.email))return ue.error("Please enter a recipient email"),!1;const Ie=at||{first_name:""},et=Dw(de,Ie),Dt=Dw(ae,Ie),Jt=Re(Dt);try{if(j){const cs=(m==null?void 0:m.display_name)||"ReLevelUp",Ht=`${cs.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,dt=`${cs} <${Ht}>`,{data:Qt,error:yt}=await H.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:at.email,from_email:dt,subject:et,body_html:Jt,reply_to:(m==null?void 0:m.reply_to_email)||void 0}});if(yt)throw yt;if(!(Qt!=null&&Qt.success))throw new Error((Qt==null?void 0:Qt.error)||"Failed to send")}else{const{data:cs,error:Ht}=await H.functions.invoke("gmail-send",{body:{to:at.email,subject:et,body:Jt,contactId:at.id||void 0,attachments:Y.map(({name:dt,type:Qt,data:yt})=>({name:dt,type:Qt,data:yt}))}});if(Ht)throw Ht;if(!(cs!=null&&cs.success))throw new Error((cs==null?void 0:cs.error)||"Failed to send")}return c&&at.id&&await H.from("bulk_email_sends").insert({user_id:c.id,contact_id:at.id,contact_email:at.email,subject:et,source:j?"ses_bulk":"sphere_gaps"}),!0}catch(cs){return console.error("Send error:",cs),ue.error("Failed to send to "+at.first_name+": "+(cs instanceof Error?cs.message:"Unknown error")),!1}},Ke=()=>{const at=ge*xb;return b.slice(at,at+xb)},Ce=async()=>{if(!D||!z){ue.error("Please fill in subject and message");return}const at=Ke();X(!0),oe("sending");let Ie=0,et=0;for(let Jt=0;JtsetTimeout(Ht,150));Me(Jt=>Jt+Ie),Ee(Jt=>Jt+et),X(!1),d.invalidateQueries({queryKey:["bulk-email-sends"]}),ge>=S-1||ze.current?oe("all_done"):oe("batch_complete")},nt=async()=>{if(!D||!z){ue.error("Please fill in subject and message");return}if(!v){const at=N||{id:"",first_name:"",last_name:"",email:A.trim()};if(!at.email){ue.error("Please enter a recipient email");return}X(!0);try{await Qe(at)&&(d.invalidateQueries({queryKey:["bulk-email-sends"]}),ue.success("Email sent successfully!"),t(!1),o==null||o())}finally{X(!1)}return}await Ce()},$t=async()=>{be(at=>at+1),Se(0),await new Promise(at=>setTimeout(at,50)),await Ce()};k.useEffect(()=>{},[ge]);const lt=()=>{if($){ze.current=!0;return}t(!1),o==null||o()},it=ge*xb,Nt=Math.min(it+xb,b.length),Ft=v&&b.length>0?Math.round((Oe+Pe)/b.length*100):0;return e.jsx(vs,{open:s,onOpenChange:lt,children:e.jsxs(ys,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:`h-5 w-5 ${j?"text-orange-500":"text-red-500"}`}),v?`Send to ${b.length} Contacts`:"Compose Email"]}),j?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",m==null?void 0:m.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,v&&me==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[b.length," contacts"]}),". You'll review each personalized email before sending."]})]}),me==="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 ",ge+1," of ",S,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[$e," of ",Ke().length," in this batch"]})]}),e.jsx(ri,{value:$e/Ke().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Oe+Pe," / ",b.length]}),e.jsxs("span",{children:[Oe," sent • ",Pe," failed"]})]}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ze.current=!0},children:"Stop Sending"})]}),me==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Mn,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",ge+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Oe," sent, ",Pe," failed so far"]})]}),e.jsx(ri,{value:Ft,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[b.length-Oe-Pe," contacts remaining (",S-ge-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",className:"flex-1",onClick:lt,children:"Done for Now"}),e.jsxs(G,{className:"flex-1 gap-2",onClick:$t,children:[e.jsx(Zr,{className:"h-4 w-4"}),"Send Next ",Math.min(xb,b.length-Nt)," Contacts"]})]})]}),me==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Mn,{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:[Oe," emails sent successfully",Pe>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Pe," failed"]})]})]}),e.jsx(G,{className:"w-full",onClick:lt,children:"Close"})]}),me==="composing"&&e.jsxs("div",{className:"space-y-4",children:[K?e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 max-h-[50vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Q(!1),className:"h-7 px-2 text-xs",children:[e.jsx(_r,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(a5s,{onSelect:rt})]}):e.jsxs(G,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>Q(!0),children:[e.jsx(ln,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(po,{}),!v&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"gmail-to",children:"To"}),e.jsx(i5s,{value:A,onChange:P,userId:c==null?void 0:c.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(ke,{id:"gmail-subject",value:D,onChange:at=>{B(at.target.value),ce(at.target.value)},placeholder:"Enter subject..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{F(at=>at+"{{first_name}}"),ie(at=>at+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{F(at=>at+"{{last_name}}"),ie(at=>at+"{{last_name}}")},children:"{{last_name}}"}),g&&e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const at=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${g} `;F(Ie=>Ie+at),ie(Ie=>Ie+at)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(ur,{id:"gmail-body",value:z,onChange:at=>{F(at.target.value),ie(at.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var at;return(at=document.getElementById("gmail-attachments"))==null?void 0:at.click()},disabled:$,children:[e.jsx(Xj,{className:"h-4 w-4"}),"Attach Files"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"PDF, images, Word, Excel (max 5MB total)"}),e.jsx("input",{id:"gmail-attachments",type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.gif,.webp,.doc,.docx,.xls,.xlsx,.csv",className:"hidden",onChange:ct})]}),Y.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Y.map((at,Ie)=>e.jsxs(Ge,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(Xj,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:at.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",c5s(at.size),")"]}),e.jsx("button",{type:"button",onClick:()=>ve(Ie),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(_r,{className:"h-3 w-3"})})]},Ie))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),v?e.jsxs(G,{onClick:()=>{ye(b[0]||null),oe("reviewing")},disabled:!D||!z,className:"gap-2",children:["Review Emails",e.jsx(Ga,{className:"h-4 w-4"})]}):e.jsxs(G,{onClick:nt,disabled:$||!D||!z||!A.trim(),className:"gap-2",children:[$?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),$?"Sending...":"Send Email"]})]})]}),me==="reviewing"&&v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),T&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",b.length," contacts will be sent in ",S," batches of up to ",xb,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{children:["Recipients (",b.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:b.map(at=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(Te==null?void 0:Te.id)===at.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>ye(at),children:[at.first_name," ",at.last_name," — ",at.email]},at.id))})]}),Te&&e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Preview for ",Te.first_name," ",Te.last_name]})}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"To:"})," ",Te.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",Dw(de,Te)]})]}),e.jsx(po,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:Dw(ae,Te)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>{oe("composing"),ye(null)},children:[e.jsx(wa,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(G,{onClick:nt,disabled:$,className:"gap-2",children:[$?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),T?`Send First ${xb}`:`Send to ${b.length}`]})]})]})]})})}function u5s(){const s=vr(),{data:t}=$m(),{data:r}=tz(),n=txe(),{isGmailConnected:a,gmailEmail:i}=Oh(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(new Set),x=Tf(new Date),g=Hl(x,30),v=A=>{if(!A)return null;const P=A.split(/[-/T]/);if(P.length<3)return null;const D=parseInt(P[1],10)-1,B=parseInt(P[2],10);return isNaN(D)||isNaN(B)?null:new Date(x.getFullYear(),D,B)},j=k.useMemo(()=>{if(!t)return[];const A=[];for(const P of t){if(P.birthday){const D=v(P.birthday);D&&($l(D,x)||y5(D,x)&&v5(D,g))&&A.push({contact:P,type:"birthday",date:D,daysUntil:fx(D,x),dateStr:P.birthday})}if(P.home_anniversary){const D=v(P.home_anniversary);D&&($l(D,x)||y5(D,x)&&v5(D,g))&&A.push({contact:P,type:"anniversary",date:D,daysUntil:fx(D,x),dateStr:P.home_anniversary})}}return A.sort((P,D)=>P.daysUntil-D.daysUntil),A},[t]),b=async A=>{const P=(r==null?void 0:r.find(D=>D.name==="Call"))||(r==null?void 0:r[0]);if(P)try{await n.mutateAsync({contactId:A.contact.id,actionTypeId:P.id,notes:`${A.type==="birthday"?"Birthday":"Home Anniversary"} outreach`}),m(D=>new Set(D).add(`${A.contact.id}-${A.type}`)),nn({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{nn({title:"Error",description:"Failed to log touch",variant:"destructive"})}},N=A=>{const P=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,D=A.type==="birthday"?"birthday":"home_anniversary",B=new URLSearchParams({cardType:D,contactId:A.contact.id,name:P,...A.contact.address?{address:A.contact.address}:{},...A.type==="anniversary"&&A.dateStr?{date:A.dateStr}:{}});s(`/mission-control/card-studio?${B.toString()}`)},S=A=>A===0?"Today!":A===1?"Tomorrow":`${A} days`,T=A=>A===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":A<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":A<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(pd,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[j.length," event",j.length!==1?"s":""]})]})}),e.jsxs(De,{className:"space-y-2",children:[j.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Eh,{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."})]}),j.map((A,P)=>{var F,$;const D=`${A.contact.id}-${A.type}`,B=h.has(D),z=`${((F=A.contact.first_name)==null?void 0:F[0])||""}${(($=A.contact.last_name)==null?void 0:$[0])||""}`.toUpperCase();return e.jsxs("div",{className:Bt("p-3 rounded-lg border transition-colors",A.daysUntil===0&&A.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":A.daysUntil===0&&A.type==="anniversary"?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":A.type==="birthday"?"bg-pink-50/60 border-pink-200/60 hover:bg-pink-100/60 dark:bg-pink-950/20 dark:border-pink-900/30 dark:hover:bg-pink-950/30":"bg-blue-50/60 border-blue-200/60 hover:bg-blue-100/60 dark:bg-blue-950/20 dark:border-blue-900/30 dark:hover:bg-blue-950/30"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(vn,{className:Bt("h-10 w-10",A.type==="birthday"?"ring-2 ring-pink-300/50 dark:ring-pink-700/50":"ring-2 ring-blue-300/50 dark:ring-blue-700/50"),children:e.jsx(bn,{className:Bt("text-xs font-medium",A.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:z})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:A.type==="birthday"?"🎂":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[A.contact.first_name," ",A.contact.last_name||""]}),e.jsx(Ge,{variant:"outline",className:Bt("text-[10px] shrink-0 whitespace-nowrap",T(A.daysUntil)),children:S(A.daysUntil)})]}),e.jsxs("div",{className:Bt("text-xs flex items-center gap-1.5 mt-0.5",A.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[A.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Eh,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Cn,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ss(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${A.contact.phone}`,children:e.jsx(Nn,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${A.contact.phone}`,children:e.jsx(bi,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),d(!0)):window.location.href=`mailto:${A.contact.email}`},children:e.jsx(Qs,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${A.contact.id}`),children:e.jsx(sn,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{variant:"ghost",size:"sm",className:Bt("h-7 px-2 gap-1 text-xs",A.type==="birthday"?"text-pink-600 hover:text-pink-700 dark:text-pink-400":"text-blue-600 hover:text-blue-700 dark:text-blue-400"),title:`Send ${A.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>N(A),children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(G,{variant:"ghost",size:"icon",className:Bt("h-7 w-7",B&&"text-green-600"),title:"Log a touch",disabled:B||n.isPending,onClick:()=>b(A),children:e.jsx(Mn,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${A.contact.id}`),children:e.jsx(jn,{className:"h-3.5 w-3.5"})})]})]},`${D}-${P}`)})]})]}),a&&l&&e.jsx(j1,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function h5s(s){const[t,r]=k.useState([]),[n,a]=k.useState(!1),{data:i,isLoading:l}=gt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await H.rpc("cleanup_stale_visitors")}catch{}const{data:h}=await H.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!h)return[];const m=h.map(v=>v.contact_id).filter(Boolean);let x={};if(m.length>0){const{data:v}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",m);(v||[]).forEach(j=>{x[j.id]=j})}const g=h.map(v=>v.auth_user_id).filter(Boolean);if(g.length>0){const{data:v}=await H.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",g);(v||[]).forEach(j=>{const b=h.find(N=>N.auth_user_id===j.user_id);b&&!b.contact_id&&j.contact_id&&(b.contact_id=j.contact_id),b&&!x[b.contact_id||""]&&j.name&&(x[b.contact_id||b.auth_user_id||""]={first_name:j.name.split(" ")[0],last_name:j.name.split(" ").slice(1).join(" ")||null,email:null,phone:j.phone})})}return h.map(v=>{var j,b;return{...v,contact_name:x[v.contact_id||v.auth_user_id||""]?`${x[v.contact_id||v.auth_user_id||""].first_name} ${x[v.contact_id||v.auth_user_id||""].last_name||""}`.trim():null,contact_email:((j=x[v.contact_id||v.auth_user_id||""])==null?void 0:j.email)||null,contact_phone:((b=x[v.contact_id||v.auth_user_id||""])==null?void 0:b.phone)||null}})},enabled:!!s,refetchInterval:6e4});k.useEffect(()=>{if(!s)return;const h=H.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},m=>{m.eventType==="INSERT"?r(x=>x.find(v=>v.id===m.new.id)?x:[m.new,...x]):m.eventType==="UPDATE"?r(x=>x.map(g=>g.id===m.new.id?{...g,...m.new}:g)):m.eventType==="DELETE"&&r(x=>x.filter(g=>g.id!==m.old.id))}).subscribe(m=>{m==="SUBSCRIBED"&&a(!0)});return()=>{H.removeChannel(h)}},[s]);const o=n&&t.length>0?m5s([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(h=>c-new Date(h.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function m5s(s){const t=new Set;return s.filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const f5s={property_view:{label:"Viewed",icon:jn,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:nl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:hi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function p5s(){const{user:s}=As(),t=vr(),{isGmailConnected:r,gmailEmail:n}=Oh(),{leadSite:a}=ey(),{count:i}=h5s(a==null?void 0:a.id),[l,o]=k.useState(!1),[c,d]=k.useState(null),{data:h,isLoading:m}=gt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:N,error:S}=await H.rpc("get_lead_site_activity",{_user_id:s.id});if(S)throw S;return N},enabled:!!s,refetchInterval:6e4});if(m||!(h!=null&&h.has_site))return null;const x=(h.activities||[]).filter(N=>N.visitor_name&&N.visitor_name!=="Site Visitor"),g=x.filter(N=>N.activity_type==="new_lead"),v=(h.activities||[]).filter(N=>N.activity_type==="property_view").length,j=(h.activities||[]).filter(N=>N.activity_type==="saved_listing").length,b=N=>{if(N.visitor_email)if(r){const S=(N.visitor_name||"").split(" ");d({id:N.contact_id||"",first_name:S[0]||"",last_name:S.slice(1).join(" ")||null,email:N.visitor_email}),o(!0)}else window.location.href=`mailto:${N.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(gc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(Ga,{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(nl,{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:g.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(jn,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:v}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(hi,{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:j}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),x.length>0?e.jsxs("div",{className:"space-y-2",children:[x.slice(0,5).map((N,S)=>{const T=f5s[N.activity_type],A=T.icon,P=al(new Date(N.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${T.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${T.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{className:"font-medium text-sm text-primary hover:underline text-left truncate block",onClick:()=>{N.contact_id&&t(`/mission-control/contacts/${N.contact_id}`)},children:N.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:T.label}),N.mls_number&&e.jsxs("span",{children:["· MLS# ",N.mls_number]}),N.lead_type&&e.jsxs("span",{children:["· ",N.lead_type]}),e.jsxs("span",{children:["· ",P]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[N.visitor_email&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>b(N),children:e.jsx(Qs,{className:"h-3.5 w-3.5"})}),N.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${N.visitor_phone}`,children:e.jsx(Nn,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${N.visitor_phone}`,children:e.jsx(bi,{className:"h-3.5 w-3.5"})})]}),N.contact_id&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${N.contact_id}`),children:e.jsx(ya,{className:"h-3.5 w-3.5"})})]})]},`${N.activity_type}-${N.occurred_at}-${S}`)}),x.length>5&&e.jsxs(G,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",x.length-5," more activities",e.jsx(Ga,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 text-center",children:[e.jsx(Ch,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:v>0?`${v} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(G,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Ga,{className:"h-3.5 w-3.5 ml-1"})]})]})}),r&&c&&e.jsx(j1,{open:l,onOpenChange:o,contact:c,gmailEmail:n})]})}const fqe={Crown:nm,FileText:ln,Users:fr,Globe:gc,Star:Qn,Phone:Nn,MessageSquare:bi,PenTool:Qj,Video:sn,Gift:li},x5s={"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 g5s(){var nt,$t,lt,it,Nt,Ft;const s=vr(),{user:t}=As(),{data:r}=qx(),{data:n}=qnt(),{data:a}=$m(),{data:i}=tz(),{data:l}=Knt(),o=M$t(),c=A5e(),d=E$t(90),h=txe(),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(!1),[P,D]=k.useState(""),[B,z]=k.useState(the()),[F,$]=k.useState("cards"),[X,K]=k.useState(!1),[Q,Y]=k.useState(null),[ne,de]=k.useState(null),[ce,ae]=k.useState(""),{isGmailConnected:ie,gmailEmail:me}=Oh(),oe=()=>{const at=parseInt(P,10);if(isNaN(at)||at<1){nn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}z(at),Wnt(at),A(!1),nn({title:"Goal updated",description:`Weekly touch goal set to ${at}`})},ge=()=>{D(B.toString()),A(!0)};k.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:Ie}=await H.from("profiles").select("name").eq("id",t.id).single();Ie!=null&&Ie.name&&S(Ie.name.split(" ")[0])})()},[t==null?void 0:t.id]),k.useEffect(()=>{o.mutate()},[]);const be=Tf(new Date),Oe=Hl(be,7),Me=at=>{if(!at)return null;const Ie=at.split(/[-/T]/);if(Ie.length<3)return null;const et=parseInt(Ie[1],10)-1,Dt=parseInt(Ie[2],10);return isNaN(et)||isNaN(Dt)?null:new Date(be.getFullYear(),et,Dt)},Pe=(a==null?void 0:a.filter(at=>{const Ie=Me(at.birthday),et=Me(at.home_anniversary);return Ie&&$l(Ie,be)||et&&$l(et,be)}))||[];a!=null&&a.filter(at=>{if(!at.birthday&&!at.home_anniversary)return!1;const Ie=et=>{if(!et)return!1;const Dt=Me(et);return Dt?y5(Dt,be)&&v5(Dt,Oe):!1};return Ie(at.birthday)||Ie(at.home_anniversary)}).slice(0,5);const Ee=[],$e=(i==null?void 0:i.find(at=>at.name==="Call"))||(i==null?void 0:i[0]);for(const at of Pe){const Ie=Me(at.birthday),et=Me(at.home_anniversary),Dt=Ie&&$l(Ie,be),Jt=et&&$l(et,be);Dt&&Ee.push({contact:at,actionType:$e||{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:((lt=($t=(nt=at.tags)==null?void 0:nt[0])==null?void 0:$t.relationship_type)==null?void 0:lt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Jt&&Ee.push({contact:at,actionType:$e||{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:((Ft=(Nt=(it=at.tags)==null?void 0:it[0])==null?void 0:Nt.relationship_type)==null?void 0:Ft.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const ze=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((at,Ie)=>{var Dt,Jt,cs;const et=i==null?void 0:i[Ie%((i==null?void 0:i.length)||1)];return et?{contact:at,actionType:et,planName:"Quick Touch",relationshipTypeName:((cs=(Jt=(Dt=at.tags)==null?void 0:Dt[0])==null?void 0:Jt.relationship_type)==null?void 0:cs.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Te=[...Ee,...ze],ye=async(at,Ie,et)=>{await h.mutateAsync({contactId:at,actionTypeId:Ie,scriptUsedId:et}),b(!1),v(null)},ct=at=>{at.script?(v(at),b(!0)):ye(at.contact.id,at.actionType.id)},ve=at=>fqe[at||"Phone"]||Nn,rt=at=>fqe[at||"Users"]||fr,Re=(at,Ie)=>at.replace(/\{\{FirstName\}\}/g,Ie.first_name).replace(/\{\{LastName\}\}/g,Ie.last_name||"").replace(/\{\{AgentName\}\}/g,N||"there"),Qe=(at,Ie)=>({Call:`Thinking of you, ${Ie}!`,Text:`Quick hello, ${Ie}`,Email:`Checking in, ${Ie}`,"Handwritten Note":`A note for ${Ie}`,Video:`Video message for ${Ie}`,Gift:`Something special for you, ${Ie}`})[at]||`Hello ${Ie}!`,Ke=(at,Ie,et)=>{const Dt=`sms:${at}`;if(Ie&&et){const Jt=Re(Ie,et);return`${Dt}?body=${encodeURIComponent(Jt)}`}return Dt},Ce=(at,Ie,et,Dt,Jt)=>{const cs=`mailto:${at}`,Ht=[];if(Jt){const dt=et||Qe(Dt||"Email",Jt.first_name);if(Ht.push(`subject=${encodeURIComponent(dt)}`),Ie){const Qt=Re(Ie,Jt);Ht.push(`body=${encodeURIComponent(Qt)}`)}}return Ht.length>0?`${cs}?${Ht.join("&")}`:cs};return e.jsxs(e.Fragment,{children:[e.jsxs(_s,{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(p5s,{}),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(at=>at.active).map(at=>{const Ie=rt(at.icon),et=(n==null?void 0:n[at.id])||0,Dt=m===at.id,Jt=x5s[at.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{Dt?(x(null),s("/mission-control/contacts")):(x(at.id),s(`/mission-control/contacts?type=${at.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${Dt?Jt:"bg-card hover:bg-accent"} `,children:[e.jsx(Ie,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:`text-sm ${Dt?"opacity-90":"text-muted-foreground"}`,children:[et," Contacts"]})]})]},at.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(G,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Nh,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(G,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx(ya,{className:"h-4 w-4 ml-1"})]}),e.jsx(G,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(G,{variant:"outline",onClick:()=>s("/mission-control/plans"),className:"w-full",children:"Manage Plans"})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(jr,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(G,{variant:F==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>$("cards"),title:"Card view",children:e.jsx(Sf,{className:"h-4 w-4"})}),e.jsx(G,{variant:F==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>$("table"),title:"Table view",children:e.jsx(lm,{className:"h-4 w-4"})})]})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-4",children:Te.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx(G,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):F==="table"?e.jsx(n5s,{actions:Te,onMarkComplete:ye,onViewScript:ct,isLoading:h.isPending,buildSmsLink:Ke,buildEmailLink:Ce,onGmailCompose:ie?at=>{Y(at),K(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Te.map((at,Ie)=>{var yt,ss,Is,fs,ar,Er,Tr;const et=at.isSpecialDate,Dt=at.specialDateType,Jt=et?Dt==="birthday"?Eh:Cn:ve(((yt=at.actionType)==null?void 0:yt.icon)||null),cs=at.contact.phone,Ht=at.contact.email,dt=et?Dt==="birthday"?"#EC4899":"#8B5CF6":((ss=at.actionType)==null?void 0:ss.color)||"#3B82F6",Qt=et?Dt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Is=at.actionType)==null?void 0:Is.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${et?"ring-2 ring-offset-2":""}`,style:et?{"--tw-ring-color":dt}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:dt},children:[e.jsx(Jt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Qt})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${at.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[at.contact.first_name," ",at.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[cs&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${at.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(Nn,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ke(at.contact.phone,(fs=at.script)==null?void 0:fs.script_body,at.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(bi,{className:"h-3 w-3"}),"Text"]})]}),Ht&&(ie?e.jsxs("button",{onClick:()=>{Y({id:at.contact.id,first_name:at.contact.first_name,last_name:at.contact.last_name,email:at.contact.email}),K(!0)},className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Compose Email",children:[e.jsx(Qs,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ce(at.contact.email,(ar=at.script)==null?void 0:ar.script_body,(Er=at.script)==null?void 0:Er.email_subject,(Tr=at.actionType)==null?void 0:Tr.name,at.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(Qs,{className:"h-3 w-3"}),"Email"]}))]}),et&&e.jsxs("button",{onClick:()=>{const Lr=`${at.contact.first_name}${at.contact.last_name?" "+at.contact.last_name:""}`,$r=Dt==="birthday"?"birthday":"home_anniversary",kr=new URLSearchParams({cardType:$r,contactId:at.contact.id,name:Lr,...at.contact.address?{address:at.contact.address}:{},...Dt==="anniversary"&&at.contact.home_anniversary?{date:at.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${kr.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(Qs,{className:"h-3 w-3"}),"Send ",Dt==="birthday"?"Birthday":"Anniversary"," Card"]}),!cs&&!Ht&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[at.relationshipTypeName&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:at.relationshipTypeName}),at.monthNumber>0&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["Month ",at.monthNumber]})]}),at.script&&e.jsx(G,{size:"sm",variant:"outline",className:"w-full",onClick:()=>ct(at),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{de(at.contact.id),ae(`${at.contact.first_name} ${at.contact.last_name||""}`.trim())},children:[e.jsx(cm,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(G,{size:"sm",className:"flex-1",onClick:()=>{var Lr;return ye(at.contact.id,at.actionType.id,(Lr=at.script)==null?void 0:Lr.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]},at.contact.id+Ie)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"ghost",className:"h-full w-full",children:[e.jsx(ix,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Vd,{children:e.jsx(Da,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"text-lg",children:"Momentum"}),e.jsxs(vs,{open:T,onOpenChange:A,children:[e.jsx(Ni,{asChild:!0,children:e.jsx("button",{onClick:ge,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(lo,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(ys,{className:"sm:max-w-[360px]",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Set Weekly Goal"}),e.jsx(Fr,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(ke,{id:"weekly-goal-ic",type:"number",min:"1",value:P,onChange:at=>D(at.target.value),placeholder:"20",onKeyDown:at=>{at.key==="Enter"&&oe()}})]}),e.jsx(G,{onClick:oe,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(ri,{value:Math.min(c.actionsThisWeek/B*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(xc,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",B]}),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(cn,{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(ya,{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(cat,{}),e.jsx(u5s,{})]})]}),e.jsx(vs,{open:j,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(bs,{className:"flex items-center gap-2",children:g&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:g.actionType.color||"#3B82F6"}}),g.actionType.name," Script"]})})}),g&&g.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:[g.contact.first_name," ",g.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Re(g.script.script_body,g.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",className:"flex-1",onClick:()=>b(!1),children:"Close"}),e.jsx(G,{className:"flex-1",onClick:()=>{var at;return ye(g.contact.id,g.actionType.id,(at=g.script)==null?void 0:at.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(Q3s,{})]}),ie&&Q&&e.jsx(j1,{open:X,onOpenChange:K,contact:Q,gmailEmail:me}),e.jsx(Sge,{open:!!ne,onOpenChange:at=>!at&&de(null),contactId:ne||"",contactName:ce})]})}const y5s=[{value:"bidirectional",label:"Two-Way",icon:Rd,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Fd,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Ku,tooltip:"Only pull BoldTrail → Agent OS"}];function ySe({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(nAe,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:y5s.map(a=>e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(rfe,{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(Wl,{children:a.tooltip})]},a.value))})]})}function pqe(){const s=es(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),[g,v]=k.useState(0),j=k.useRef(!1),{data:b}=gt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:F,error:$}=await H.functions.invoke("boldtrail-sync",{body:{action:"status"}});if($)throw $;return F}}),N=(b==null?void 0:b.sync_direction)||"bidirectional",S=d??N,T=Lt({mutationFn:async()=>{const{data:F,error:$}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if($)throw $;if(F!=null&&F.error)throw new Error(F.error);return F},onSuccess:F=>{h(null),a(F),r(!0)},onError:F=>{ue.error(F.message||"Failed to generate sync preview")}}),A=Lt({mutationFn:async()=>{j.current=!1,x("Initializing sync..."),v(5);const{data:F,error:$}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:S}});if($)throw $;if(F!=null&&F.error)throw new Error(F.error);const X=F;let K=X.sync_log_id,Q=X.next_phase,Y=X.next_offset,ne=X.push_total||0,de=X.pull_total||0,ce=X.update_total||0,ae=0,ie=0,me=0;for(;Q!=="finalize"&&!j.current;){const be=ne+de+ce;Q==="fetch_bt"?x("Fetching BoldTrail contacts..."):Q==="analyze"?(x("Analyzing contacts..."),v(15)):Q==="push"?(x(`Pushing contacts to BoldTrail... (${ae}/${ne})`),v(be>0?ae/be*90:0)):Q==="pull"?(x(`Pulling contacts from BoldTrail... (${ie}/${de})`),v(be>0?(ne+ie)/be*90:0)):Q==="update"&&(x(`Updating existing contacts... (${me}/${ce})`),v(be>0?(ne+de+me)/be*90:0));const{data:Oe,error:Me}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:Q,offset:Y,sync_log_id:K,sync_direction:S}});if(Me)throw Me;if(Oe!=null&&Oe.error)throw new Error(Oe.error);const Pe=Oe;ae+=Pe.chunk_pushed||0,ie+=Pe.chunk_pulled||0,me+=Pe.chunk_updated||0,Pe.push_total!==void 0&&(ne=Pe.push_total||0),Pe.pull_total!==void 0&&(de=Pe.pull_total||0),Pe.update_total!==void 0&&(ce=Pe.update_total||0),Pe.progress&&x(Pe.progress),Q=Pe.next_phase,Y=Pe.next_offset}x("Finalizing sync..."),v(95);const{data:oe,error:ge}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:K,sync_direction:S}});if(ge)throw ge;return v(100),oe},onSuccess:F=>{x(null),v(0),r(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const $=[`Pushed ${F.contacts_pushed||0}`,`pulled ${F.contacts_pulled||0}`,`updated ${F.contacts_updated||0}`,`skipped ${F.contacts_skipped||0} duplicates`];ue.success(`Sync complete! ${$.join(", ")}.`)},onError:F=>{x(null),v(0),ue.error(F.message||"Sync failed")}});if(!(b!=null&&b.connected))return null;const P=S==="pull_only"?0:(n==null?void 0:n.to_push)??0,D=S==="push_only"?0:(n==null?void 0:n.to_pull)??0,B=(n==null?void 0:n.to_update)??0,z=P>0||D>0||B>0;return e.jsxs(e.Fragment,{children:[e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,className:"shrink-0",children:T.isPending?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Rd,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Wl,{children:"Sync with BoldTrail"})]}),e.jsx(vs,{open:t,onOpenChange:F=>{A.isPending||r(F)},children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Rd,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Fr,{children:"Review what will happen when you sync your contacts."})]}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ySe,{value:S,onChange:h,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${S==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:P}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${S==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ku,{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:B}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(mM,{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(fr,{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"]}),B>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(mM,{className:"h-3 w-3 inline mr-1"}),B," contacts have missing fields that will be filled from the other system"]}),P>0&&e.jsxs(bx,{open:i,onOpenChange:l,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3 text-emerald-600"}),P," contacts to push to BoldTrail"]}),e.jsx(so,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(wx,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.push_preview.map((F,$)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},$)),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(bx,{open:o,onOpenChange:c,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ku,{className:"h-3 w-3 text-blue-600"}),D," contacts to pull from BoldTrail"]}),e.jsx(so,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(wx,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.pull_preview.map((F,$)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},$)),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"]})]})})]}),!z&&!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(ri,{value:g||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:m||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(G,{onClick:()=>A.mutate(),disabled:A.isPending||!z,className:"gap-2",children:[A.isPending?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Rd,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const v5s=()=>{const{user:s}=As();return gt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.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})},Tge=s=>{const{user:t}=As();return gt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let r=H.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})},lAe=()=>{const{user:s}=As();return gt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("relationship_type_popby_defaults").select("*");if(r)throw r;return t},enabled:!!s})},Amt=()=>{const{user:s}=As();return gt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_popby_settings").select("*");if(r)throw r;return t},enabled:!!s})},b5s=()=>{const{data:s}=$m(),{data:t}=qx(),{data:r}=Tge(),{data:n}=Amt(),{data:a}=lAe(),i=new Map;r==null||r.forEach(h=>{const m=i.get(h.contact_id);(!m||new Date(h.completed_at)>new Date(m))&&i.set(h.contact_id,h.completed_at)});const l=new Map;a==null||a.forEach(h=>l.set(h.relationship_type_id,h.frequency_days));const o=new Map;n==null||n.filter(h=>h.is_active).forEach(h=>{o.set(h.contact_id,h.frequency_days)});const c=Tf(new Date);return(s||[]).map(h=>{let m=90;if(o.has(h.id))m=o.get(h.id);else if(h.tags&&h.tags.length>0){const b=h.tags.map(N=>l.get(N.relationship_type_id)).filter(N=>N!==void 0);b.length>0&&(m=Math.min(...b))}const x=i.get(h.id)||null,g=x?Kg(c,Tf(new Date(x))):null,v=g===null||g>=m,j=v&&g!==null?g-m:0;return{...h,lastPopby:x,daysSinceLastPopby:g,frequencyDays:m,isDue:v,daysOverdue:j}}).sort((h,m)=>m.daysOverdue-h.daysOverdue)},Mmt=()=>b5s().filter(t=>t.isDue),_5s=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{error:n}=await H.from("popby_items").insert({...r,owner_user_id:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),nn({title:"Popby item created!"})},onError:r=>{nn({title:"Error creating popby item",description:r.message,variant:"destructive"})}})},w5s=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const n=new Date().toISOString(),{error:a}=await H.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 H.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await H.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"]}),nn({title:"Popby logged!"})},onError:r=>{nn({title:"Error logging popby",description:r.message,variant:"destructive"})}})},j5s=()=>{const s=es(),{user:t}=As();return Lt({mutationFn:async r=>{const{error:n}=await H.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"]}),nn({title:"Frequency updated!"})},onError:r=>{nn({title:"Error updating frequency",description:r.message,variant:"destructive"})}})},N5s=()=>{const{data:s}=Tge(30),t=Mmt(),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 k5s(){const{user:s}=As();return gt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Imt(s){const{data:t}=k5s(),{data:r}=Amt(),{data:n}=lAe(),{data:a}=J3s();return k.useMemo(()=>{const i=a==null?void 0:a.find(b=>b.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Tf(new Date);if(l&&!v5(l,o))return{nextTouchDate:l,daysUntil:Kg(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(b=>b.contact_id===s.id))||[]).sort((b,N)=>new Date(N.completed_at).getTime()-new Date(b.completed_at).getTime())[0],h=d?new Date(d.completed_at):null;let m=90;const x=r==null?void 0:r.find(b=>b.contact_id===s.id&&b.is_active);if(x)m=x.frequency_days;else if(s.tags&&s.tags.length>0){const b=s.tags.map(N=>{const S=n==null?void 0:n.find(T=>T.relationship_type_id===N.relationship_type_id);return S==null?void 0:S.frequency_days}).filter(N=>N!==void 0);b.length>0&&(m=Math.min(...b))}if(!h)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:m,lastTouchDate:null,snoozedUntil:null};const g=Hl(Tf(h),m),v=Kg(g,o);let j;return v<0?j="overdue":v<=7?j="due-soon":j="on-track",{nextTouchDate:g,daysUntil:v,status:j,frequencyDays:m,lastTouchDate:h,snoozedUntil:null}},[s,t,r,n,a])}function vSe({contact:s}){const t=Imt(s),n=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Hi,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:cn,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:Mn,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:cm,text:`Snoozed until ${Ss(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:rn,text:"Never touched",className:"border-dashed"}}})(),a=n.icon;return e.jsxs(Ge,{variant:n.variant,className:Bt("gap-1",n.className),children:[e.jsx(a,{className:"h-3 w-3"}),n.text]})}function S5s({contact:s,onLogTouch:t,onSnooze:r}){const n=Imt(s),a=t5s(),[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(Hi,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(cn,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Mn,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(cm,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(rn,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(n.status){case"overdue":return`${Math.abs(n.daysUntil)} days overdue`;case"due-soon":return n.daysUntil===0?"Due today!":`Due in ${n.daysUntil} days`;case"on-track":return`On track - ${n.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${n.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},h=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Bt("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:"})," ",Ss(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:"})," ",Ss(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:"})," ",Ss(n.lastTouchDate,"MMM d, yyyy")]}),n.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",n.frequencyDays," days"]}),n.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1",onClick:h,disabled:a.isPending,children:[e.jsx(_r,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(G,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),n.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(cm,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(n.status==="overdue"||n.status==="due-soon"||n.status==="never-touched")&&t&&e.jsx(G,{size:"sm",className:"flex-1",variant:n.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(Sge,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const x_e=768;function tL(){const[s,t]=k.useState(void 0);return k.useEffect(()=>{const r=window.matchMedia(`(max-width: ${x_e-1}px)`),n=()=>{t(window.innerWidthr.removeEventListener("change",n)},[]),!!s}function C5s(){const{user:s}=As(),{hasLeadSite:t,leadSite:r}=ey(),{data:n,isLoading:a}=gt({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 H.from("lead_site_visitors").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),{data:l}=await H.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 T5s={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"}},E5s={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 _8({score:s,showScore:t=!1,showTooltip:r=!0,size:n="sm",className:a}){const i=T5s[s.status],l=E5s[n],o=e.jsxs("div",{className:Bt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Bt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return r?e.jsx(A_,{children:e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:o}),e.jsx(Wl,{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:Bt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ri,{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 A5s=[{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}],HU=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]},M5s=({open:s,onOpenChange:t,relationshipTypes:r,onSuccess:n})=>{const{user:a}=As(),{toast:i}=Ea(),l=k.useRef(null),[o,c]=k.useState("upload"),[d,h]=k.useState([]),[m,x]=k.useState([]),[g,v]=k.useState({}),[j,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState(!1),[P,D]=k.useState(null),B=()=>{c("upload"),h([]),x([]),v({}),b([]),S([]),D(null),l.current&&(l.current.value="")},z=()=>{B(),t(!1)},F=me=>{const oe=me.split(` `).map(Ee=>Ee.trim()).filter(Ee=>Ee);if(oe.length===0)return{headers:[],data:[]};const ge=Ee=>{const $e=[];let Se="",ze=!1;for(let Te=0;Te0&&(be[0]=be[0].replace(/^\uFEFF/,""));const Oe=new Map,Me=be.map((Ee,$e)=>{let Se=(Ee||"").trim();Se||(Se=`Column ${$e+1}`);const ze=Oe.get(Se)||0;return Oe.set(Se,ze+1),ze===0?Se:`${Se} (${ze+1})`}),Pe=oe.slice(1).map(ge);return{headers:Me,data:Pe}},$=me=>{var be;const oe=(be=me.target.files)==null?void 0:be[0];if(!oe)return;const ge=new FileReader;ge.onload=Oe=>{var Se;const Me=(Se=Oe.target)==null?void 0:Se.result,{headers:Pe,data:Ee}=F(Me);if(Pe.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}h(Pe),x(Ee);const $e={};Pe.forEach(ze=>{const Te=ze.toLowerCase().replace(/[_\s-]/g,"");Te.includes("firstname")||Te==="first"?$e.first_name=ze:Te.includes("lastname")||Te==="last"?$e.last_name=ze:Te.includes("spouse")&&Te.includes("email")?$e.spouse_email=ze:Te.includes("spouse")||Te.includes("partner")?$e.spouse_name=ze:Te.includes("email")?$e.email=ze:Te.includes("phone")||Te.includes("mobile")||Te.includes("cell")?$e.phone=ze:Te.includes("address")||Te.includes("street")?$e.address=ze:Te==="city"?$e.city=ze:Te==="state"||Te==="province"?$e.state=ze:Te==="zip"||Te==="zipcode"||Te==="postalcode"?$e.zip=ze:Te.includes("company")||Te.includes("organization")||Te.includes("business")?$e.company_name=ze:Te.includes("jobtitle")||Te.includes("title")&&!Te.includes("spouse")?$e.job_title=ze:Te.includes("birthday")||Te.includes("dob")||Te.includes("birthdate")?$e.birthday=ze:Te.includes("anniversary")||Te.includes("homeanniversary")?$e.home_anniversary=ze:(Te.includes("notes")||Te.includes("comment"))&&($e.notes=ze)}),v($e),c("mapping")},ge.readAsText(oe)},X=(me,oe)=>{v(ge=>{if(oe==="none"){const{[me]:be,...Oe}=ge;return Oe}return{...ge,[me]:oe}})},K=me=>{b(oe=>oe.includes(me)?oe.filter(ge=>ge!==me):[...oe,me])},Q=async()=>{if(!(a!=null&&a.id))return;const{data:me}=await H.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),oe=new Set((me||[]).filter(Oe=>Oe.email).map(Oe=>Oe.email.toLowerCase())),ge=new Set((me||[]).filter(Oe=>Oe.phone).map(Oe=>Oe.phone.replace(/[^0-9]/g,""))),be=m.map(Oe=>{const Me=Te=>{const ye=g[Te];if(!ye)return"";const ct=d.indexOf(ye);return ct>=0?(Oe[ct]||"").trim():""},Pe=Me("first_name"),Ee=Me("email"),$e=Me("phone"),Se=Pe.length>0,ze=!!(Ee&&oe.has(Ee.toLowerCase())||$e&&ge.has($e.replace(/[^0-9]/g,"")));return{first_name:Pe,last_name:Me("last_name"),email:Ee,phone:$e,address:Me("address"),city:Me("city"),state:Me("state"),zip:Me("zip"),spouse_name:Me("spouse_name"),spouse_email:Me("spouse_email"),company_name:Me("company_name"),job_title:Me("job_title"),birthday:Me("birthday"),home_anniversary:Me("home_anniversary"),notes:Me("notes"),isValid:Se,isDuplicate:ze,error:Se?void 0:"First name is required"}});S(be),c("preview")},Y=me=>{const oe=me.trim().split(/\s+/);return{first_name:oe[0],last_name:oe.length>1?oe.slice(1).join(" "):null}},ne=async()=>{if(!(a!=null&&a.id))return;const me=N.filter(Oe=>Oe.isValid);if(me.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}A(!0);let oe=0,ge=0,be=0;try{for(const Oe of me)try{let Me=null;if(Oe.email){const{data:$e}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Oe.email).maybeSingle();Me=$e}if(!Me&&Oe.phone){const $e=Oe.phone.replace(/[^0-9]/g,""),{data:Se}=await H.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Se){const ze=Se.find(Te=>Te.phone&&Te.phone.replace(/[^0-9]/g,"")===$e);ze&&(Me={id:ze.id})}}const Pe={owner_user_id:a.id,first_name:Oe.first_name,last_name:Oe.last_name||null,email:Oe.email||null,phone:Oe.phone||null,address:Oe.address||null,city:Oe.city||null,state:Oe.state||null,zip:Oe.zip||null,spouse_name:Oe.spouse_name||null,spouse_email:Oe.spouse_email||null,company_name:Oe.company_name||null,job_title:Oe.job_title||null,birthday:HU(Oe.birthday),home_anniversary:HU(Oe.home_anniversary),notes:Oe.notes||null};let Ee=null;if(Me){const{data:$e}=await H.from("innercircle_contacts").select("*").eq("id",Me.id).single();if($e){const Se={},ze=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Te of ze){const ye=$e[Te],ct=Pe[Te];(!ye||ye==="")&&ct&&(Se[Te]=ct)}Object.keys(Se).length>0&&await H.from("innercircle_contacts").update(Se).eq("id",Me.id)}Ee=Me.id,ge++}else{const{data:$e,error:Se}=await H.from("innercircle_contacts").insert(Pe).select("id").single();Se?(console.error("Insert error for contact:",Oe.first_name,Se),be++):$e?(Ee=$e.id,j.length>0&&await H.from("innercircle_contact_tags").insert(j.map(ze=>({contact_id:$e.id,relationship_type_id:ze}))),oe++):be++}if(Ee&&Oe.spouse_name){const $e=Y(Oe.spouse_name);let Se=null;if(Oe.spouse_email){const{data:Te}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Oe.spouse_email).maybeSingle();Se=Te}if(!Se){const{data:Te}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",$e.first_name).eq("last_name",$e.last_name||Oe.last_name||"").maybeSingle();Se=Te}let ze=null;if(Se){ze=Se.id;const Te=HU(Oe.home_anniversary);Te&&await H.from("innercircle_contacts").update({home_anniversary:Te}).eq("id",Se.id).is("home_anniversary",null)}else{const{data:Te}=await H.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:$e.first_name,last_name:$e.last_name||Oe.last_name||null,email:Oe.spouse_email||null,address:Oe.address||null,city:Oe.city||null,state:Oe.state||null,zip:Oe.zip||null,home_anniversary:HU(Oe.home_anniversary),spouse_name:`${Oe.first_name}${Oe.last_name?" "+Oe.last_name:""}`,spouse_email:Oe.email||null,notes:`Spouse of ${Oe.first_name} ${Oe.last_name||""} (imported via CSV)`.trim()}).select("id").single();Te&&(ze=Te.id,oe++)}ze&&(await H.from("innercircle_contacts").update({spouse_contact_id:ze}).eq("id",Ee),await H.from("innercircle_contacts").update({spouse_contact_id:Ee}).eq("id",ze))}}catch(Me){console.error("Error importing contact:",Me),be++}D({created:oe,updated:ge,failed:be}),c("result"),(oe>0||ge>0)&&n(),i({title:"Import Complete",description:`${oe} created, ${ge} updated${be>0?`, ${be} failed`:""}.`})}catch(Oe){console.error("Import error:",Oe),i({title:"Import Failed",description:Oe.message||"Failed to import contacts",variant:"destructive"})}finally{A(!1)}},de=N.filter(me=>me.isValid).length,ce=N.filter(me=>!me.isValid).length,ae=N.filter(me=>me.isValid&&me.isDuplicate).length,ie=de-ae;return e.jsx(vs,{open:s,onOpenChange:z,children:e.jsxs(ys,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Jb,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Fr,{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:$,className:"hidden"}),e.jsx(oa,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(G,{onClick:()=>{var me;return(me=l.current)==null?void 0:me.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{const me=`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`,oe=new Blob([me],{type:"text/csv"}),ge=URL.createObjectURL(oe),be=document.createElement("a");be.href=ge,be.download="contact_import_template.csv",be.click(),URL.revokeObjectURL(ge)},children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download Template"]})]})]}),o==="mapping"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:A5s.map(me=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(he,{className:"w-40 text-sm",children:[me.label,me.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(zs,{value:g[me.key]||"none",onValueChange:oe=>X(me.key,oe),children:[e.jsx(Os,{className:"w-48",children:e.jsx(Us,{placeholder:"Select column..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"-- Not mapped --"}),d.map(oe=>e.jsx(mt,{value:oe,children:oe},oe))]})]})]},me.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(me=>e.jsx(Ge,{variant:j.includes(me.id)?"default":"outline",className:"cursor-pointer",onClick:()=>K(me.id),children:me.name},me.id))})]}),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(Mn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[ie," new"]})]}),ae>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Hi,{className:"h-4 w-4"}),e.jsxs("span",{children:[ae," existing (will merge gaps)"]})]}),ce>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Hi,{className:"h-4 w-4"}),e.jsxs("span",{children:[ce," invalid"]})]})]}),ae>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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Bn,{children:N.slice(0,100).map((me,oe)=>e.jsxs(qs,{children:[e.jsx(ft,{children:me.first_name}),e.jsx(ft,{children:me.last_name}),e.jsx(ft,{children:me.email}),e.jsx(ft,{children:me.phone}),e.jsx(ft,{children:me.isValid?me.isDuplicate?e.jsx(Ge,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Ge,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Ge,{variant:"destructive",children:me.error||"Invalid"})})]},oe))})]}),N.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",N.length," contacts"]})]})]}),o==="result"&&P&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Mn,{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:[P.created," created, ",P.updated," merged"]}),P.failed>0&&e.jsxs("p",{className:"text-destructive",children:[P.failed," failed to import"]})]}),e.jsxs(on,{children:[o==="upload"&&e.jsx(G,{variant:"outline",onClick:z,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:B,children:"Back"}),e.jsx(G,{onClick:Q,disabled:!g.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(G,{onClick:ne,disabled:T||de===0,children:T?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${de} Contact${de!==1?"s":""}`})]}),o==="result"&&e.jsx(G,{onClick:z,children:"Done"})]})]})})};function I5s(){return"contacts"in navigator&&"ContactsManager"in window}function P5s(s){const t=[],r=s.split("BEGIN:VCARD").filter(n=>n.trim());for(const n of r){const a=n.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const h of a){const m=h.replace(/^\s+/,"");if(m.startsWith("N:")||m.startsWith("N;")){const g=m.substring(m.indexOf(":")+1).split(";");l=(g[0]||"").trim(),i=(g[1]||"").trim()}if((m.startsWith("FN:")||m.startsWith("FN;"))&&!i){const g=m.substring(m.indexOf(":")+1).trim().split(" ");i=g[0]||"",l=g.slice(1).join(" ")}(m.startsWith("EMAIL")||m.match(/^item\d+\.EMAIL/i))&&!o&&(o=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("TEL")||m.match(/^item\d+\.TEL/i))&&!c&&(c=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("ADR")||m.match(/^item\d+\.ADR/i))&&!d&&(d=m.substring(m.indexOf(":")+1).split(";").map(v=>v.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function L5s({open:s,onOpenChange:t,onComplete:r}){const{user:n}=As(),{data:a}=$m(),i=exe(),l=k.useRef(null),[o,c]=k.useState("choose"),[d,h]=k.useState([]),[m,x]=k.useState(new Set),[g,v]=k.useState(0),[j,b]=k.useState(0),N=I5s(),S=k.useCallback(X=>{if(!a)return X;const K=new Set(a.filter(Y=>Y.email).map(Y=>Y.email.toLowerCase())),Q=new Set(a.filter(Y=>Y.phone).map(Y=>Y.phone.replace(/\D/g,"")));return X.map(Y=>{var ce,ae;const ne=(ce=Y.email)==null?void 0:ce.toLowerCase(),de=(ae=Y.phone)==null?void 0:ae.replace(/\D/g,"");return ne&&K.has(ne)?{...Y,isDuplicate:!0,duplicateField:"email"}:de&&de.length>=7&&Q.has(de)?{...Y,isDuplicate:!0,duplicateField:"phone"}:Y})},[a]),T=async()=>{try{const X=["name","email","tel","address"],K=await navigator.contacts.select(X,{multiple:!0});if(!K||K.length===0)return;const Q=K.map(de=>{var ie,me,oe,ge;const ae=(((ie=de.name)==null?void 0:ie[0])||"").split(" ");return{first_name:ae[0]||"",last_name:ae.slice(1).join(" "),email:((me=de.email)==null?void 0:me[0])||"",phone:((oe=de.tel)==null?void 0:oe[0])||"",address:(ge=de.address)!=null&&ge[0]?[de.address[0].streetAddress,de.address[0].city,de.address[0].region,de.address[0].postalCode].filter(Boolean).join(", "):""}}),Y=S(Q);h(Y);const ne=new Set;Y.forEach((de,ce)=>{de.isDuplicate||ne.add(ce)}),x(ne),c("preview")}catch(X){console.error("Contact Picker error:",X),nn({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},A=X=>{var Y;const K=(Y=X.target.files)==null?void 0:Y[0];if(!K)return;const Q=new FileReader;Q.onload=ne=>{var me;const de=(me=ne.target)==null?void 0:me.result,ce=P5s(de);if(ce.length===0){nn({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ae=S(ce);h(ae);const ie=new Set;ae.forEach((oe,ge)=>{oe.isDuplicate||ie.add(ge)}),x(ie),c("preview")},Q.readAsText(K),l.current&&(l.current.value="")},P=async()=>{const X=d.filter((Q,Y)=>m.has(Y));if(X.length===0)return;c("importing");let K=0;for(const Q of X)try{await i.mutateAsync({first_name:Q.first_name,last_name:Q.last_name||void 0,email:Q.email||void 0,phone:Q.phone||void 0,address:Q.address||void 0}),K++,b(Math.round(K/X.length*100))}catch(Y){console.error(`Failed to import ${Q.first_name} ${Q.last_name}:`,Y)}v(K),c("done")},D=X=>{x(K=>{const Q=new Set(K);return Q.has(X)?Q.delete(X):Q.add(X),Q})},B=()=>{m.size===d.length?x(new Set):x(new Set(d.map((X,K)=>K)))},z=X=>{X||(c("choose"),h([]),x(new Set),v(0),b(0),o==="done"&&r()),t(X)},F=d.filter(X=>X.isDuplicate).length,$=m.size;return e.jsx(vs,{open:s,onOpenChange:z,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(zg,{className:"h-5 w-5 text-primary"}),o==="choose"&&"Import Phone Contacts",o==="preview"&&"Select Contacts to Import",o==="importing"&&"Importing Contacts...",o==="done"&&"Import Complete"]}),o==="choose"&&e.jsx(Fr,{children:"Add contacts from your phone directly into Agent OS."})]}),o==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[N&&e.jsxs(G,{onClick:T,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(zg,{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:[N&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),N&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(G,{variant:N?"outline":"default",onClick:()=>{var X;return(X=l.current)==null?void 0:X.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(oa,{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:N?"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:l,type:"file",accept:".vcf,.vcard",onChange:A,className:"hidden"}),!N&&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"})]})]})]}),o==="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:[d.length," contact",d.length!==1?"s":""," found",F>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",F," already exist)"]})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:B,children:m.size===d.length?"Deselect All":"Select All"})]}),e.jsx(ti,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:d.map((X,K)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${X.isDuplicate?"opacity-60":""}`,onClick:()=>D(K),children:[e.jsx(Ei,{checked:m.has(K),onCheckedChange:()=>D(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:[X.first_name," ",X.last_name]}),X.isDuplicate&&e.jsxs(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",X.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[X.phone&&e.jsx("div",{children:X.phone}),X.email&&e.jsx("div",{className:"truncate",children:X.email})]})]})]},K))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c("choose"),children:"Back"}),e.jsxs(G,{onClick:P,disabled:$===0,children:["Import ",$," Contact",$!==1?"s":""]})]})]}),o==="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:[j,"% 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:`${j}%`}})})]}),o==="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(Hn,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[g," contact",g!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx(G,{onClick:()=>z(!1),className:"mt-2",children:"Done"})]})]})})}function D5s(s){return gt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function R5s(){const{user:s}=As();return gt({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 H.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(r)throw r;const n=t;return{totalSent:n.length,totalOpened:n.filter(a=>a.opened_at).length,totalClicked:n.filter(a=>a.clicked_at).length,totalWatched:n.filter(a=>a.watched_at).length,openRate:n.length>0?Math.round(n.filter(a=>a.opened_at).length/n.length*100):0,clickRate:n.length>0?Math.round(n.filter(a=>a.clicked_at).length/n.length*100):0,watchRate:n.length>0?Math.round(n.filter(a=>a.watched_at).length/n.length*100):0}},enabled:!!(s!=null&&s.id)})}function O5s(){const{user:s}=As();return gt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await H.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 Pmt(){const{user:s}=As(),t=es();return Lt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await H.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 Lmt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function Dmt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const F5s=100;function B5s({open:s,onOpenChange:t,contacts:r,isGmailConnected:n,isMassEmailReady:a,onSendComplete:i}){const l=vr(),o=na(),c=Pmt(),[d,h]=k.useState([]),[m,x]=k.useState(!1),[g,v]=k.useState(""),[j,b]=k.useState(null),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState(!1),[B,z]=k.useState({done:0,total:0,failed:0}),F=r.filter(ce=>!!ce.email),$=r.length-F.length,X=F.length>F5s;k.useEffect(()=>{s&&(b(null),v(""),z({done:0,total:0,failed:0}))},[s]),k.useEffect(()=>{!s||!o||(x(!0),H.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:ce})=>{h(ce||[]),x(!1)}))},[s,o]),k.useEffect(()=>{if(!j)return;const ce=j.title||"a quick video";S(`I recorded a video for you — ${ce}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[j]);const K=d.filter(ce=>!g||(ce.title||"").toLowerCase().includes(g.toLowerCase())),Q=(ce,ae)=>{if(!j)return"";const ie=j.share_token?`https://video.relevelup.com/share/video/${j.share_token}`:"",me=j.share_token?`https://video.relevelup.com/thumb/${j.share_token}`:j.thumbnail_url||"",oe=j.title||"Video Message",be=T.replace(/\{\{first_name\}\}/gi,ce).split(/\n\n+/).map(Pe=>`

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

`).join(""),Oe=ae?Dmt(ae):ie,Me=ae?``:"";return`
${be}

▶ Watch Video

${Me}
`},Y=async()=>{if(!j)return;D(!0),z({done:0,total:F.length,failed:0});let ce=0,ae=0;for(const ie of F)try{let me;try{me=(await c.mutateAsync({video_id:j.id,recipient_email:ie.email,recipient_name:`${ie.first_name} ${ie.last_name||""}`.trim(),contact_id:ie.id,sent_via:"gmail"})).share_token}catch(Me){console.warn("Tracking record failed for",ie.email,Me)}const oe=Q(ie.first_name,me),ge=N.replace(/\{\{first_name\}\}/gi,ie.first_name),{data:be,error:Oe}=await H.functions.invoke("gmail-send",{body:{to:ie.email,subject:ge,body:oe,contactId:ie.id}});if(Oe||!(be!=null&&be.success))throw new Error((be==null?void 0:be.error)||(Oe==null?void 0:Oe.message)||"Send failed");ce+=1}catch(me){console.error("Failed to send to",ie.email,me),ae+=1}finally{z({done:ce+ae,total:F.length,failed:ae}),await new Promise(me=>setTimeout(me,250))}D(!1),ae===0?ue.success(`Video sent to ${ce} ${ce===1?"contact":"contacts"}!`):ue.warning(`Sent to ${ce}, ${ae} failed. Check console for details.`),t(!1),i==null||i()},ne=()=>{if(!j)return;const ce=Q("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:F.map(ae=>({email:ae.email,name:`${ae.first_name} ${ae.last_name||""}`.trim()})),initialSubject:N,initialBodyHtml:ce}}),t(!1)},de=!!j&&!!N.trim()&&F.length>0&&(X?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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5 text-primary"}),"Send Video to ",F.length," ",F.length===1?"Contact":"Contacts"]}),e.jsxs(Fr,{children:[X?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(Cu,{className:"h-3.5 w-3.5"}),F.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),$>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",$," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[X&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Hi,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",F.length," recipients."]})]}),!X&&!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Hi,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("div",{children:"Gmail isn't connected. Connect Gmail in Integrations to send videos."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Choose a video"}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(Ws,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search your video library...",value:g,onChange:ce=>v(ce.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(Vs,{className:"h-14 w-full"}),e.jsx(Vs,{className:"h-14 w-full"})]}):K.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:d.length===0?"No videos yet. Record one to get started.":"No videos match your search."}):K.map(ce=>{const ae=(j==null?void 0:j.id)===ce.id;return e.jsxs("button",{type:"button",onClick:()=>b(ce),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ae?"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:[ce.thumbnail_url?e.jsx("img",{src:ce.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Nh,{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(Ho,{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:ce.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ce.duration_seconds?`${Math.round(ce.duration_seconds)}s`:"",ce.created_at?` · ${new Date(ce.created_at).toLocaleDateString()}`:""]})]})]},ce.id)})})]}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(ke,{id:"bulk-video-subject",value:N,onChange:ce=>S(ce.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(ur,{id:"bulk-video-message",value:T,onChange:ce=>A(ce.target.value),rows:4,className:"resize-y"})]}),P&&B.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",B.done," / ",B.total,B.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",B.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:P,children:"Cancel"}),X?e.jsxs(G,{onClick:ne,disabled:!de,className:"gap-2",children:[e.jsx(Cu,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(G,{onClick:Y,disabled:!de||P,className:"gap-2",children:[P?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),P?"Sending…":`Send to ${F.length}`]})]})]})]})})}function cAe(){const s=na();return gt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 z5s(s){return gt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function $5s(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 Rmt(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 U5s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("drip_campaigns").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function q5s(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const[{data:n,error:a},{data:i,error:l}]=await Promise.all([H.from("drip_campaigns").select("*").eq("id",r).single(),H.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 H.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description,category:n.category,icon:n.icon,cover_color:n.cover_color,goal:n.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(m=>({campaign_id:o.id,step_order:m.step_order,channel:m.channel,subject:m.subject,body:m.body,video_url:m.video_url,delay_type:m.delay_type,delay_days:m.delay_days,delay_hours:m.delay_hours,anchor_field:m.anchor_field,anchor_offset_days:m.anchor_offset_days,send_window_start:m.send_window_start,send_window_end:m.send_window_end})),{error:h}=await H.from("drip_campaign_steps").insert(d);if(h)throw h}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Omt(s){return gt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function V5s(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 H5s(){const s=es();return Lt({mutationFn:async({id:t,campaign_id:r,...n})=>{const{data:a,error:i}=await H.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 G5s(){const s=es();return Lt({mutationFn:async({id:t,campaign_id:r})=>{const{error:n}=await H.from("drip_campaign_steps").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function W5s(s){return gt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 K5s(s){return gt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:r}=await H.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 Fmt(){const s=es();return Lt({mutationFn:async({campaignId:t,contactIds:r})=>{const{data:n,error:a}=await H.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 Y5s(){const s=es();return Lt({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 H.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 Z5s=[{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"}],Ege={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"},X5s={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 sL({userId:s,onSelect:t,onSelectVideo:r,triggerLabel:n="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=k.useState(!1),[d,h]=k.useState([]),[m,x]=k.useState(!1),[g,v]=k.useState("");k.useEffect(()=>{!o||!s||(x(!0),H.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:b})=>{h(b||[]),x(!1)}))},[o,s]);const j=d.filter(b=>!g||(b.title||b.recipient_name||"").toLowerCase().includes(g.toLowerCase()));return e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Nh,{className:"h-3.5 w-3.5"}),n]})}),e.jsxs(ys,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(js,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search videos...",value:g,onChange:b=>v(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"h-16 w-full"}),e.jsx(Vs,{className:"h-16 w-full"})]}):j.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"}):j.map(b=>e.jsxs("button",{onClick:()=>{t(b.playback_url||""),r==null||r(b),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:b.thumbnail_url?e.jsx("img",{src:b.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:N=>{const S=N.currentTarget.parentElement;if(S){N.currentTarget.remove();const T=document.createElement("span");T.innerHTML="🎬",T.className="text-lg",S.appendChild(T)}}}):e.jsx(sn,{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 Q5s(){return gt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await H.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function J5s(s){return gt({queryKey:["video-scripts",s],queryFn:async()=>{let t=H.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 eTs(){const{user:s}=As();return gt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await H.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 tTs(){const{user:s}=As(),t=es();return Lt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await H.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 sTs(s){const{user:t}=As();return gt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let r=H.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 rTs(s){return gt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:r}=await H.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 O_(){const{user:s}=As(),t=es();return Lt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await H.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 nTs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 aTs(){const s=es();return Lt({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 H.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 H.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await H.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 Age(){const{user:s}=As();return gt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await H.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 Bmt(){const{data:s,isLoading:t}=Age(),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 sT(s){const{data:t,error:r}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(r)throw r;return t}async function rT(s){const{data:t,error:r}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}async function u1(s){const{data:t,error:r}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}function iTs(){const{user:s}=As(),t=es();return Lt({mutationFn:async({contactId:r,videoId:n,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await H.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 H.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 zmt({open:s,onOpenChange:t,onUploadComplete:r}){const{data:n}=$m(),{data:a}=Age(),i=O_(),l=k.useRef(null),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(!1),[N,S]=k.useState(0),[T,A]=k.useState("idle"),P=(a==null?void 0:a.total_storage_mb)||0,B=((a==null?void 0:a.max_storage_mb)||1024)-P,z=K=>{var ne;const Q=(ne=K.target.files)==null?void 0:ne[0];if(!Q)return;if(!Q.type.startsWith("video/")){ue.error("Please select a video file");return}const Y=Q.size/(1024*1024);if(Y>500){ue.error("Video file must be less than 500MB");return}if(Y>B){ue.error(`Not enough storage. You have ${B.toFixed(1)} MB remaining.`);return}c(Q),d||h(Q.name.replace(/\.[^/.]+$/,""))},F=async()=>{if(!o){ue.error("Please select a video file");return}b(!0),S(0),A("creating");try{const{data:K,error:Q}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(Q)throw new Error(Q.message);const{videoId:Y,libraryId:ne}=K;A("uploading");const{data:de,error:ce}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Y,isAgentVideo:!0}});if(ce)throw new Error(ce.message);await new Promise((me,oe)=>{const ge=new XMLHttpRequest;ge.upload.addEventListener("progress",be=>{if(be.lengthComputable){const Oe=Math.round(be.loaded/be.total*100);S(Oe)}}),ge.addEventListener("load",()=>{ge.status>=200&&ge.status<300?me():oe(new Error(`Upload failed with status ${ge.status}`))}),ge.addEventListener("error",()=>oe(new Error("Upload failed"))),ge.open("PUT",de.uploadUrl),ge.setRequestHeader("AccessKey",de.apiKey),ge.send(o)}),A("processing");const ae=o.size/(1024*1024),ie=`https://iframe.mediadelivery.net/embed/${ne}/${Y}`;await i.mutateAsync({bunny_video_id:Y,playback_url:ie,file_size_mb:ae,title:d||o.name,notes:m||void 0,contact_id:g||void 0,status:"processing",touch_type:"video_upload"}),ue.success("Video uploaded successfully! Processing may take a few minutes."),r==null||r(ie),$()}catch(K){console.error("Upload error:",K),ue.error(K instanceof Error?K.message:"Failed to upload video")}finally{b(!1),A("idle")}},$=()=>{j||(c(null),h(""),x(""),v(""),S(0),A("idle"),t(!1))},X=()=>{switch(T){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${N}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(vs,{open:s,onOpenChange:$,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Upload Video"}),e.jsx(Fr,{children:"Upload a video file from your device to your video library."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(sn,{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"]})]}),!j&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:K=>{K.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 K;return(K=l.current)==null?void 0:K.click()},children:[e.jsx(oa,{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:z,disabled:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(ke,{id:"title",value:d,onChange:K=>h(K.target.value),placeholder:"Enter video title",disabled:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Associate with Contact (optional)"}),e.jsxs(zs,{value:g||"__none__",onValueChange:K=>v(K==="__none__"?"":K),disabled:j,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a contact"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"__none__",children:"No contact"}),n==null?void 0:n.map(K=>e.jsxs(mt,{value:K.id,children:[K.first_name," ",K.last_name||""]},K.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(ur,{id:"notes",value:m,onChange:K=>x(K.target.value),placeholder:"Add any notes about this video",rows:2,disabled:j})]}),j&&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:X()})]}),e.jsx(ri,{value:T==="uploading"?N:T==="processing"?100:10})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:$,disabled:j,children:"Cancel"}),e.jsx(G,{onClick:F,disabled:!o||j,children:j?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(oa,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const oTs=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"];function $mt({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}=z5s(o||void 0),{data:h,isLoading:m}=Omt(o||void 0),x=$5s(),g=Rmt(),v=V5s(),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState("nurture"),[P,D]=k.useState("🌱"),[B,z]=k.useState("");k.useEffect(()=>{d?(b(d.name),S(d.description||""),A(d.category),D(d.icon),z(d.goal||"")):c||(b(""),S(""),A("nurture"),D("🌱"),z(""))},[d,c,s]);const F=X5s[T],$=async()=>{if(!j.trim()){ue.error("Give your campaign a name");return}try{if(c&&o)await g.mutateAsync({id:o,name:j,description:N,category:T,icon:P,goal:B,cover_color:F}),ue.success("Campaign updated");else{const K=await x.mutateAsync({name:j,description:N,category:T,icon:P,goal:B,cover_color:F});return ue.success("Campaign created — now add your first step!"),a(K.id),l("steps"),K}}catch(K){ue.error(K.message||"Failed to save")}},X=async()=>{if(!o){ue.error("Save the campaign first, then add steps");return}const K=((h==null?void 0:h.length)||0)+1;try{await v.mutateAsync({campaign_id:o,step_order:K,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:K===1?0:2,delay_hours:0})}catch{ue.error("Failed to add step")}};return e.jsx(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 ${F} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:P}),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(Fr,{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(Rn,{value:i,onValueChange:K=>l(K),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Dn,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Xt,{value:"details",children:"Details"}),e.jsxs(Xt,{value:"steps",disabled:!c,children:["Steps ",h&&h.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-[10px]",children:h.length})]})]}),e.jsx(as,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(ti,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Campaign Name *"}),e.jsx(ke,{value:j,onChange:K=>b(K.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Description"}),e.jsx(ur,{value:N,onChange:K=>S(K.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Goal (optional)"}),e.jsx(ke,{value:B,onChange:K=>z(K.target.value),placeholder:"e.g. Book a buyer consultation within 14 days",className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Category"}),e.jsxs(zs,{value:T,onValueChange:K=>A(K),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Object.entries(Ege).map(([K,Q])=>e.jsx(mt,{value:K,children:Q},K))})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:oTs.map(K=>e.jsx("button",{type:"button",onClick:()=>D(K),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${P===K?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:K},K))})]})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Save changes, then jump to the Steps tab to manage your sequence.":"Save to create the campaign, then you can add steps to it."})})]})})}),e.jsx(as,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(ti,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:m?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!h||h.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(jr,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(G,{size:"sm",onClick:X,disabled:v.isPending,children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[h.map((K,Q)=>e.jsx(lTs,{step:K,index:Q,totalSteps:h.length},K.id)),e.jsxs(G,{variant:"outline",size:"sm",onClick:X,disabled:v.isPending,className:"w-full",children:[v.isPending?e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(on,{className:"border-t p-4 shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(G,{onClick:$,disabled:x.isPending||g.isPending,children:[(x.isPending||g.isPending)&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function lTs({step:s,index:t,totalSteps:r}){const n=H5s(),a=G5s(),i=na(),[l,o]=k.useState(!1),[c,d]=k.useState(s),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(""),[b,N]=k.useState(!1);k.useEffect(()=>d(s),[s]);const S=JSON.stringify(c)!==JSON.stringify(s),T=async()=>{m(!0);try{await n.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),ue.success(`Step ${t+1} saved`)}catch{ue.error("Failed to save step")}finally{m(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ue.success("Step deleted")}catch{ue.error("Failed to delete")}},P=B=>{d({...c,body:c.body+B})},D=()=>{if(c.delay_type==="calendar_anchor"){const z=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${z}`:F<0?`${Math.abs(F)}d before ${z}`:`${F}d after ${z}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const B=[];return c.delay_days&&B.push(`${c.delay_days}d`),c.delay_hours&&B.push(`${c.delay_hours}h`),t===0?`After ${B.join(" ")||"0"}`:`+${B.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(rn,{className:"h-3 w-3"}):e.jsx(cn,{className:"h-3 w-3"}),e.jsx("span",{children:D()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Qs,{className:"h-3 w-3"}):e.jsx(bi,{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(xp,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(so,{className:"h-4 w-4 text-muted-foreground"})]}),l&&e.jsxs("div",{className:"border-t p-4 space-y-3 bg-muted/10",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Channel"}),e.jsxs(zs,{value:c.channel,onValueChange:B=>d({...c,channel:B}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsx(Fs,{children:e.jsx(mt,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Timing Type"}),e.jsxs(zs,{value:c.delay_type,onValueChange:B=>d({...c,delay_type:B}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"relative",children:"⏱ Relative delay"}),e.jsx(mt,{value:"calendar_anchor",children:"📅 Calendar date"})]})]})]})]}),c.delay_type==="relative"?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Days delay"}),e.jsx(ke,{type:"number",min:0,value:c.delay_days,onChange:B=>d({...c,delay_days:parseInt(B.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Hours delay"}),e.jsx(ke,{type:"number",min:0,max:23,value:c.delay_hours,onChange:B=>d({...c,delay_hours:parseInt(B.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Anchor"}),e.jsxs(zs,{value:c.anchor_field||"birthday",onValueChange:B=>d({...c,anchor_field:B}),children:[e.jsx(Os,{className:"mt-1 h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"birthday",children:"🎂 Birthday"}),e.jsx(mt,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(ke,{type:"number",value:c.anchor_offset_days||0,onChange:B=>d({...c,anchor_offset_days:parseInt(B.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject Line"}),e.jsx(ke,{value:c.subject,onChange:B=>d({...c,subject:B.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(he,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(ur,{value:c.body,onChange:B=>d({...c,body:B.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:"}),Z5s.map(B=>e.jsx("button",{type:"button",onClick:()=>P(B.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:B.label},B.key))]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Video (optional)"}),c.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(sn,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(sL,{userId:i||void 0,onSelect:B=>d({...c,video_url:B}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>N(!0),children:[e.jsx(oa,{className:"h-3 w-3"})," Upload"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{j(""),g(!0)},children:[e.jsx(xo,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(zmt,{open:b,onOpenChange:N,onUploadComplete:B=>d({...c,video_url:B})}),e.jsx(vs,{open:x,onOpenChange:g,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add video URL"}),e.jsx(Fr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(ke,{value:v,onChange:B=>j(B.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:B=>{B.key==="Enter"&&v.trim()&&(d({...c,video_url:v.trim()}),g(!1))}}),e.jsxs(on,{children:[e.jsx(G,{variant:"ghost",onClick:()=>g(!1),children:"Cancel"}),e.jsx(G,{disabled:!v.trim(),onClick:()=>{d({...c,video_url:v.trim()}),g(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(G,{size:"sm",onClick:T,disabled:!S||h,children:[h&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function cTs({open:s,onOpenChange:t,contactIds:r,onSuccess:n}){const{data:a,isLoading:i}=cAe(),l=Fmt(),[o,c]=k.useState(""),[d,h]=k.useState(null),[m,x]=k.useState(!1),g=(a||[]).filter(b=>!b.is_starter),v=g.filter(b=>b.name.toLowerCase().includes(o.toLowerCase())||(b.description||"").toLowerCase().includes(o.toLowerCase())),j=async()=>{if(d)try{const b=await l.mutateAsync({campaignId:d,contactIds:r}),N=[`${b.enrolled} enrolled`];b.skipped>0&&N.push(`${b.skipped} skipped`),b.errors>0&&N.push(`${b.errors} errors`),ue.success(N.join(" · ")),t(!1),h(null),n==null||n()}catch(b){ue.error(b.message||"Failed to enroll contacts")}};return e.jsxs(vs,{open:s,onOpenChange:t,children:[e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Fr,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search campaigns...",value:o,onChange:b=>c(b.target.value),className:"pl-9 h-9"})]}),e.jsx(ti,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):v.length===0?e.jsx("div",{className:"text-center py-8",children:g.length===0?e.jsxs(e.Fragment,{children:[e.jsx(jr,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(G,{size:"sm",onClick:()=>x(!0),children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:v.map(b=>e.jsxs("button",{onClick:()=>h(b.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===b.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${b.cover_color} flex items-center justify-center text-lg`,children:b.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),b.is_active&&e.jsx(Ge,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:b.description})]}),d===b.id&&e.jsx(Hn,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},b.id))})})]}),e.jsxs(on,{className:"gap-2 sm:gap-2",children:[g.length>0&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>x(!0),className:"mr-auto text-xs",children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:j,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($mt,{open:m,onOpenChange:x})]})}function dTs({selectedIds:s,contacts:t,onClearSelection:r,onSendToLeadPond:n,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=vr(),{data:c}=qx(),d=E5e(),h=es(),{isGmailConnected:m}=Oh(),{isReady:x}=Az(),{data:g}=eL(),v=aAe(),j=Tmt(),[b,N]=k.useState(!1),[S,T]=k.useState(!1),[A,P]=k.useState(!1),[D,B]=k.useState(!1),[z,F]=k.useState(!1),[$,X]=k.useState(""),K=s.size;if(K===0)return null;const Q=async me=>{N(!0);try{const ge=Array.from(s).map(Oe=>({contact_id:Oe,relationship_type_id:me})),{error:be}=await H.from("innercircle_contact_tags").upsert(ge,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(be)throw be;h.invalidateQueries({queryKey:["innercircle-contacts"]}),h.invalidateQueries({queryKey:["innercircle-contact-counts"]}),nn({title:`Assigned type to ${K} contacts`}),r()}catch(oe){nn({title:"Error assigning type",description:oe.message,variant:"destructive"})}finally{N(!1)}},Y=async me=>{N(!0);try{const oe=Array.from(s);for(const ge of oe)try{await j.mutateAsync({contactId:ge,tagId:me})}catch{}h.invalidateQueries({queryKey:["all-contact-custom-tags"]}),nn({title:`Tagged ${K} contacts`}),F(!1),X("")}catch(oe){nn({title:"Error adding tags",description:oe.message,variant:"destructive"})}finally{N(!1)}},ne=async()=>{if($.trim()){N(!0);try{const me=await v.mutateAsync({name:$.trim()});await Y(me.id)}catch(me){nn({title:"Error creating tag",description:me.message,variant:"destructive"}),N(!1)}}},de=(g==null?void 0:g.filter(me=>me.name.toLowerCase().includes($.toLowerCase())))||[],ce=g==null?void 0:g.find(me=>me.name.toLowerCase()===$.trim().toLowerCase()),ae=()=>{const me=t.filter(Ee=>s.has(Ee.id)),oe=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],ge=me.map(Ee=>{var $e;return[Ee.first_name,Ee.last_name||"",Ee.email||"",Ee.phone||"",Ee.address||"",Ee.birthday||"",Ee.home_anniversary||"",Ee.notes||"",(($e=Ee.tags)==null?void 0:$e.map(Se=>{var ze;return(ze=Se.relationship_type)==null?void 0:ze.name}).join("; "))||""]}),be=[oe.join(","),...ge.map(Ee=>Ee.map($e=>`"${($e||"").replace(/"/g,'""')}"`).join(","))].join(` `),Oe=new Blob([be],{type:"text/csv"}),Me=URL.createObjectURL(Oe),Pe=document.createElement("a");Pe.href=Me,Pe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Pe.click(),URL.revokeObjectURL(Me),nn({title:`Exported ${K} contacts`})},ie=async()=>{if(confirm(`Are you sure you want to delete ${K} contacts? This cannot be undone.`)){N(!0);try{const me=Array.from(s);for(const oe of me)await d.mutateAsync(oe);r()}catch(me){nn({title:"Error deleting contacts",description:me.message,variant:"destructive"})}finally{N(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(Ge,{variant:"secondary",className:"font-semibold",children:[K," selected"]}),e.jsxs(zs,{onValueChange:Q,disabled:b,children:[e.jsx(Os,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ah,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(Fs,{children:c==null?void 0:c.filter(me=>me.active).map(me=>e.jsx(mt,{value:me.id,children:me.name},me.id))})]}),e.jsxs(Ao,{open:z,onOpenChange:F,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",disabled:b,children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(wo,{className:"w-56 p-2",align:"start",children:[e.jsx(ke,{placeholder:"Search or create tag...",value:$,onChange:me=>X(me.target.value),onKeyDown:me=>{me.key==="Enter"&&$.trim()&&!ce?(me.preventDefault(),ne()):me.key==="Enter"&&ce&&(me.preventDefault(),Y(ce.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[de.map(me=>e.jsxs("button",{onClick:()=>Y(me.id),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:me.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:me.name})]},me.id)),$.trim()&&!ce&&e.jsxs("button",{onClick:ne,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(Ws,{className:"h-3.5 w-3.5"}),'Create "',$.trim(),'"']}),de.length===0&&!$.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),m&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:b,children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),x&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{const me=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${me}`)},disabled:b,children:[e.jsx(Cu,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:b,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>B(!0),disabled:b,children:[e.jsx(jr,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&n&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>n(Array.from(s)),disabled:b,children:[e.jsx(t0,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:b,children:[e.jsx(Xb,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ae,disabled:b,children:[e.jsx(Xa,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ie,disabled:b,className:"text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:r,className:"ml-auto",children:[e.jsx(_r,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(cTs,{open:D,onOpenChange:B,contactIds:Array.from(s),onSuccess:r}),e.jsx(j1,{open:S,onOpenChange:T,bulkContacts:Array.from(s).map(me=>{const oe=t.find(ge=>ge.id===me);return oe?{id:oe.id,first_name:oe.first_name,last_name:oe.last_name,email:oe.email||""}:null}).filter(me=>me!==null&&me.email!==""),onSendComplete:()=>{T(!1),r()}}),e.jsx(B5s,{open:A,onOpenChange:P,contacts:Array.from(s).map(me=>t.find(oe=>oe.id===me)).filter(me=>!!me).map(me=>({id:me.id,first_name:me.first_name,last_name:me.last_name,email:me.email})),isGmailConnected:!!m,isMassEmailReady:!!x,onSendComplete:()=>{P(!1),r()}})]})}function xqe({contact:s,onEdit:t,onDelete:r,onSnooze:n,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=vr(),{isReady:d}=Az(),h=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:m=>m.stopPropagation(),children:e.jsx(ix,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",onClick:m=>m.stopPropagation(),children:[e.jsxs(Da,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Da,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Da,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Da,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Da,{onClick:()=>n(s.id,h),children:[e.jsx(cm,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Da,{onClick:()=>a(s.id),children:[e.jsx(t0,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Da,{onClick:()=>l(s.id),children:[e.jsx(Xb,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Da,{onClick:()=>t(s),children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Da,{onClick:()=>r(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function uTs({currentFilters:s,currentSortBy:t,onApplySmartList:r}){const{data:n}=Emt(),a=g3s(),i=y3s(),[l,o]=k.useState(!1),[c,d]=k.useState(""),h=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all",m=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(s0,{className:"h-3.5 w-3.5"}),"Smart Filters",n&&n.length>0&&e.jsx(Ge,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:n.length}),e.jsx(so,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Vd,{align:"start",className:"w-56",children:[n&&n.length>0?e.jsxs(e.Fragment,{children:[n.map(x=>e.jsxs(Da,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>r(x.filters,x.sort_by),children:x.name}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:g=>{g.stopPropagation(),i.mutate(x.id)},children:e.jsx(yr,{className:"h-3 w-3 text-destructive"})})]},x.id)),e.jsx(y_,{})]}):e.jsx(Da,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),h&&e.jsxs(Da,{onClick:()=>o(!0),children:[e.jsx(YR,{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(js,{children:e.jsx(bs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ke,{placeholder:"e.g. Buyers in 40205",value:c,onChange:x=>d(x.target.value),onKeyDown:x=>x.key==="Enter"&&m(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{onClick:m,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}function gqe(s){if(!s)return null;const t=Ul(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:nl,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:cn,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:Ev,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:Eh,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:Cn,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:Yu,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:gc,gradient:"from-indigo-500/15 via-blue-500/10 to-transparent",iconBg:"bg-indigo-500/15",iconColor:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",subtitle:"Top relationships",icon:jr,gradient:"from-amber-400/20 via-yellow-300/10 to-transparent",iconBg:"bg-amber-400/20",iconColor:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",subtitle:"No email or phone",icon:od,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 hTs({contacts:s,contactDealsMap:t,websiteActiveIds:r,activeKey:n,onSelect:a}){const i=k.useRef(null),l=k.useMemo(()=>{const c={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":r.size,"missing-info":0,vips:0};if(!s)return c;for(const d of s){const h={hasDeal:!!(t&&t[d.id]),daysToBirthday:gqe(d.birthday),daysToAnniv:gqe(d.home_anniversary)};for(const m of yqe)m.key!=="website-active"&&m.match(d,h)&&c[m.key]++}return c},[s,t,r]),o=c=>{var d;(d=i.current)==null||d.scrollBy({left:c,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Smart Segments"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-organized for you"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n&&e.jsxs("button",{onClick:()=>a(null),className:"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx(_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(Vo,{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(ya,{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:yqe.map(c=>{const d=c.icon,h=l[c.key],m=n===c.key,x=h===0;return e.jsxs("button",{onClick:()=>a(m?null:c.key),disabled:x&&!m,className:`group relative shrink-0 snap-start w-[180px] text-left rounded-xl border transition-all duration-200 overflow-hidden ${m?"border-[#406E71] ring-2 ring-[#406E71]/30 shadow-lg scale-[1.02] bg-card":x?"border-border/40 bg-card/50 opacity-50 cursor-not-allowed":"border-border hover:border-[#406E71]/50 hover:shadow-md hover:-translate-y-0.5 bg-card cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${c.gradient} pointer-events-none`}),e.jsxs("div",{className:"relative p-3.5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg ${c.iconBg} flex items-center justify-center`,children:e.jsx(d,{className:`h-4.5 w-4.5 ${c.iconColor}`,strokeWidth:2.25})}),e.jsx("div",{className:"text-right",children:e.jsx("div",{className:"text-2xl font-bold leading-none text-foreground tabular-nums",children:h.toLocaleString()})})]}),e.jsx("div",{className:"text-sm font-semibold text-foreground leading-tight",children:c.title}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5 leading-tight",children:c.subtitle})]})]},c.key)})})]})}const Umt="innercircle_geocode_cache_v1";function mTs(){try{return JSON.parse(localStorage.getItem(Umt)||"{}")}catch{return{}}}function fTs(s){try{localStorage.setItem(Umt,JSON.stringify(s))}catch{}}function pTs(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 xTs({open:s,onOpenChange:t,contacts:r,onCitySelect:n}){const a=k.useRef(null),i=k.useRef(null),[l,o]=k.useState(""),[c,d]=k.useState(!0),[h,m]=k.useState([]),[x,g]=k.useState({done:0,total:0}),[v,j]=k.useState(!1),[b,N]=k.useState("heat");k.useEffect(()=>{if(!s)return;let T=!1;return(async()=>{d(!0);const{data:A}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();T||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{T=!0}},[s]),k.useEffect(()=>{if(!s||!l)return;let T=!1;return(async()=>{const P=mTs(),D=r.map(Y=>({c:Y,addr:pTs(Y)})).filter(Y=>Y.addr),B=[],z=[];for(const{c:Y,addr:ne}of D){const de=P[ne];de!==null&&(de?B.push({id:Y.id,name:`${Y.first_name||""} ${Y.last_name||""}`.trim(),city:Y.city||null,state:Y.state||null,zip:Y.zip||Y.zip_code||null,lat:de.lat,lng:de.lng}):z.push({c:Y,addr:ne}))}if(T||m(B),g({done:B.length,total:D.length}),z.length===0)return;j(!0);const F=6;let $=0;const X={...P},K=[...B],Q=async()=>{var Y;for(;${T=!0}},[s,l,r]);const S=k.useMemo(()=>{const T=new Map;for(const A of r){const P=(A.city||"").trim();if(!P)continue;const D=(A.state||"").trim()||null,B=`${P.toLowerCase()}|${D||""}`,z=T.get(B);z?z.count++:T.set(B,{city:P,state:D,count:1})}return Array.from(T.values()).sort((A,P)=>P.count-A.count)},[r]);return k.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return El.accessToken=l,i.current=new El.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new El.NavigationControl,"top-right"),()=>{var T;(T=i.current)==null||T.remove(),i.current=null}},[s,l]),k.useEffect(()=>{const T=i.current;if(!T||h.length===0)return;const A=()=>{const D={type:"FeatureCollection",features:h.map(z=>({type:"Feature",properties:{id:z.id,name:z.name},geometry:{type:"Point",coordinates:[z.lng,z.lat]}}))},B=T.getSource("contacts-src");if(B?B.setData(D):(T.addSource("contacts-src",{type:"geojson",data:D}),T.addLayer({id:"contacts-heat",type:"heatmap",source:"contacts-src",maxzoom:15,paint:{"heatmap-weight":1,"heatmap-intensity":["interpolate",["linear"],["zoom"],0,1,15,3],"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(64,110,113,0)",.2,"rgba(64,110,113,0.4)",.4,"rgba(56,189,248,0.6)",.6,"rgba(250,204,21,0.7)",.8,"rgba(249,115,22,0.85)",1,"rgba(220,38,38,1)"],"heatmap-radius":["interpolate",["linear"],["zoom"],0,12,9,30,15,60],"heatmap-opacity":["interpolate",["linear"],["zoom"],13,1,15,.6]}}),T.addLayer({id:"contacts-points",type:"circle",source:"contacts-src",paint:{"circle-radius":["interpolate",["linear"],["zoom"],0,4,8,5,16,9],"circle-color":"#406E71","circle-stroke-color":"#ffffff","circle-stroke-width":1.5,"circle-opacity":.9}}),T.on("click","contacts-points",z=>{var X;const F=(X=z.features)==null?void 0:X[0];if(!F)return;const $=F.geometry.coordinates.slice();new El.Popup({offset:12}).setLngLat($).setHTML(`
${F.properties.name||"Contact"}
`).addTo(T)}),T.on("mouseenter","contacts-points",()=>{T.getCanvas().style.cursor="pointer"}),T.on("mouseleave","contacts-points",()=>{T.getCanvas().style.cursor=""})),T.getLayer("contacts-heat")&&T.setLayoutProperty("contacts-heat","visibility",b==="heat"?"visible":"none"),T.getLayer("contacts-points")&&(T.setPaintProperty("contacts-points","circle-opacity",b==="points"?.9:0),T.setLayoutProperty("contacts-points","visibility","visible")),h.length>0&&!T._fitDone){const z=new El.LngLatBounds;h.forEach(F=>z.extend([F.lng,F.lat]));try{T.fitBounds(z,{padding:60,maxZoom:11,duration:600}),T._fitDone=!0}catch{}}};T.isStyleLoaded()?A():T.once("load",A)},[h,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(js,{className:"p-4 pb-2 border-b",children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(xc,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[h.length," mapped · ",S.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(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(G,{size:"sm",variant:b==="heat"?"default":"ghost",onClick:()=>N("heat"),className:"h-8",children:[e.jsx(xc,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(G,{size:"sm",variant:b==="points"?"default":"ghost",onClick:()=>N("points"),className:"h-8",children:[e.jsx(uO,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),v&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(ls,{className:"h-3 w-3 animate-spin"}),"Mapping ",x.done," / ",x.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Hi,{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(ja,{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(ti,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[S.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),S.slice(0,50).map((T,A)=>{var B;const P=((B=S[0])==null?void 0:B.count)||1,D=T.count/P*100;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{n==null||n(T.city,T.state),t(!1)},children:e.jsxs(De,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${D}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[T.city,T.state?`, ${T.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(Ge,{variant:"secondary",className:"shrink-0",children:T.count})]})]})},`${T.city}-${T.state}-${A}`)})]})})]})]})]})})}function I4(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 bqe({birthday:s,homeAnniversary:t,className:r,contactId:n,contactName:a,contactAddress:i}){const l=vr(),o=vqe(s,"birthday",7),c=vqe(t,"anniversary",7);if(!o&&!c)return null;const d=(h,m)=>{m.stopPropagation();const x=new URLSearchParams;n&&x.set("contactId",n),a&&x.set("name",a),i&&x.set("address",i),h==="home_anniversary"&&t&&x.set("date",t),x.set("cardType",h),l(`/mission-control/card-studio?${x.toString()}`)};return e.jsxs("div",{className:Bt("flex flex-wrap gap-1",r),children:[o&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ge,{variant:"secondary",className:Bt("text-[10px] gap-0.5 font-medium",o.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:o.label}),n&&e.jsxs("button",{onClick:h=>d("birthday",h),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(Qs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ge,{variant:"secondary",className:Bt("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:c.label}),n&&e.jsxs("button",{onClick:h=>d("home_anniversary",h),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(Qs,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function _qe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 font-medium whitespace-nowrap",style:{borderColor:t.color,color:t.color,backgroundColor:`${t.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.name]})}function wqe({count:s,className:t}){return!s||s<=0?null:e.jsxs(Ge,{variant:"outline",className:Bt("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(G3,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function gTs(){const s=na();return gt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:r}=await H.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 yTs(){const s=na();return gt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:r}=await H.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 vTs({contactId:s,compact:t=!1}){const{data:r}=eL(),{data:n}=m3s(s),a=aAe(),i=Tmt(),l=x3s(),[o,c]=k.useState(!1),[d,h]=k.useState(""),m=k.useRef(null),x=new Set((n==null?void 0:n.map(N=>N.tag_id))||[]),g=(r==null?void 0:r.filter(N=>N.name.toLowerCase().includes(d.toLowerCase())))||[],v=r==null?void 0:r.find(N=>N.name.toLowerCase()===d.trim().toLowerCase()),j=async N=>{x.has(N.id)?await l.mutateAsync({contactId:s,tagId:N.id}):await i.mutateAsync({contactId:s,tagId:N.id})},b=async()=>{if(!(!d.trim()||v))try{const N=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:N.id}),h("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n==null?void 0:n.map(N=>{var S,T,A;return e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((S=N.tag)==null?void 0:S.color)||"#6366F1",color:((T=N.tag)==null?void 0:T.color)||"#6366F1"},children:[e.jsx(Ah,{className:"h-2.5 w-2.5"}),(A=N.tag)==null?void 0:A.name,e.jsx("button",{onClick:P=>{P.stopPropagation(),l.mutate({contactId:s,tagId:N.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"})})]},N.id)}),e.jsxs(Ao,{open:o,onOpenChange:c,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:N=>N.stopPropagation(),children:[e.jsx(Ws,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(wo,{className:"w-56 p-2",align:"start",onClick:N=>N.stopPropagation(),children:[e.jsx(ke,{ref:m,placeholder:"Search or create tag...",value:d,onChange:N=>h(N.target.value),onKeyDown:N=>{N.key==="Enter"&&d.trim()&&!v?(N.preventDefault(),b()):N.key==="Enter"&&v&&!x.has(v.id)&&(N.preventDefault(),j(v))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[g.map(N=>e.jsxs("button",{onClick:()=>j(N),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:N.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:N.name}),x.has(N.id)&&e.jsx(Hn,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},N.id)),d.trim()&&!v&&e.jsxs("button",{onClick:b,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Ws,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),g.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 jqe({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(r=>{var n,a,i;return e.jsx(Ge,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((n=r.tag)==null?void 0:n.color)||"#6366F1",color:((a=r.tag)==null?void 0:a.color)||"#6366F1"},children:(i=r.tag)==null?void 0:i.name},r.tag_id)})})}const GU=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function bTs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=eL(),a=aAe(),i=p3s(),l=f3s(),[o,c]=k.useState(""),[d,h]=k.useState(GU[0]),[m,x]=k.useState(null),[g,v]=k.useState(""),[j,b]=k.useState(""),N=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),h(GU[0]),nn({title:"Tag created"})}catch(P){nn({title:"Error",description:P.message,variant:"destructive"})}},S=async P=>{if(g.trim())try{await i.mutateAsync({id:P,name:g.trim(),color:j}),x(null),nn({title:"Tag updated"})}catch(D){nn({title:"Error",description:D.message,variant:"destructive"})}},T=async(P,D)=>{if(confirm(`Delete tag "${D}"? It will be removed from all contacts.`))try{await l.mutateAsync(P),nn({title:"Tag deleted"})}catch(B){nn({title:"Error",description:B.message,variant:"destructive"})}},A=P=>{x(P.id),v(P.name),b(P.color)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{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(ke,{placeholder:"New tag name...",value:o,onChange:P=>c(P.target.value),onKeyDown:P=>P.key==="Enter"&&N(),className:"flex-1 h-9"}),e.jsxs(G,{size:"sm",onClick:N,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:GU.map(P=>e.jsx("button",{onClick:()=>h(P),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===P?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:P}},P))})]}),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(P=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:m===P.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:GU.map(D=>e.jsx("button",{onClick:()=>b(D),className:`h-5 w-5 rounded-full border-2 ${j===D?"border-foreground":"border-transparent"}`,style:{backgroundColor:D}},D))}),e.jsx(ke,{value:g,onChange:D=>v(D.target.value),onKeyDown:D=>D.key==="Enter"&&S(P.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>S(P.id),children:e.jsx(Hn,{className:"h-4 w-4 text-primary"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(null),children:e.jsx(_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:P.color}}),e.jsx("span",{className:"flex-1 text-sm",children:P.name}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(P),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>T(P.id,P.name),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})},P.id))]})]})})}function _Ts({open:s,onOpenChange:t}){const{data:r,isLoading:n}=IP(),a=M5e(),i=mUt(),l=fUt(),[o,c]=k.useState(""),[d,h]=k.useState(null),[m,x]=k.useState(""),g=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(N){ue.error(N.message||"Failed to add lead source")}},v=async N=>{if(m.trim())try{await i.mutateAsync({id:N,name:m.trim()}),h(null)}catch(S){ue.error(S.message||"Failed to update")}},j=async(N,S)=>{if(confirm(`Remove lead source "${S}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(N)}catch(T){ue.error(T.message||"Failed to remove")}},b=N=>{h(N.id),x(N.name)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(bs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"New lead source name...",value:o,onChange:N=>c(N.target.value),onKeyDown:N=>N.key==="Enter"&&g(),className:"flex-1 h-9"}),e.jsxs(G,{size:"sm",onClick:g,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),r==null?void 0:r.map(N=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===N.id?e.jsxs(e.Fragment,{children:[e.jsx(ke,{value:m,onChange:S=>x(S.target.value),onKeyDown:S=>S.key==="Enter"&&v(N.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>v(N.id),children:e.jsx(Hn,{className:"h-4 w-4 text-primary"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(null),children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:N.name}),N.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>b(N),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>j(N.id,N.name),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),!N.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},N.id))]})]})})}function qmt({value:s,onChange:t,label:r="Lead Source"}){const{data:n}=IP(),a=M5e(),[i,l]=k.useState(!1),[o,c]=k.useState(""),d=async()=>{if(o.trim())try{const h=await a.mutateAsync(o.trim());h&&(t(h.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:r}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{value:s||"_none",onValueChange:h=>t(h==="_none"?"":h),children:[e.jsx(Os,{className:"flex-1",children:e.jsx(Us,{placeholder:"Select lead source"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"_none",children:"No source"}),n==null?void 0:n.map(h=>e.jsx(mt,{value:h.id,children:h.name},h.id))]})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(_r,{className:"h-4 w-4"}):e.jsx(Ws,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"New lead source name...",value:o,onChange:h=>c(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())},className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function bSe({contactId:s,currentSpouseContactId:t,currentSpouseName:r,currentSpouseEmail:n,onLink:a,onUnlink:i,isEditing:l}){const o=vr(),[c,d]=k.useState(!1),[h,m]=k.useState(""),{data:x}=gt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:v,error:j}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(j)throw j;return v},enabled:!!t}),{data:g}=gt({queryKey:["spouse-search",h],queryFn:async()=>{let v=H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").neq("id",s).order("first_name").limit(20);h.trim()&&(v=v.or(`first_name.ilike.%${h}%,last_name.ilike.%${h}%,email.ilike.%${h}%,phone.ilike.%${h}%`));const{data:j,error:b}=await v;if(b)throw b;return j},enabled:c});if(t&&x){const v=`${x.first_name} ${x.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(Bi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${x.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:v}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[x.phone,x.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(W3,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${x.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Ga,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(r||n)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(Bi,{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(Ao,{open:c,onOpenChange:d,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(rl,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(wo,{className:"w-72 p-2",align:"end",children:e.jsx(Nqe,{search:h,setSearch:m,results:g,onSelect:v=>{a(v),d(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(Ao,{open:c,onOpenChange:d,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(rl,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(wo,{className:"w-72 p-2",align:"start",children:e.jsx(Nqe,{search:h,setSearch:m,results:g,onSelect:v=>{a(v),d(!1),m("")}})})]})]}):null}function Nqe({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(fn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(ti,{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 wTs(){var Na;const s=vr(),[t,r]=Lc(),{user:n}=As(),a=tL(),i=es(),l=t.get("type"),o=t.get("filter")??t.get("status"),c=t.get("new")==="true",{contactsWithScores:d,isLoading:h}=nxe(),{activeContactIds:m,hasLeadSite:x}=C5s(),{data:g}=gTs(),{data:v}=qx(),{data:j}=yTs(),{data:b}=eL(),{data:N}=iAe(),[S,T]=k.useState(new Set),[A,P]=k.useState("any"),D=exe(),B=T5e(),z=E5e(),F=Vnt(),[$,X]=k.useState(""),[K,Q]=k.useState(!1),[Y,ne]=k.useState(l||"all"),[de,ce]=k.useState(o||"all"),[ae,ie]=k.useState("date-added"),[me,oe]=k.useState(c),[ge,be]=k.useState(null),[Oe,Me]=k.useState(!1),[Pe,Ee]=k.useState(!1),[$e,Se]=k.useState(null),[ze,Te]=k.useState(""),[ye,ct]=k.useState(new Set),[ve,rt]=k.useState(!1),Re=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Qe,Ke]=k.useState(Re),Ce=k.useCallback(Je=>{Ke(Fe=>{const We=typeof Je=="function"?Je(Fe):Je;return r(He=>{const bt=new URLSearchParams(He);return We<=1?bt.delete("page"):bt.set("page",String(We)),bt},{replace:!0}),We})},[]),[nt,$t]=k.useState(50),[lt,it]=k.useState("my"),[Nt,Ft]=k.useState(!1),[at,Ie]=k.useState(!1),{data:et}=Xg(),{addToLeadPond:Dt}=Ylt(et==null?void 0:et.teamId),Jt=!!((Na=et==null?void 0:et.team)!=null&&Na.lead_pond_enabled&&(et!=null&&et.teamId)),cs=!!(et!=null&&et.teamId),[Ht,dt]=k.useState([]),[Qt,yt]=k.useState(!1),ss=Je=>{dt([Je]),yt(!0)},Is=Je=>{dt(Je),yt(!0)},fs=Je=>{et!=null&&et.teamId&&Dt.mutate({contact_id:Je,team_id:et.teamId})},ar=Je=>{et!=null&&et.teamId&&Je.forEach(Fe=>{Dt.mutate({contact_id:Fe,team_id:et.teamId})})},Er=k.useCallback(Je=>{rt(!1),ct(Fe=>{const We=new Set(Fe);return We.has(Je)?We.delete(Je):We.add(Je),We})},[]);k.useEffect(()=>{if(!(n!=null&&n.id))return;const Je=H.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()=>{H.removeChannel(Je)}},[i,n==null?void 0:n.id]),k.useEffect(()=>{o&&ce(o)},[o]);const[Tr,Lr]=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&&oe(!0)},[c]),k.useEffect(()=>{var Je;ge&&Lr({first_name:ge.first_name||"",last_name:ge.last_name||"",email:ge.email||"",phone:ge.phone||"",address:ge.address||"",city:ge.city||"",state:ge.state||"",zip_code:ge.zip_code||"",birthday:ge.birthday||"",home_anniversary:ge.home_anniversary||"",spouse_name:ge.spouse_name||"",spouse_email:ge.spouse_email||"",lead_source_id:ge.lead_source_id||"",notes:ge.notes||"",tagIds:((Je=ge.tags)==null?void 0:Je.map(Fe=>Fe.relationship_type_id))||[]})},[ge]);const $r=k.useMemo(()=>{if(!d)return[];let Je=d.filter(Fe=>{var ut,kt,Gt,Mt,Kt;const We=$===""||`${Fe.first_name} ${Fe.last_name}`.toLowerCase().includes($.toLowerCase())||((ut=Fe.email)==null?void 0:ut.toLowerCase().includes($.toLowerCase()))||((kt=Fe.phone)==null?void 0:kt.includes($))||((Gt=Fe.city)==null?void 0:Gt.toLowerCase().includes($.toLowerCase()))||((Mt=Fe.state)==null?void 0:Mt.toLowerCase().includes($.toLowerCase())),He=Y==="all"||((Kt=Fe.tags)==null?void 0:Kt.some(Es=>Es.relationship_type_id===Y)),bt=S.size===0||(()=>{const Es=(N==null?void 0:N.filter(Ls=>Ls.contact_id===Fe.id).map(Ls=>Ls.tag_id))||[];return A==="any"?Es.some(Ls=>S.has(Ls)):Array.from(S).every(Ls=>Es.includes(Ls))})();return We&&He&&bt});return de==="not-touched-90"?Je=Je.filter(Fe=>{const We=Fe.relationshipScore.daysSinceTouch;return We===null||We>90}):de==="at-risk"?Je=Je.filter(Fe=>Fe.relationshipScore.status==="at-risk"):de==="cooling"?Je=Je.filter(Fe=>Fe.relationshipScore.status==="cooling"):de==="warm"?Je=Je.filter(Fe=>Fe.relationshipScore.status==="warm"):de==="has-deal"?Je=Je.filter(Fe=>j&&j[Fe.id]):de==="no-deal"?Je=Je.filter(Fe=>!j||!j[Fe.id]):de==="open-house"?Je=Je.filter(Fe=>{var He;return(((He=Fe.lead_source_ref)==null?void 0:He.name)||Fe.lead_source)==="Open House"}):de==="website-active"?Je=Je.filter(Fe=>m.has(Fe.id)):de==="never-contacted"?Je=Je.filter(Fe=>Fe.relationshipScore.daysSinceTouch===null):de==="vips"?Je=Je.filter(Fe=>Fe.relationshipScore.score>=80):de==="missing-info"?Je=Je.filter(Fe=>{var We,He;return!((We=Fe.email)!=null&&We.trim())&&!((He=Fe.phone)!=null&&He.trim())}):de==="birthdays-soon"?Je=Je.filter(Fe=>{const We=I4(Fe.birthday);return We!==null&&We<=30}):de==="anniversary-soon"?Je=Je.filter(Fe=>{const We=I4(Fe.home_anniversary);return We!==null&&We<=30}):de==="in-drip"?Je=Je.filter(Fe=>((g==null?void 0:g[Fe.id])??0)>0):de==="not-in-drip"&&(Je=Je.filter(Fe=>((g==null?void 0:g[Fe.id])??0)===0)),Je=[...Je].sort((Fe,We)=>{switch(ae){case"important-dates":{const He=I4(Fe.birthday),bt=I4(We.birthday),ut=I4(Fe.home_anniversary),kt=I4(We.home_anniversary),Gt=[He,ut].filter(Kt=>Kt!==null).sort((Kt,Es)=>(Kt??1/0)-(Es??1/0))[0]??1/0,Mt=[bt,kt].filter(Kt=>Kt!==null).sort((Kt,Es)=>(Kt??1/0)-(Es??1/0))[0]??1/0;return Gt-Mt}case"last-touched":{const He=Fe.relationshipScore.lastTouchDate,bt=We.relationshipScore.lastTouchDate;return!He&&!bt?0:He?bt?new Date(He).getTime()-new Date(bt).getTime():1:-1}case"next-touch":{const He=Fe.relationshipScore.daysSinceTouch,bt=We.relationshipScore.daysSinceTouch;return He===null&&bt===null?0:He===null?-1:bt===null?1:bt-He}case"score":return Fe.relationshipScore.score-We.relationshipScore.score;case"date-added":{const He=Fe.created_at,bt=We.created_at;return!He&&!bt?0:He?bt?new Date(bt).getTime()-new Date(He).getTime():-1:1}case"name":default:{const He=`${Fe.first_name||""} ${Fe.last_name||""}`.toLowerCase(),bt=`${We.first_name||""} ${We.last_name||""}`.toLowerCase();return He.localeCompare(bt)}}}),Je},[d,$,Y,S,A,de,ae,j,N,m,g]),kr=$r.length,Sr=Math.max(1,Math.ceil(kr/nt)),hn=Math.min(Qe,Sr),zn=k.useMemo(()=>{const Je=(hn-1)*nt;return $r.slice(Je,Je+nt)},[$r,hn,nt]),Xs=k.useRef(!1);k.useEffect(()=>{if(!Xs.current){Xs.current=!0;return}Ce(1)},[$,Y,S,A,de,ae]);const Ur=k.useCallback(()=>{rt(!1),ct(Je=>Je.size>0?new Set:new Set(zn.map(Fe=>Fe.id)))},[zn]),xn=k.useCallback(()=>{rt(!0),ct(new Set($r.map(Je=>Je.id)))},[$r]),us=k.useCallback((Je,Fe)=>{X(Je.search||""),ne(Je.type||"all"),ce(Je.status||"all"),ie(Fe||"name")},[]),pr=()=>{Lr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Hr=async Je=>{Je.preventDefault();const Fe={...Tr,lead_source_id:Tr.lead_source_id||null};ge?(await B.mutateAsync({id:ge.id,...Fe}),be(null)):(await D.mutateAsync(Fe),oe(!1)),pr()},aa=async Je=>{confirm("Are you sure you want to delete this contact?")&&await z.mutateAsync(Je)};return e.jsx(_s,{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"})]}),et&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>it("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${lt==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(et.team.contact_visibility==="full_team"||et.team.contact_visibility==="leader_only"&&et.role==="team_leader")&&e.jsxs("button",{onClick:()=>it("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${lt==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Team"]}),et.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>it("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${lt==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(t0,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Vo,{className:"h-4 w-4 mr-1"}),"Back"]})}),lt==="team"?e.jsx($Te,{}):lt==="lead-pond"&&et?e.jsx(UTe,{teamId:et.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(hTs,{contacts:d,contactDealsMap:j,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"}[de]??null,onSelect:Je=>{const We=Je?{"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"}[Je]:"all";ce(We),Ce(1)}}),e.jsx(Ne,{children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, or phone...",value:$,onChange:Je=>X(Je.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-0",children:[e.jsxs(G,{onClick:()=>Q(!0),className:"sm:hidden w-full h-11 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0 shadow-sm",children:[e.jsx(xc,{className:"h-4 w-4 mr-2"}),"View Geographic Heat Map"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:hidden",children:[e.jsxs(G,{onClick:()=>oe(!0),className:"h-10 w-full justify-center",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Add Contact"})]}),e.jsxs(G,{variant:"outline",onClick:()=>Me(!0),className:"h-10 w-full justify-center",children:[e.jsx(oa,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Import CSV"})]}),e.jsxs(G,{variant:"outline",onClick:()=>Ee(!0),className:"h-10 w-full justify-center",children:[e.jsx(zg,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"From Phone"})]}),e.jsx("div",{className:"w-full [&>*]:w-full [&_button]:w-full [&_button]:h-10 [&_button]:justify-center",children:e.jsx(pqe,{})})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 flex-wrap",children:[e.jsxs(G,{onClick:()=>oe(!0),className:"shrink-0",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add Contact"]}),e.jsxs(G,{variant:"outline",onClick:()=>Me(!0),className:"shrink-0",children:[e.jsx(oa,{className:"h-4 w-4 mr-1"}),"Import CSV"]}),e.jsxs(G,{variant:"outline",onClick:()=>Ee(!0),className:"shrink-0",children:[e.jsx(zg,{className:"h-4 w-4 mr-1"}),"Import from Phone"]}),e.jsx(pqe,{}),e.jsxs(G,{variant:"outline",onClick:()=>Q(!0),className:"shrink-0 border-orange-200 text-orange-700 hover:bg-orange-50 hover:text-orange-800 dark:border-orange-900 dark:text-orange-400",children:[e.jsx(xc,{className:"h-4 w-4 mr-1"}),"Heat Map"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(zs,{value:Y,onValueChange:ne,children:[e.jsx(Os,{className:"w-[145px] h-9 text-sm",children:e.jsx(Us,{placeholder:"Filter by type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),v==null?void 0:v.filter(Je=>Je.active).map(Je=>e.jsx(mt,{value:Je.id,children:Je.name},Je.id))]})]}),b&&b.length>0&&e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"h-9 justify-start text-sm",children:[e.jsx(Ah,{className:"h-3.5 w-3.5 mr-1.5 shrink-0 text-muted-foreground"}),S.size===0?"Filter by Tags":`${S.size} tag${S.size>1?"s":""}`]})}),e.jsx(wo,{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:()=>P("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:()=>P("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(Je=>{const Fe=S.has(Je.id);return e.jsxs("button",{onClick:()=>{T(We=>{const He=new Set(We);return He.has(Je.id)?He.delete(Je.id):He.add(Je.id),He})},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(Ei,{checked:Fe,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Je.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Je.name})]},Je.id)})}),S.size>0&&e.jsx(G,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>T(new Set),children:"Clear tags"})]})})]}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",title:"Settings",children:e.jsx(lo,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(Vd,{align:"end",children:[e.jsxs(Da,{onClick:()=>Ft(!0),children:[e.jsx(Ah,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Da,{onClick:()=>Ie(!0),children:[e.jsx(t0,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]}),e.jsxs(zs,{value:de,onValueChange:ce,children:[e.jsx(Os,{className:"w-[145px] h-9 text-sm",children:e.jsx(Us,{placeholder:"Filter by status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Status"}),e.jsx(mt,{value:"warm",children:"🟢 Warm"}),e.jsx(mt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(mt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(mt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(mt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(mt,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(mt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(mt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(mt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(zs,{value:ae,onValueChange:ie,children:[e.jsx(Os,{className:"w-[165px] h-9 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rd,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Us,{placeholder:"Sort by"})]})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"name",children:"Name (A-Z)"}),e.jsx(mt,{value:"important-dates",children:"Important Dates"}),e.jsx(mt,{value:"last-touched",children:"Last Touched"}),e.jsx(mt,{value:"next-touch",children:"Next Touch Due"}),e.jsx(mt,{value:"score",children:"Relationship Score"}),e.jsx(mt,{value:"date-added",children:"Date Added"})]})]}),e.jsx(uTs,{currentFilters:{search:$,type:Y,status:de},currentSortBy:ae,onApplySmartList:us})]})]})})}),e.jsx(dTs,{selectedIds:ye,contacts:$r,onClearSelection:()=>{ct(new Set),rt(!1)},showLeadPondAction:Jt,onSendToLeadPond:ar,showTransferAction:cs,onTransfer:Is}),ye.size>0&&ye.size===zn.length&&!ve&&kr>nt&&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 ",zn.length," contacts on this page are selected."]}),e.jsxs(G,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:xn,children:["Select all ",kr.toLocaleString()," matching contacts"]})]}),ve&&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 ",kr.toLocaleString()," matching contacts are selected.",e.jsx(G,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{ct(new Set),rt(!1)},children:"Clear selection"})]}),kr>nt&&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 ",(hn-1)*nt+1,"–",Math.min(hn*nt,kr)," of ",kr.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ce(1),children:"First"}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ce(Je=>Je-1),children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",hn," of ",Sr]}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn>=Sr,onClick:()=>Ce(Je=>Je+1),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn>=Sr,onClick:()=>Ce(Sr),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:h?e.jsx(Ne,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):$r.length===0?e.jsx(Ne,{className:"p-6 text-center text-muted-foreground",children:$||Y!=="all"||de!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):zn.map(Je=>{var We,He,bt;const{relationshipScore:Fe}=Je;return e.jsx(Ne,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const ut=new URLSearchParams;$&&ut.set("search",$),Y!=="all"&&ut.set("type",Y),de!=="all"&&ut.set("filter",de);const kt=ut.toString();s(`/mission-control/contacts/${Je.id}${kt?`?${kt}`:""}`)},children:e.jsx(De,{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:[Je.first_name," ",Je.last_name]}),e.jsx(wqe,{count:(g==null?void 0:g[Je.id])??0}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Je.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Qs,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Je.email})]}),Je.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Je.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(_8,{score:Fe,size:"sm"}),e.jsx(vSe,{contact:Je}),(((We=Je.lead_source_ref)==null?void 0:We.name)||Je.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((He=Je.lead_source_ref)==null?void 0:He.name)||Je.lead_source}),(bt=Je.tags)==null?void 0:bt.map(ut=>{var kt;return e.jsx(Ge,{variant:"secondary",className:"text-xs",children:(kt=ut.relationship_type)==null?void 0:kt.name},ut.id)}),e.jsx(jqe,{contactId:Je.id,tags:N==null?void 0:N.filter(ut=>ut.contact_id===Je.id)}),e.jsx(_qe,{deal:j==null?void 0:j[Je.id]})]}),e.jsx(bqe,{birthday:Je.birthday,homeAnniversary:Je.home_anniversary,className:"mb-2",contactId:Je.id,contactName:`${Je.first_name}${Je.last_name?" "+Je.last_name:""}`,contactAddress:[Je.address,Je.city,Je.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Fe.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Ss(new Date(Fe.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Je.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(Ul(Je.birthday),"MMM d")]}),Je.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),Ss(Ul(Je.home_anniversary),"MMM d")]}),Je.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ws,{className:"h-3 w-3"}),"Added ",Ss(new Date(Je.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ut=>ut.stopPropagation(),children:e.jsx(xqe,{contact:Je,onEdit:be,onDelete:aa,onSnooze:(ut,kt)=>{Se(ut),Te(kt)},showLeadPondAction:Jt,onSendToLeadPond:fs,showTransferAction:cs,onTransfer:ss})})]})})},Je.id)})}):e.jsx(Ne,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(On,{className:"min-w-[800px]",children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(Ei,{checked:zn.length>0&&zn.every(Je=>ye.has(Je.id)),onCheckedChange:()=>Ur()})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Score"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Types / Pipeline"}),e.jsx(Tt,{children:"Last Contact"}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ie(ae==="date-added"?"name":"date-added"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Date Added",ae==="date-added"&&e.jsx(Rd,{className:"h-3 w-3"})]})}),e.jsx(Tt,{children:"Important Dates"}),e.jsx(Tt,{className:"w-[50px]",children:"Actions"})]})}),e.jsx(Bn,{children:h?e.jsx(qs,{children:e.jsx(ft,{colSpan:10,className:"text-center py-8",children:"Loading contacts..."})}):$r.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:$||Y!=="all"||de!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):zn.map(Je=>{var He,bt,ut;const{relationshipScore:Fe}=Je,We=j==null?void 0:j[Je.id];return e.jsxs(qs,{className:`cursor-pointer hover:bg-accent/50 ${ye.has(Je.id)?"bg-accent/30":""}`,onClick:()=>{const kt=new URLSearchParams;$&&kt.set("search",$),Y!=="all"&&kt.set("type",Y),de!=="all"&&kt.set("status",de);const Gt=kt.toString();s(`/mission-control/contacts/${Je.id}${Gt?`?${Gt}`:""}`)},children:[e.jsx(ft,{onClick:kt=>kt.stopPropagation(),children:e.jsx(Ei,{checked:ye.has(Je.id),onCheckedChange:()=>Er(Je.id)})}),e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[Je.first_name," ",Je.last_name]}),e.jsx(wqe,{count:(g==null?void 0:g[Je.id])??0})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(_8,{score:Fe,size:"sm"}),e.jsx(vSe,{contact:Je})]})}),e.jsx(ft,{children:e.jsx(_8,{score:Fe,size:"sm",showScore:!0})}),e.jsx(ft,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[Je.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Qs,{className:"h-3 w-3"}),Je.email]}),Je.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),Je.phone]})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(((He=Je.lead_source_ref)==null?void 0:He.name)||Je.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((bt=Je.lead_source_ref)==null?void 0:bt.name)||Je.lead_source}),(ut=Je.tags)==null?void 0:ut.map(kt=>{var Gt;return e.jsx(Ge,{variant:"secondary",className:"text-xs",children:(Gt=kt.relationship_type)==null?void 0:Gt.name},kt.id)}),e.jsx(jqe,{contactId:Je.id,tags:N==null?void 0:N.filter(kt=>kt.contact_id===Je.id)}),e.jsx(_qe,{deal:We})]})}),e.jsx(ft,{children:e.jsx("div",{className:"text-sm",children:Fe.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(cn,{className:"h-3 w-3"}),Ss(new Date(Fe.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),e.jsx(ft,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Je.created_at?Ss(new Date(Je.created_at),"MMM d, yyyy"):"—"})}),e.jsx(ft,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(bqe,{birthday:Je.birthday,homeAnniversary:Je.home_anniversary,contactId:Je.id,contactName:`${Je.first_name}${Je.last_name?" "+Je.last_name:""}`,contactAddress:[Je.address,Je.city,Je.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Je.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(Ul(Je.birthday),"MMM d")]}),Je.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),Ss(Ul(Je.home_anniversary),"MMM d")]})]})]})}),e.jsx(ft,{children:e.jsx(xqe,{contact:Je,onEdit:be,onDelete:aa,onSnooze:(kt,Gt)=>{Se(kt),Te(Gt)},showLeadPondAction:Jt,onSendToLeadPond:fs,showTransferAction:cs,onTransfer:ss})})]},Je.id)})})]})})}),kr>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 ",(hn-1)*nt+1,"–",Math.min(hn*nt,kr)," of ",kr.toLocaleString()," contacts"]}),e.jsxs(zs,{value:String(nt),onValueChange:Je=>{$t(Number(Je)),Ce(1)},children:[e.jsx(Os,{className:"w-[80px] h-8",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"50",children:"50"}),e.jsx(mt,{value:"100",children:"100"}),e.jsx(mt,{value:"250",children:"250"})]})]}),e.jsx("span",{className:"text-xs",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ce(1),children:"First"}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn<=1,onClick:()=>Ce(Je=>Je-1),children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",hn," of ",Sr]}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn>=Sr,onClick:()=>Ce(Je=>Je+1),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",disabled:hn>=Sr,onClick:()=>Ce(Sr),children:"Last"})]})]}),e.jsx(vs,{open:me||!!ge,onOpenChange:Je=>{Je||(oe(!1),be(null),pr())},children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:ge?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Hr,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"first_name",children:"First Name *"}),e.jsx(ke,{id:"first_name",value:Tr.first_name,onChange:Je=>Lr({...Tr,first_name:Je.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ke,{id:"last_name",value:Tr.last_name,onChange:Je=>Lr({...Tr,last_name:Je.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{id:"email",type:"email",value:Tr.email,onChange:Je=>Lr({...Tr,email:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(ke,{id:"phone",value:Tr.phone,onChange:Je=>Lr({...Tr,phone:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"address",children:"Address"}),e.jsx(ke,{id:"address",value:Tr.address,onChange:Je=>Lr({...Tr,address:Je.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(ke,{id:"city",value:Tr.city,onChange:Je=>Lr({...Tr,city:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(ke,{id:"state",value:Tr.state,onChange:Je=>Lr({...Tr,state:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"zip_code",children:"Zip"}),e.jsx(ke,{id:"zip_code",value:Tr.zip_code,onChange:Je=>Lr({...Tr,zip_code:Je.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ke,{id:"birthday",type:"date",value:Tr.birthday,onChange:Je=>Lr({...Tr,birthday:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ke,{id:"home_anniversary",type:"date",value:Tr.home_anniversary,onChange:Je=>Lr({...Tr,home_anniversary:Je.target.value})})]})]}),ge&&e.jsx(bSe,{contactId:ge.id,currentSpouseContactId:(ge==null?void 0:ge.spouse_contact_id)||null,currentSpouseName:(ge==null?void 0:ge.spouse_name)||null,currentSpouseEmail:(ge==null?void 0:ge.spouse_email)||null,onLink:Je=>F.mutate({contactId:ge.id,spouseContactId:Je}),onUnlink:()=>F.mutate({contactId:ge.id,spouseContactId:null}),isEditing:!0}),e.jsx(qmt,{value:Tr.lead_source_id,onChange:Je=>Lr({...Tr,lead_source_id:Je})}),e.jsxs("div",{children:[e.jsx(he,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(Je=>Je.active).map(Je=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ei,{checked:Tr.tagIds.includes(Je.id),onCheckedChange:Fe=>{Lr(Fe?{...Tr,tagIds:[...Tr.tagIds,Je.id]}:{...Tr,tagIds:Tr.tagIds.filter(We=>We!==Je.id)})}}),e.jsx("span",{className:"text-sm",children:Je.name})]},Je.id))})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(ur,{id:"notes",value:Tr.notes,onChange:Je=>Lr({...Tr,notes:Je.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>{oe(!1),be(null),pr()},children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:D.isPending||B.isPending,children:[ge?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(M5s,{open:Oe,onOpenChange:Me,relationshipTypes:(v==null?void 0:v.filter(Je=>Je.active))||[],onSuccess:()=>{Me(!1)}}),e.jsx(L5s,{open:Pe,onOpenChange:Ee,onComplete:()=>Ee(!1)}),e.jsx(Sge,{open:!!$e,onOpenChange:Je=>{Je||Se(null)},contactId:$e||"",contactName:ze}),e.jsx(bTs,{open:Nt,onOpenChange:Ft}),e.jsx(_Ts,{open:at,onOpenChange:Ie}),e.jsx(xTs,{open:K,onOpenChange:Q,contacts:d||[],onCitySelect:Je=>{X(Je),Ce(1)}}),e.jsx(Zlt,{open:Qt,onOpenChange:yt,contactIds:Ht,contactNames:Ht.map(Je=>{const Fe=$r.find(We=>We.id===Je);return Fe?`${Fe.first_name} ${Fe.last_name||""}`.trim():""}),onComplete:()=>{dt([]),ct(new Set),rt(!1)}})]})]})})}const jTs="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function NTs({open:s,onOpenChange:t,contact:r}){var K;const{user:n}=As(),a=vr(),i=es(),{intakePage:l,isLoading:o}=Cge(),{isGmailConnected:c,gmailEmail:d}=Oh(),h=txe(),{data:m}=gt({queryKey:["profile-for-invite",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&s,queryFn:async()=>{const{data:Q}=await H.from("profiles").select("name, email, avatar_url").eq("id",n.id).maybeSingle();return Q}}),x=(m==null?void 0:m.name)||((K=n==null?void 0:n.email)==null?void 0:K.split("@")[0])||"Your Agent",g=x.split(" ")[0],v=l?`https://contacts.relevelup.com/${l.slug}`:"",j=k.useMemo(()=>`Hi ${r.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[r.first_name]),[b,N]=k.useState("gmail"),[S,T]=k.useState(""),[A,P]=k.useState(""),[D,B]=k.useState(!1);k.useEffect(()=>{s&&(T(`Quick favor, ${r.first_name} — can you update your info?`),P(j),N(c?"gmail":"system"))},[s,j,r.first_name,c]);const z=k.useMemo(()=>A.split(/\n\n+/).map(Q=>`

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

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

A note from ${x}

${z}

Update Your Info

Takes about a minute — promise

Share My Info →

${v}

Sent with care by ${x}

Powered by ReLevelUp

`,$=async()=>{if(!l){ue.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!S.trim()||!A.trim()){ue.error("Subject and message are required");return}B(!0);const Q=F();try{if(b==="gmail"&&c){const{data:Y,error:ne}=await H.functions.invoke("gmail-send",{body:{to:r.email,subject:S,body:Q,contactId:r.id}});if(ne)throw ne;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Failed to send")}else{const{data:Y,error:ne}=await H.functions.invoke("send-connect-invite",{body:{contactEmail:r.email,subject:S,htmlBody:Q,replyToEmail:(m==null?void 0:m.email)||(n==null?void 0:n.email),agentName:x}});if(ne)throw ne;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Failed to send")}try{await h.mutateAsync({contactId:r.id,actionTypeId:jTs,notes:`Sent Connect Page invite — Subject: "${S}"`})}catch(Y){console.warn("Failed to log activity:",Y)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ue.success("Connect Page invite sent!"),t(!1)}catch(Y){console.error("Send error:",Y),ue.error(Y instanceof Error?Y.message:"Failed to send invite")}finally{B(!1)}},X=F();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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[r.first_name," ",r.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(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(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(Rn,{value:b,onValueChange:Q=>N(Q),className:"mt-1.5",children:e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"gmail",disabled:!c,children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Xt,{value:"system",children:[e.jsx(jr,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:b==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(m==null?void 0:m.email)||(n==null?void 0:n.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(ke,{id:"invite-subject",value:S,onChange:Q=>T(Q.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(ur,{id:"invite-message",value:A,onChange:Q=>P(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(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Yr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:X,title:"Email preview",sandbox:"",className:"w-full h-[420px] bg-background"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsx(G,{onClick:$,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(Zr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Hi,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs(G,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(rl,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function kTs(s){return gt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 STs(s){return gt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function dAe(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 rL(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 Vmt(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 Hmt(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 Gmt(){const s=es();return Lt({mutationFn:async({id:t,dealId:r})=>{await H.from("portal_updates").delete().eq("portal_id",t);const{error:n}=await H.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 CTs(s){return gt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Wmt(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 TTs(){const s=na();return gt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 ETs(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 ATs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 MTs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function s1(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function ITs({contactId:s}){const t=vr(),r=es(),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(null),j=rL(),b=Wmt(),{data:N,isLoading:S}=gt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:z,error:F}=await H.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(F)throw F;if(!z||z.length===0)return[];const $=z.map(Q=>Q.id),{data:X,error:K}=await H.from("client_portals").select("*").in("deal_id",$).is("archived_at",null);if(K)throw K;return(X||[]).map(Q=>({...Q,deal:z.find(Y=>Y.id===Q.deal_id)}))},enabled:!!s}),T=(N==null?void 0:N.map(z=>z.id))||[],{data:A}=gt({queryKey:["contact-portal-updates",T],queryFn:async()=>{if(T.length===0)return{};const{data:z,error:F}=await H.from("portal_updates").select("*").in("portal_id",T).order("created_at",{ascending:!1});if(F)throw F;const $={};return(z||[]).forEach(X=>{$[X.portal_id]||($[X.portal_id]=X)}),$},enabled:T.length>0}),P=z=>{navigator.clipboard.writeText(s1(z)),a(z),ue.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},D=async z=>{d.trim()&&(await b.mutateAsync({portal_id:z,title:d,content:m||void 0}),c(!1),h(""),x(""),r.invalidateQueries({queryKey:["contact-portal-updates"]}),ue.success("Portal update posted!"))},B=async()=>{g&&(await j.mutateAsync({id:g.id,welcome_message:g.welcome_message,next_step_text:g.next_step_text,is_enabled:g.is_enabled,show_post_close_tips:g.show_post_close_tips,review_url:g.review_url}),l(!1),v(null),r.invalidateQueries({queryKey:["contact-portals",s]}),ue.success("Portal settings updated!"))};return S||!N||N.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(De,{className:"space-y-3",children:N.map(z=>{var K,Q,Y;const F=((K=z.stage_mapping)==null?void 0:K.length)>0?z.stage_mapping:Bpe(((Q=z.deal)==null?void 0:Q.deal_type)||"buyer"),$=F==null?void 0:F[z.current_stage_index??0],X=A==null?void 0:A[z.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:((Y=z.deal)==null?void 0:Y.deal_name)||"Portal"}),$&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",$.label||$.name]})]}),e.jsx(Ge,{variant:z.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:z.is_enabled?"Active":"Disabled"})]}),X&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:X.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(X.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>P(z.slug),children:[n===z.slug?e.jsx(Hn,{className:"h-3 w-3 mr-1"}):e.jsx(Ra,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(s1(z.slug),"_blank"),children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(bi,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:d,onChange:ne=>h(ne.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Details (optional)"}),e.jsx(ur,{value:m,onChange:ne=>x(ne.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(G,{onClick:()=>D(z.id),disabled:!d.trim()||b.isPending,className:"w-full",children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(vs,{open:i,onOpenChange:l,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{v({...z}),l(!0)},children:[e.jsx(lo,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Portal Settings"})}),g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Portal Enabled"}),e.jsx(br,{checked:g.is_enabled,onCheckedChange:ne=>v({...g,is_enabled:ne})})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Welcome Message"}),e.jsx(ur,{value:g.welcome_message||"",onChange:ne=>v({...g,welcome_message:ne.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Next Step"}),e.jsx(ke,{value:g.next_step_text||"",onChange:ne=>v({...g,next_step_text:ne.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review URL"}),e.jsx(ke,{value:g.review_url||"",onChange:ne=>v({...g,review_url:ne.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Show Post-Close Tips"}),e.jsx(br,{checked:g.show_post_close_tips,onCheckedChange:ne=>v({...g,show_post_close_tips:ne})})]}),e.jsx(po,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{onClick:B,disabled:j.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(G,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${z.deal_id}`),children:[e.jsx(Ga,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),N.length>1&&e.jsx(po,{})]},z.id)})})]})}function PTs({contactId:s}){const{data:t}=gt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await H.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}=gt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await H.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(Ne,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{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(jn,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Ge,{variant:"secondary",className:"text-xs ml-auto",children:[n.length," ",n.length===1?"property":"properties"]})]})}),e.jsx(De,{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(Cn,{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(cn,{className:"h-3 w-3"}),e.jsx("span",{title:Ss(new Date(l.viewed_at),"PPp"),children:al(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Yr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const LTs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function kqe({value:s,onChange:t,onAdd:r,suggestions:n,placeholder:a,icon:i}){const[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(null);k.useEffect(()=>{const m=x=>{d.current&&!d.current.contains(x.target)&&c.current&&!c.current.contains(x.target)&&o(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]);const h=n.filter(m=>m.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ke,{ref:c,value:s,onChange:m=>{t(m.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h.length>0?r(h[0]):r(s))}}),n.length>0&&e.jsx(so,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>r(s),children:e.jsx(Ws,{className:"h-4 w-4"})})]}),l&&h.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:h.map(m=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{r(m),o(!1)},children:[i||e.jsx(ja,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),m]},m))})]})}function DTs({contactId:s,contactName:t}){var F,$,X;const{user:r}=As(),n=na(),{hasLeadSite:a}=ey(),i=es(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(""),{data:x}=gt({queryKey:["agent-lead-site-config",n],queryFn:async()=>{const{data:K,error:Q}=await H.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(Q||!K)return{cities:[],zipCodes:[]};const Y=K.theme_config||{},ne=Array.isArray(Y.searchCities)?Y.searchCities:[];K.mls_market_area&&!ne.includes(K.mls_market_area)&&ne.unshift(K.mls_market_area);const de=Array.isArray(Y.searchZipCodes)?Y.searchZipCodes:[];return{cities:ne,zipCodes:de}},enabled:!!n}),{data:g,isLoading:v}=gt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:K,error:Q}=await H.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(Q)throw Q;return K},enabled:!!s&&!!r}),[j,b]=k.useState({}),N=()=>{b({is_active:(g==null?void 0:g.is_active)??!0,min_price:(g==null?void 0:g.min_price)??null,max_price:(g==null?void 0:g.max_price)??null,min_beds:(g==null?void 0:g.min_beds)??null,min_baths:(g==null?void 0:g.min_baths)??null,min_sqft:(g==null?void 0:g.min_sqft)??null,max_sqft:(g==null?void 0:g.max_sqft)??null,cities:(g==null?void 0:g.cities)??[],zip_codes:(g==null?void 0:g.zip_codes)??[],property_types:(g==null?void 0:g.property_types)??[],frequency:(g==null?void 0:g.frequency)??"daily"}),o(!0)},S=Lt({mutationFn:async()=>{const K={contact_id:s,owner_user_id:n,is_active:j.is_active??!0,min_price:j.min_price||null,max_price:j.max_price||null,min_beds:j.min_beds||null,min_baths:j.min_baths||null,min_sqft:j.min_sqft||null,max_sqft:j.max_sqft||null,cities:j.cities||[],zip_codes:j.zip_codes||[],property_types:j.property_types||[],frequency:j.frequency||"daily"};if(g!=null&&g.id){const{error:Q}=await H.from("contact_property_alerts").update(K).eq("id",g.id);if(Q)throw Q}else{const{error:Q}=await H.from("contact_property_alerts").insert(K);if(Q)throw Q}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ue.success("Property alert saved!")},onError:K=>{ue.error(K.message||"Failed to save alert")}}),T=Lt({mutationFn:async()=>{if(!(g!=null&&g.id))return;const{error:K}=await H.from("contact_property_alerts").delete().eq("id",g.id);if(K)throw K},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ue.success("Property alert removed")}}),A=K=>{var Y;const Q=K.trim();Q&&!((Y=j.cities)!=null&&Y.includes(Q))&&b(ne=>({...ne,cities:[...ne.cities||[],Q]})),d("")},P=K=>{var Y;const Q=K.trim();Q&&!((Y=j.zip_codes)!=null&&Y.includes(Q))&&b(ne=>({...ne,zip_codes:[...ne.zip_codes||[],Q]})),m("")},D=K=>{b(Q=>{const Y=Q.property_types||[];return{...Q,property_types:Y.includes(K)?Y.filter(ne=>ne!==K):[...Y,K]}})};if(!a||v)return null;if(g&&!l)return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${g.is_active?"bg-green-500/10":"bg-muted"}`,children:g.is_active?e.jsx(Rm,{className:"h-4 w-4 text-green-600"}):e.jsx(Fv,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(Ge,{variant:g.is_active?"default":"secondary",className:"text-xs ml-auto",children:[g.is_active?"Active":"Paused"," · ",g.frequency]})]})}),e.jsxs(De,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[g.min_price||g.max_price?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(_l,{className:"h-3 w-3"}),g.min_price?`$${(g.min_price/1e3).toFixed(0)}k`:"$0"," - ",g.max_price?`$${(g.max_price/1e3).toFixed(0)}k`:"Any"]}):null,g.min_beds?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(b3,{className:"h-3 w-3"}),g.min_beds,"+ beds"]}):null,g.min_baths?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(fp,{className:"h-3 w-3"}),g.min_baths,"+ baths"]}):null,(F=g.cities)==null?void 0:F.map(K=>e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),K]},K)),($=g.zip_codes)==null?void 0:$.map(K=>e.jsx(Ge,{variant:"outline",children:K},K)),(X=g.property_types)==null?void 0:X.map(K=>e.jsx(Ge,{variant:"outline",children:K},K))]}),g.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(g.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:N,className:"flex-1",children:"Manage Alert"}),e.jsxs(G,{variant:"destructive",size:"sm",onClick:()=>T.mutate(),disabled:T.isPending,className:"flex-1",children:[T.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(_r,{className:"h-4 w-4 mr-1"}),"Remove Alert"]})]})]})]});const B=((x==null?void 0:x.cities)||[]).filter(K=>{var Q;return!((Q=j.cities)!=null&&Q.includes(K))}),z=((x==null?void 0:x.zipCodes)||[]).filter(K=>{var Q;return!((Q=j.zip_codes)!=null&&Q.includes(K))});return l?e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Rm,{className:"h-4 w-4 text-primary"}),g?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Alert Active"}),e.jsx(br,{checked:j.is_active??!0,onCheckedChange:K=>b(Q=>({...Q,is_active:K}))})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(_l,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ke,{type:"number",placeholder:"Min price",value:j.min_price??"",onChange:K=>b(Q=>({...Q,min_price:K.target.value?Number(K.target.value):null}))}),e.jsx(ke,{type:"number",placeholder:"Max price",value:j.max_price??"",onChange:K=>b(Q=>({...Q,max_price:K.target.value?Number(K.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(b3,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(zs,{value:j.min_beds?String(j.min_beds):"any",onValueChange:K=>b(Q=>({...Q,min_beds:K==="any"?null:Number(K)})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Any"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"any",children:"Any"}),[1,2,3,4,5].map(K=>e.jsxs(mt,{value:String(K),children:[K,"+"]},K))]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(fp,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(zs,{value:j.min_baths?String(j.min_baths):"any",onValueChange:K=>b(Q=>({...Q,min_baths:K==="any"?null:Number(K)})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Any"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(K=>e.jsxs(mt,{value:String(K),children:[K,"+"]},K))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(U3,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ke,{type:"number",placeholder:"Min sqft",value:j.min_sqft??"",onChange:K=>b(Q=>({...Q,min_sqft:K.target.value?Number(K.target.value):null}))}),e.jsx(ke,{type:"number",placeholder:"Max sqft",value:j.max_sqft??"",onChange:K=>b(Q=>({...Q,max_sqft:K.target.value?Number(K.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ja,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(kqe,{value:c,onChange:d,onAdd:A,suggestions:B,placeholder:"Type to search cities..."}),j.cities&&j.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:j.cities.map(K=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[K,e.jsx("button",{onClick:()=>b(Q=>{var Y;return{...Q,cities:(Y=Q.cities)==null?void 0:Y.filter(ne=>ne!==K)}}),children:e.jsx(_r,{className:"h-3 w-3"})})]},K))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(kqe,{value:h,onChange:m,onAdd:P,suggestions:z,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),j.zip_codes&&j.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:j.zip_codes.map(K=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[K,e.jsx("button",{onClick:()=>b(Q=>{var Y;return{...Q,zip_codes:(Y=Q.zip_codes)==null?void 0:Y.filter(ne=>ne!==K)}}),children:e.jsx(_r,{className:"h-3 w-3"})})]},K))})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:LTs.map(K=>{var Q;return e.jsx(Ge,{variant:(Q=j.property_types)!=null&&Q.includes(K)?"default":"outline",className:"cursor-pointer",onClick:()=>D(K),children:K},K)})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"mb-1.5",children:"Frequency"}),e.jsxs(zs,{value:j.frequency||"daily",onValueChange:K=>b(Q=>({...Q,frequency:K})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"daily",children:"Daily"}),e.jsx(mt,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{onClick:()=>S.mutate(),disabled:S.isPending,className:"flex-1",children:[S.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),g&&e.jsx(G,{variant:"destructive",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,children:e.jsx(_r,{className:"h-4 w-4"})})]})]})]}):e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:N,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Rm,{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 RTs({contactId:s,contactName:t}){var de;const{user:r}=As(),n=na(),{hasLeadSite:a}=ey(),i=es(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState([]),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(""),A=k.useRef(null),P=k.useRef(null),{data:D}=gt({queryKey:["agent-lead-site-cities",n],queryFn:async()=>{const{data:ce,error:ae}=await H.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(ae||!ce)return[];const ie=ce.theme_config||{},me=Array.isArray(ie.searchCities)?ie.searchCities:[];return ce.mls_market_area&&!me.includes(ce.mls_market_area)&&me.unshift(ce.mls_market_area),me},enabled:!!n}),{data:B,isLoading:z}=gt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ce,error:ae}=await H.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ae)throw ae;return ce},enabled:!!s&&!!r});k.useEffect(()=>{const ce=ae=>{P.current&&!P.current.contains(ae.target)&&A.current&&!A.current.contains(ae.target)&&j(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[]);const F=()=>{g((B==null?void 0:B.market_report_enabled)??!1),m((B==null?void 0:B.market_report_cities)??[]),o(!0)},$=ce=>{const ae=(ce||c).trim();ae&&!h.includes(ae)&&m([...h,ae]),d(""),j(!1)},X=(D||[]).filter(ce=>!h.includes(ce)&&ce.toLowerCase().includes(c.toLowerCase())),K=Lt({mutationFn:async()=>{const{data:ce,error:ae}=await H.functions.invoke("send-market-report",{body:{action:"preview",agentId:n,cities:(B==null?void 0:B.market_report_cities)??[]}});if(ae)throw new Error(ae.message||"Failed to generate preview");if(ce&&!ce.ok&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{T(ce.html),N(!0)},onError:ce=>{ue.error(ce.message||"Failed to generate preview")}}),Q=Lt({mutationFn:async()=>{const{data:ce,error:ae}=await H.functions.invoke("send-market-report",{body:{action:"send",agentId:n,cities:(B==null?void 0:B.market_report_cities)??[],contactIds:[s]}});if(ae)throw new Error(ae.message||"Failed to send report");if(ce&&!ce.ok&&ce.error)throw new Error(ce.error);return ce},onSuccess:()=>{ue.success(`Market report sent to ${t}!`)},onError:ce=>{ue.error(ce.message||"Failed to send report")}}),Y=Lt({mutationFn:async()=>{const{error:ce}=await H.from("innercircle_contacts").update({market_report_enabled:x,market_report_cities:h}).eq("id",s);if(ce)throw ce},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ue.success(x?"Monthly market report enabled!":"Market report disabled")},onError:ce=>{ue.error(ce.message||"Failed to save")}}),ne=Lt({mutationFn:async()=>{const{error:ce}=await H.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ce)throw ce},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),g(!1),m([]),ue.success("Market report removed")},onError:ce=>{ue.error(ce.message||"Failed to remove market report")}});return!a||z?null:B!=null&&B.market_report_enabled&&!l?e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{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(ao,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Ge,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(De,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((de=B.market_report_cities)==null?void 0:de.length)>0?B.market_report_cities.map(ce=>e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),ce]},ce)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(jn,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(G,{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(Zr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:F,className:"flex-1",children:"Manage"}),e.jsxs(G,{variant:"destructive",size:"sm",onClick:()=>ne.mutate(),disabled:ne.isPending,className:"flex-1",children:[ne.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:N,children:e.jsxs(ys,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(ao,{className:"h-5 w-5 text-primary"}),"Market Report Preview"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsx("div",{className:"border rounded-lg overflow-hidden",dangerouslySetInnerHTML:{__html:S}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(G,{onClick:()=>{N(!1),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(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(G,{variant:"outline",onClick:()=>N(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(ao,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Send Monthly Report"}),e.jsx(br,{checked:x,onCheckedChange:g})]}),x&&e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ja,{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(ke,{ref:A,value:c,onChange:ce=>{d(ce.target.value),j(!0)},onFocus:()=>j(!0),placeholder:"Type to search cities...",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),X.length>0?$(X[0]):$())}}),e.jsx(so,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>$(),children:e.jsx(Ws,{className:"h-4 w-4"})})]}),v&&X.length>0&&e.jsx("div",{ref:P,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:X.map(ce=>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:()=>$(ce),children:[e.jsx(ja,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ce]},ce))})]}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(ce=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[ce,e.jsx("button",{onClick:()=>m(h.filter(ae=>ae!==ce)),children:e.jsx(_r,{className:"h-3 w-3"})})]},ce))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{onClick:()=>Y.mutate(),disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:F,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ao,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable Monthly Market Report"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-send ",t," a branded market report with real MLS data every month"]})]})]})})})}function OTs(s){return gt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:r}=await H.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 H.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 H.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",n).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(h=>{var m;return{...h,campaign:{name:((m=i.get(h.campaign_id))==null?void 0:m.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function FTs(s){switch(s){case"active":return e.jsx(Ge,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Ge,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Ge,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Ge,{variant:"outline",children:"Exited"});default:return e.jsx(Ge,{variant:"outline",children:s})}}function Sqe(s){return s==="sent"?e.jsx(Mn,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(od,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(cm,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(cn,{className:"h-4 w-4 text-muted-foreground"})}function BTs({contactId:s}){const t=vr(),{data:r,isLoading:n}=OTs(s),[a,i]=k.useState(null);if(n)return null;const l=(r==null?void 0:r.enrollments)||[],o=(r==null?void 0:r.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(G3,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(De,{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(G3,{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"}),FTs(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: ",al(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",al(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",al(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,h;return e.jsxs(vs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:m=>!m&&i(null),children:[e.jsx(Ni,{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:Sqe(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(bi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(Qs,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",Ss(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[Sqe(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((h=c.campaign)==null?void 0:h.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Ss(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(G,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function Kmt({contactId:s}={}){const{user:t}=As();return gt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const r=t.id;let n=H.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=H.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source").eq("user_id",r).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await H.from("email_campaigns").select("id, subject").eq("user_id",r),l=(i.data||[]).map(j=>j.id),o=new Map((i.data||[]).map(j=>[j.id,j.subject]));let c=[];if(l.length>0){let j=H.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&&(j=j.eq("contact_id",s)),c=(await j).data||[]}const[d,h]=await Promise.all([n,a]),m=(d.data||[]).map(j=>({id:`g-${j.id}`,channel:j.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:j.subject,to_email:j.to_email,contact_id:j.contact_id,sent_at:j.sent_at,source:j.source})),x=(h.data||[]).map(j=>({id:`b-${j.id}`,channel:"Mass Email",subject:j.subject,to_email:j.contact_email,contact_id:j.contact_id,sent_at:j.sent_at,source:j.source})),g=c.map(j=>({id:`c-${j.id}`,channel:"Campaign",subject:o.get(j.campaign_id)||"(campaign)",to_email:j.email,contact_id:j.contact_id,sent_at:j.sent_at,source:null,campaign_id:j.campaign_id,opened_at:j.opened_at,clicked_at:j.clicked_at})),v=[...m,...x,...g];return v.sort((j,b)=>j.sent_at0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(De,{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(Qs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ge,{variant:"outline",className:`text-xs ${zTs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(G,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!n),children:n?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Kn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function UTs({videoId:s}){var l;const{data:t,isLoading:r,error:n}=rTs(s);if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{className:"w-full aspect-video rounded-lg"}),e.jsx(Vs,{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(od,{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 qTs({contactId:s}){const t=vr(),[r,n]=k.useState(!1),{data:a,isLoading:i}=gt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:x}=await H.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(x)throw x;return m},enabled:!!s}),l=async(m,x)=>{const g=x==="done"?"todo":"done";await H.from("deal_tasks").update({status:g,completed_at:g==="done"?new Date().toISOString():null}).eq("id",m),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=gt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:x}=await H.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(x)throw x;return m},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(m=>m.status!=="done"))||[],h=(a==null?void 0:a.filter(m=>m.status==="done"))||[];return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Hn,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>n(!0),children:e.jsx(Ws,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(De,{className:"space-y-1",children:i?e.jsx(Vs,{className:"h-8 w-full"}):d.length===0&&h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(m=>e.jsxs("button",{onClick:async()=>{await l(m.id,m.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[m.priority]," ",m.title]}),m.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(m.due_date),"MMM d")})]},m.id)),h.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[h.length," completed"]})})]})}),r&&e.jsx(VTs,{contactId:s,open:r,onOpenChange:m=>{n(m),m||o()}})]})}function VTs({contactId:s,open:t,onOpenChange:r}){const[n,a]=k.useState(""),[i,l]=k.useState("medium"),[o,c]=k.useState(),{data:d}=gt({queryKey:["session"],queryFn:async()=>{const{data:m}=await H.auth.getSession();return m.session}}),h=async()=>{var x;if(!n.trim()||!((x=d==null?void 0:d.user)!=null&&x.id))return;const{error:m}=await H.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:n.trim(),priority:i,status:"todo",due_date:o?Ss(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(js,{children:e.jsx(bs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:n,onChange:m=>a(m.target.value),placeholder:"Task title...",onKeyDown:m=>m.key==="Enter"&&h()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Priority"}),e.jsxs("select",{value:i,onChange:m=>l(m.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Due Date"}),e.jsx(ke,{type:"date",value:o?Ss(o,"yyyy-MM-dd"):"",onChange:m=>c(m.target.value?new Date(m.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{onClick:h,disabled:!n.trim(),children:"Create Task"})]})]})]})})}function HTs({contactId:s}){const t=vr(),{data:r,isLoading:n}=gt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await H.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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Yu,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(De,{className:"space-y-2",children:r.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function GTs(){var lt,it,Nt,Ft,at;const{contactId:s}=Xi(),t=vr(),[r]=Lc(),n=r.get("search")||"",a=r.get("type")||"all",i=r.get("status")||"all",{data:l,isLoading:o}=y$t(s||""),{data:c}=qx(),{data:d}=tz(),{data:h}=sz(3650),{data:m}=Tge(365),{data:x}=kTs(s),{contactsWithScores:g}=nxe(),v=T5e(),j=E5e(),b=txe(),N=Vnt(),[S,T]=k.useState(!1),[A,P]=k.useState({}),[D,B]=k.useState(!1),[z,F]=k.useState(null),[$,X]=k.useState(""),[K,Q]=k.useState(void 0),[Y,ne]=k.useState(""),[de,ce]=k.useState(null),[ae,ie]=k.useState(!1),[me,oe]=k.useState(null),[ge,be]=k.useState(!1),{isGmailConnected:Oe,gmailEmail:Me}=Oh(),{data:Pe}=gt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Ie,error:et}=await H.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(et)throw et;return Ie},enabled:!!s}),Ee=Ie=>{if(!Ie)return null;const et=Ie.match(/Video ID:\s*([a-f0-9-]+)/i);return et?et[1]:null},$e=k.useMemo(()=>{if(!g)return[];let Ie=g.filter(et=>{var cs,Ht,dt;const Dt=n===""||`${et.first_name} ${et.last_name}`.toLowerCase().includes(n.toLowerCase())||((cs=et.email)==null?void 0:cs.toLowerCase().includes(n.toLowerCase()))||((Ht=et.phone)==null?void 0:Ht.includes(n)),Jt=a==="all"||((dt=et.tags)==null?void 0:dt.some(Qt=>Qt.relationship_type_id===a));return Dt&&Jt});return i==="not-touched-90"?Ie=Ie.filter(et=>{const Dt=et.relationshipScore.daysSinceTouch;return Dt===null||Dt>90}):i==="at-risk"?Ie=Ie.filter(et=>et.relationshipScore.status==="at-risk"):i==="cooling"?Ie=Ie.filter(et=>et.relationshipScore.status==="cooling"):i==="warm"&&(Ie=Ie.filter(et=>et.relationshipScore.status==="warm")),Ie.map(et=>et.id)},[g,n,a,i]),Se=$e.indexOf(s||""),ze=Se>0?$e[Se-1]:null,Te=Se<$e.length-1?$e[Se+1]:null,ye=$e.length>1&&Se!==-1,ct=Ie=>{const et=new URLSearchParams;n&&et.set("search",n),a!=="all"&&et.set("type",a),i!=="all"&&et.set("status",i);const Dt=et.toString();return`/mission-control/contacts/${Ie}${Dt?`?${Dt}`:""}`},ve=k.useMemo(()=>{const Ie=((h==null?void 0:h.filter(Dt=>Dt.contact_id===s))||[]).map(Dt=>{var dt,Qt,yt;const Jt=Ee(Dt.notes);let cs=((dt=Dt.action_type)==null?void 0:dt.name)||"Touch",Ht=Dt.notes;if(cs==="Other"&&((Qt=Dt.notes)!=null&&Qt.startsWith("["))){const ss=Dt.notes.indexOf("]");ss>0&&(cs=Dt.notes.substring(1,ss),Ht=Dt.notes.substring(ss+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Dt.id,type:"touch",completed_at:Dt.completed_at,name:cs,color:((yt=Dt.action_type)==null?void 0:yt.color)||"#3B82F6",notes:Ht,videoId:Jt}}),et=((m==null?void 0:m.filter(Dt=>Dt.contact_id===s))||[]).map(Dt=>({id:Dt.id,type:"popby",completed_at:Dt.completed_at,name:"Pop-by",color:"#F97316",notes:Dt.notes,videoId:null}));return[...Ie,...et].sort((Dt,Jt)=>new Date(Jt.completed_at).getTime()-new Date(Dt.completed_at).getTime())},[h,m,s]),rt=()=>{var Ie;l&&(P({first_name:l.first_name||"",last_name:l.last_name||"",email:l.email||"",phone:l.phone||"",address:l.address||"",city:l.city||"",state:l.state||"",zip_code:l.zip_code||"",birthday:l.birthday||"",home_anniversary:l.home_anniversary||"",spouse_name:l.spouse_name||"",spouse_email:l.spouse_email||"",company_name:l.company_name||"",job_title:l.job_title||"",lead_source_id:l.lead_source_id||"",notes:l.notes||"",tagIds:((Ie=l.tags)==null?void 0:Ie.map(et=>et.relationship_type_id))||[]}),T(!0))},Re=async()=>{await v.mutateAsync({id:s,...A,lead_source_id:A.lead_source_id||null}),T(!1)},Qe=async()=>{confirm("Are you sure you want to delete this contact?")&&(await j.mutateAsync(s),t("/mission-control/contacts"))},Ce=((lt=d==null?void 0:d.find(Ie=>Ie.id===z))==null?void 0:lt.name)==="Other",nt=async()=>{if(!z||Ce&&!Y.trim())return;const Ie=K?new Date(K.getFullYear(),K.getMonth(),K.getDate(),12,0,0).toISOString():void 0,et=Ce?`[${Y.trim()}]${$?" — "+$:""}`:$;await b.mutateAsync({contactId:s,actionTypeId:z,notes:et,completedAt:Ie}),B(!1),F(null),X(""),Q(void 0),ne("")},$t=(Ie,et)=>{Oe&&l?(oe({email:Ie,name:et||`${l.first_name} ${l.last_name||""}`.trim()}),ie(!0)):window.location.href=`mailto:${Ie}`};return o?e.jsx(_s,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):l?e.jsxs(e.Fragment,{children:[e.jsx(_s,{title:`${l.first_name} ${l.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(Vo,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),ye&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>ze&&t(ct(ze)),disabled:!ze,className:"px-2",children:[e.jsx(Vo,{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:[Se+1," of ",$e.length]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Te&&t(ct(Te)),disabled:!Te,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(ya,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[l.email&&e.jsxs(G,{variant:"outline",onClick:()=>$t(l.email,`${l.first_name} ${l.last_name||""}`.trim()),children:[e.jsx(Qs,{className:"h-4 w-4 mr-1"}),"Email"]}),l.email&&e.jsxs(G,{variant:"outline",onClick:()=>be(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(G,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(vs,{open:D,onOpenChange:B,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(ys,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:d==null?void 0:d.filter(Ie=>Ie.active).map(Ie=>e.jsxs("button",{onClick:()=>F(Ie.id),className:` p-3 rounded-lg border text-left transition-all ${z===Ie.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:Ie.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ie.description})]},Ie.id))}),Ce&&e.jsxs("div",{className:"mt-3",children:[e.jsx(he,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(ke,{id:"custom-action-name",value:Y,onChange:Ie=>ne(Ie.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Date (optional — backdate if needed)"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal mt-2",!K&&"text-muted-foreground"),children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),K?Ss(K,"PPP"):"Today (default)"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:K,onSelect:Q,disabled:Ie=>Ie>new Date,initialFocus:!0,className:Bt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(ur,{id:"action-notes",value:$,onChange:Ie=>X(Ie.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(G,{onClick:nt,disabled:!z||Ce&&!Y.trim()||b.isPending,className:"w-full",children:[e.jsx(Hn,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(G,{variant:"outline",onClick:rt,children:[e.jsx(nd,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(G,{variant:"destructive",size:"icon",onClick:Qe,children:e.jsx(yr,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"bg-card border rounded-lg p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold",children:[l.first_name," ",l.last_name||""]}),(((it=l.lead_source_ref)==null?void 0:it.name)||l.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((Nt=l.lead_source_ref)==null?void 0:Nt.name)||l.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[l.email&&e.jsxs("button",{onClick:()=>$t(l.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Qs,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:l.email})]}),l.phone&&e.jsxs("a",{href:`tel:${l.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:l.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(vSe,{contact:l}),(Ft=l.tags)==null?void 0:Ft.map(Ie=>{const et=c==null?void 0:c.find(Dt=>Dt.id===Ie.relationship_type_id);return et?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:et.name},Ie.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(vTs,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(Ne,{className:"md:col-span-2",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Contact Information"})}),e.jsx(De,{children:S?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"first_name",children:"First Name"}),e.jsx(ke,{id:"first_name",value:A.first_name,onChange:Ie=>P({...A,first_name:Ie.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ke,{id:"last_name",value:A.last_name,onChange:Ie=>P({...A,last_name:Ie.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(ke,{id:"email",type:"email",value:A.email,onChange:Ie=>P({...A,email:Ie.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(ke,{id:"phone",value:A.phone,onChange:Ie=>P({...A,phone:Ie.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"address",children:"Street Address"}),e.jsx(ke,{id:"address",value:A.address,onChange:Ie=>P({...A,address:Ie.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(ke,{id:"city",value:A.city,onChange:Ie=>P({...A,city:Ie.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(ke,{id:"state",value:A.state,onChange:Ie=>P({...A,state:Ie.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(ke,{id:"zip_code",value:A.zip_code,onChange:Ie=>P({...A,zip_code:Ie.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ke,{id:"birthday",type:"date",value:A.birthday,onChange:Ie=>P({...A,birthday:Ie.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ke,{id:"home_anniversary",type:"date",value:A.home_anniversary,onChange:Ie=>P({...A,home_anniversary:Ie.target.value})})]})]}),e.jsx(po,{}),e.jsx(bSe,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:(l==null?void 0:l.spouse_name)||null,currentSpouseEmail:(l==null?void 0:l.spouse_email)||null,onLink:Ie=>N.mutate({contactId:s,spouseContactId:Ie}),onUnlink:()=>N.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"company_name",children:"Company"}),e.jsx(ke,{id:"company_name",value:A.company_name,onChange:Ie=>P({...A,company_name:Ie.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"job_title",children:"Job Title"}),e.jsx(ke,{id:"job_title",value:A.job_title,onChange:Ie=>P({...A,job_title:Ie.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(qmt,{value:A.lead_source_id||"",onChange:Ie=>P({...A,lead_source_id:Ie})}),e.jsxs("div",{children:[e.jsx(he,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:c==null?void 0:c.filter(Ie=>Ie.active).map(Ie=>{var et;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ei,{checked:(et=A.tagIds)==null?void 0:et.includes(Ie.id),onCheckedChange:Dt=>{var Jt;P(Dt?{...A,tagIds:[...A.tagIds||[],Ie.id]}:{...A,tagIds:(Jt=A.tagIds)==null?void 0:Jt.filter(cs=>cs!==Ie.id)})}}),e.jsx("span",{className:"text-sm",children:Ie.name})]},Ie.id)})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(ur,{id:"notes",value:A.notes,onChange:Ie=>P({...A,notes:Ie.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{onClick:Re,disabled:v.isPending,children:"Save Changes"}),e.jsx(G,{variant:"outline",onClick:()=>T(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[ve.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Ss(new Date(ve[0].completed_at),"MMM d, yyyy")," ","(",ve[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[l.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>$t(l.email),className:"text-primary hover:underline truncate text-left",children:l.email})]}),l.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${l.phone}`,className:"text-primary hover:underline",children:l.phone})]})]}),(l.address||l.city||l.state||l.zip_code)&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ja,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[l.address&&e.jsx("span",{children:l.address}),(l.city||l.state||l.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[l.city,l.state].filter(Boolean).join(", "),l.zip_code&&` ${l.zip_code}`]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[l.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",Ss(Ul(l.birthday),"MMMM d")]})]}),l.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",Ss(Ul(l.home_anniversary),"MMMM d")]})]}),l.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",Ss(new Date(l.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(po,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(bSe,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:l.spouse_name||null,currentSpouseEmail:l.spouse_email||null,onLink:Ie=>N.mutate({contactId:s,spouseContactId:Ie}),onUnlink:()=>N.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(l.company_name||l.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:l.job_title&&l.company_name?`${l.job_title} at ${l.company_name}`:l.job_title||l.company_name})]})]}),e.jsx(po,{}),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:(at=l.tags)!=null&&at.length?l.tags.map(Ie=>{var et;return e.jsx(Ge,{variant:"secondary",children:(et=Ie.relationship_type)==null?void 0:et.name},Ie.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),l.notes&&e.jsxs(e.Fragment,{children:[e.jsx(po,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:l.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(S5s,{contact:l,onLogTouch:()=>B(!0)}),e.jsx(HTs,{contactId:s}),e.jsx(ITs,{contactId:s}),e.jsx(PTs,{contactId:s}),e.jsx(DTs,{contactId:s,contactName:l.first_name}),e.jsx(RTs,{contactId:s,contactName:l.first_name}),e.jsx(qTs,{contactId:s}),e.jsx(BTs,{contactId:s}),e.jsx($Ts,{contactId:s}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Activity Log"})}),e.jsx(De,{children:ve.length>0?e.jsx("div",{className:"space-y-4",children:ve.map(Ie=>{var et;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:Ie.color},children:Ie.type==="popby"?e.jsx(li,{className:"h-4 w-4"}):(et=Ie.name)==null?void 0:et.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:Ie.name}),Ie.videoId&&e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ce(Ie.videoId),children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Ie.completed_at),"MMM d, yyyy h:mm a")}),Ie.notes&&!Ie.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ie.notes})]})]},Ie.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),x&&x.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(bi,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:x.map(Ie=>{var et,Dt;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(et=Ie.video)!=null&&et.thumbnail_url?e.jsx("img",{src:Ie.video.thumbnail_url,alt:Ie.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>ce(Ie.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:()=>ce(Ie.video_id),children:e.jsx(sn,{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: ",((Dt=Ie.video)==null?void 0:Dt.title)||"Untitled Video"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>ce(Ie.video_id),children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Ie.created_at),"MMM d, yyyy h:mm a")}),Ie.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',Ie.message,'"']})]})]},Ie.id)})})})]}),Pe&&Pe.length>0&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:Pe.map(Ie=>e.jsxs(vs,{children:[e.jsx(Ni,{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(Qs,{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:Ie.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Ie.to_email," · ",Ss(new Date(Ie.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(ya,{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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5 text-sky-500"}),Ie.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Ie.to_email," · ",Ss(new Date(Ie.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:Ie.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${Ie.subject}`})})]})]},Ie.id))})})]})]}),e.jsx(vs,{open:!!de,onOpenChange:Ie=>!Ie&&ce(null),children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsx(bs,{children:"Video Preview"})}),de&&e.jsx(UTs,{videoId:de})]})})]})]})}),Oe&&l&&me&&e.jsx(j1,{open:ae,onOpenChange:ie,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:me.email},gmailEmail:Me}),l&&l.email&&e.jsx(NTs,{open:ge,onOpenChange:be,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:l.email}})]}):e.jsx(_s,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(G,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function WTs({rangeDays:s}){const{user:t}=As(),r=es(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),{data:d=[],isLoading:h}=gt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let g=H.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();g=g.gte("created_at",b)}const{data:v,error:j}=await g;if(j)throw j;return v||[]}}),{data:m}=gt({queryKey:["newsletter-campaign-recipients",n],enabled:!!n,queryFn:async()=>{const{data:g,error:v}=await H.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",n).order("sent_at",{ascending:!1}).limit(2e3);if(v)throw v;return g||[]}}),x=async()=>{if(!(!i||!t)){c(!0);try{const{data:g,error:v}=await H.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(v)throw v;if(!g||g.length===0){ue.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:j}=await H.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!j)throw new Error("Original campaign not found");const{data:b,error:N}=await H.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:j.subject,body_html:j.body_html,from_email:j.from_email,reply_to_email:j.reply_to_email,total_recipients:g.length,status:"draft"}).select("id").single();if(N)throw N;const S=g.map(A=>({campaign_id:b.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const v=g.sent_count||0,j=v>0?g.open_count/v*100:0,b=v>0?g.click_count/v*100:0,N=g.sent_at?Kg(new Date,new Date(g.sent_at)):0,S=g.status==="sent"&&N>=3&&v>0&&g.open_counta(g.id),children:[e.jsx(jn,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),S&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>l(g),children:[e.jsx($3,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),g.status==="sent"&&v>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(WU,{icon:e.jsx(Zr,{className:"h-3.5 w-3.5"}),label:"Sent",value:v,sub:`of ${g.total_recipients}`}),e.jsx(WU,{icon:e.jsx(jn,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:g.open_count,sub:`${j.toFixed(1)}%`,children:e.jsx(ri,{value:j,className:"h-1 mt-1"})}),e.jsx(WU,{icon:e.jsx(Dd,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:g.click_count,sub:`${b.toFixed(1)}%`,children:e.jsx(ri,{value:b,className:"h-1 mt-1"})}),e.jsx(WU,{icon:e.jsx(dM,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:g.bounce_count,sub:g.bounce_count>0?"review":"none"})]})]},g.id)})})]})}),e.jsx(G2,{open:!!n,onOpenChange:g=>!g&&a(null),children:e.jsxs(I_,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(W2,{children:e.jsx(K2,{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(g=>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:g.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:g.email})]}),e.jsx("td",{className:"py-2 text-xs",children:g.opened_at?e.jsx(Ge,{variant:"default",className:"text-xs",children:Ss(new Date(g.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:g.clicked_at?e.jsx(Ge,{variant:"default",className:"text-xs bg-purple-600",children:Ss(new Date(g.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[g.status==="sent"&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"sent"}),g.status==="pending"&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"queued"}),g.status==="failed"&&e.jsx(Ge,{variant:"destructive",className:"text-xs",title:g.error_message||"",children:"failed"}),g.status==="suppressed"&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},g.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Yo,{open:!!i,onOpenChange:g=>!g&&l(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Resend to non-openers?"}),e.jsxs(Uo,{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(zo,{children:[e.jsx(qo,{disabled:o,children:"Cancel"}),e.jsx(Eo,{onClick:x,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($3,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function WU({icon:s,label:t,value:r,sub:n,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:r.toLocaleString()}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),a]})}const Cqe=["Gmail","Mass Email","Campaign","Client Portal Invite"],KTs={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 YTs(){const{user:s}=As(),{data:t=[],isLoading:r}=Kmt(),[n,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState("30"),[d,h]=k.useState(!1),{gmailEmail:m}=Oh(),x=k.useMemo(()=>Array.from(new Set(t.map(b=>b.contact_id).filter(Boolean))),[t]),{data:g}=gt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,x.length],enabled:x.length>0,queryFn:async()=>{const{data:b}=await H.from("innercircle_contacts").select("id, first_name, last_name").in("id",x),N=new Map;return(b||[]).forEach(S=>{N.set(S.id,[S.first_name,S.last_name].filter(Boolean).join(" ")||"Contact")}),N}}),v=k.useMemo(()=>{const b=o==="all"?null:Date.now()-parseInt(o)*864e5,N=n.trim().toLowerCase();return t.filter(S=>{if(i!=="all"&&S.channel!==i||b&&new Date(S.sent_at).getTime(){const b={};return v.forEach(N=>{b[N.channel]=(b[N.channel]||0)+1}),b},[v]);return e.jsx(_s,{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(Zr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All emails you've sent through LevelUp — Gmail, mass emails, campaigns, and client portal invites."})]}),e.jsxs(G,{onClick:()=>h(!0),children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total"}),e.jsx("p",{className:"text-2xl font-bold",children:v.length})]})}),Cqe.map(b=>e.jsx(Ne,{children:e.jsxs(De,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase truncate",children:b}),e.jsx("p",{className:"text-2xl font-bold",children:j[b]||0})]})},b))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search subject, recipient, contact...",value:n,onChange:b=>a(b.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:i,onValueChange:l,children:[e.jsx(Os,{className:"w-[200px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Channels"}),Cqe.map(b=>e.jsx(mt,{value:b,children:b},b))]})]}),e.jsxs(zs,{value:o,onValueChange:c,children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"7",children:"Last 7 days"}),e.jsx(mt,{value:"30",children:"Last 30 days"}),e.jsx(mt,{value:"90",children:"Last 90 days"}),e.jsx(mt,{value:"365",children:"Last year"}),e.jsx(mt,{value:"all",children:"All time"})]})]})]}),e.jsx(WTs,{rangeDays:o==="all"?null:parseInt(o)}),r?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):v.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Qs,{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(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"})]})}),e.jsx("tbody",{children:v.slice(0,500).map(b=>{const N=b.contact_id?g==null?void 0:g.get(b.contact_id):null;return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Ss(new Date(b.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Ge,{variant:"outline",className:KTs[b.channel],children:b.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:b.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:b.to_email}),e.jsx("td",{className:"py-3 px-4",children:b.contact_id&&N?e.jsx(Kn,{to:`/mission-control/contacts/${b.contact_id}`,className:"text-primary hover:underline",children:N}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]},b.id)})})]}),v.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",v.length," — narrow your filters to see more."]})]})})}),e.jsx(j1,{open:d,onOpenChange:h,gmailEmail:m})]})})}const Tqe={Crown:nm,FileText:ln,Users:fr,Globe:gc,Star:Qn,Phone:Nn,MessageSquare:bi,PenTool:Qj,Video:sn,Gift:li},g_e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ZTs(){var Nt,Ft;const s=vr(),{user:t}=As(),{data:r}=qx(),{data:n}=b$t(),{data:a}=C$t(),{data:i}=qnt(),{data:l}=tz(),{data:o}=v$t(),c=T$t(),d=_$t(),h=j$t(),m=N$t(),x=k$t(),g=S$t(),v=w$t(),[j,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(null),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState([]),[X,K]=k.useState(null),[Q,Y]=k.useState(null),[ne,de]=k.useState(!1),[ce,ae]=k.useState(""),[ie,me]=k.useState(""),[oe,ge]=k.useState(""),[be,Oe]=k.useState(""),Me=(at,Ie)=>a==null?void 0:a.some(et=>et.plan_id===at&&et.relationship_type_id===Ie&&et.active),Pe=at=>a==null?void 0:a.find(Ie=>Ie.relationship_type_id===at&&Ie.active),Ee=async(at,Ie)=>{const et=Me(at,Ie);await c.mutateAsync({planId:at,relationshipTypeId:Ie,active:!et})},$e=(n==null?void 0:n.filter(at=>at.active&&!at.owner_user_id))||[],Se=(n==null?void 0:n.filter(at=>at.owner_user_id===(t==null?void 0:t.id)))||[],ze=r==null?void 0:r.find(at=>at.id===j),Te=j?Pe(j):null,ye=n==null?void 0:n.find(at=>at.id===(Te==null?void 0:Te.plan_id)),ct=async()=>{if(!P.trim())return;const at=await d.mutateAsync({name:P,description:B});at&&F.length>0&&await x.mutateAsync({planId:at.id,items:F}),Re()},ve=async()=>{!P.trim()||!T||(await h.mutateAsync({id:T,name:P,description:B}),await x.mutateAsync({planId:T,items:F}),Re())},rt=at=>{var Ie;A(at.id),D(at.name),z(at.description||""),$(((Ie=at.items)==null?void 0:Ie.map(et=>({month_number:et.month_number,action_type_id:et.action_type_id,default_script_id:et.default_script_id||void 0,notes:et.notes||void 0})))||[]),S(!0)},Re=()=>{S(!1),A(null),D(""),z(""),$([])},Qe=(at,Ie)=>{Y(Ie)},Ke=(at,Ie,et)=>{$(Dt=>[...Dt.filter(cs=>cs.month_number!==at),{month_number:at,action_type_id:Ie,default_script_id:et}]),K(null),Y(null)},Ce=at=>{$(Ie=>Ie.filter(et=>et.month_number!==at))},nt=async()=>{if(!ce.trim()||!ie.trim()||!Q)return;const at=await g.mutateAsync({actionTypeId:Q,title:ce,scriptBody:ie,emailSubject:oe||void 0,tone:be||void 0});at&&X!==null&&Ke(X,Q,at.id),de(!1),ae(""),me(""),ge(""),Oe("")},$t=Q?o==null?void 0:o.filter(at=>at.action_type_id===Q&&at.active):[],lt=at=>Tqe[at||"Phone"]||Nn,it=at=>Tqe[at||"Users"]||fr;return e.jsxs(_s,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Vo,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(G,{onClick:()=>S(!0),className:"w-full sm:w-auto",children:[e.jsx(Ws,{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(at=>at.active).map(at=>{const Ie=it(at.icon),et=(i==null?void 0:i[at.id])||0,Dt=Pe(at.id),Jt=n==null?void 0:n.find(Ht=>Ht.id===(Dt==null?void 0:Dt.plan_id)),cs=j===at.id;return e.jsxs("button",{onClick:()=>b(at.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${cs?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Ie,{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:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[et," contacts"]})]}),Jt?e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(mi,{className:"h-3 w-3 mr-1"}),Jt.name.split(" ")[0]]}):e.jsx(Ge,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},at.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:j&&ze?e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[(()=>{const at=it(ze.icon);return e.jsx(at,{className:"h-5 w-5"})})(),ze.name," Touchpoint Plan"]}),e.jsxs(Nr,{children:["Choose a plan for your ",ze.name," contacts"]})]}),e.jsxs(De,{className:"space-y-6",children:[ye&&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(mi,{className:"h-4 w-4 text-green-500"}),"Currently using: ",ye.name]}),ye.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ye.description})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>Ee(ye.id,j),children:"Disable"})]}),ye.items&&ye.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(rn,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:g_e.map((at,Ie)=>{var cs,Ht;const et=((cs=ye.items)==null?void 0:cs.filter(dt=>dt.month_number===Ie+1))||[],Dt=(Ht=et[0])==null?void 0:Ht.action_type,Jt=Dt?lt(Dt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${et.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:at}),Jt&&e.jsx(Jt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Dt==null?void 0:Dt.color)||"#3B82F6"}})]},Ie)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:ye?"Switch to a Different Plan":"Choose a Plan"}),$e.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"}),$e.map(at=>{var et;const Ie=(ye==null?void 0:ye.id)===at.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ie?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((et=at.items)==null?void 0:et.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:v.isPending,onClick:()=>{const Dt=`${at.name} (Copy)`;v.mutate({sourcePlanId:at.id,newName:Dt})},children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:Ie?"outline":"default",disabled:Ie||c.isPending,onClick:()=>Ee(at.id,j),children:Ie?"Active":"Use This"})]})]},at.id)})]}),Se.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Se.map(at=>{var et;const Ie=(ye==null?void 0:ye.id)===at.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ie?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:at.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((et=at.items)==null?void 0:et.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>rt(at),children:e.jsx(bv,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>m.mutate(at.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})}),e.jsx(G,{size:"sm",variant:Ie?"outline":"default",disabled:Ie||c.isPending,onClick:()=>Ee(at.id,j),children:Ie?"Active":"Use This"})]})]},at.id)})]}),$e.length===0&&Se.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(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(rn,{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(Ne,{className:"bg-muted/50",children:e.jsx(De,{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:N,onOpenChange:at=>{at?S(!0):Re()},children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:T?"Edit Touchpoint Plan":"Create Custom Touchpoint Plan"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(ke,{id:"plan-name",value:P,onChange:at=>D(at.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(ur,{id:"plan-description",value:B,onChange:at=>z(at.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"12-Month Schedule"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Click on a month to add a touchpoint"}),e.jsx("div",{className:"grid grid-cols-6 gap-2",children:g_e.map((at,Ie)=>{const et=Ie+1,Dt=F.find(Ht=>Ht.month_number===et),Jt=Dt?l==null?void 0:l.find(Ht=>Ht.id===Dt.action_type_id):null,cs=Jt?lt(Jt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>K(X===et?null:et),className:` w-full p-3 rounded-lg border text-center transition-all ${Dt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${X===et?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:at}),cs?e.jsx(cs,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Jt==null?void 0:Jt.color)||"#3B82F6"}}):e.jsx(Ws,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Dt&&e.jsx("button",{type:"button",onClick:Ht=>{Ht.stopPropagation(),Ce(et)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(_r,{className:"h-3 w-3"})})]},Ie)})}),X!==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 ",g_e[X-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(at=>at.active).map(at=>{const Ie=lt(at.icon);return e.jsxs("button",{type:"button",onClick:()=>Qe(X,at.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Ie,{className:"h-4 w-4",style:{color:at.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:at.name})]},at.id)})})]}),X!==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(G,{variant:"ghost",size:"sm",onClick:()=>Y(null),children:[e.jsx(Vo,{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:()=>Ke(X,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"})]})}),$t==null?void 0:$t.map(at=>e.jsx("button",{type:"button",onClick:()=>Ke(X,Q,at.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:at.title}),at.tone&&e.jsx(Ge,{variant:"secondary",className:"text-xs mt-1",children:at.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[at.script_body.substring(0,100),"..."]})]})},at.id)),e.jsxs("button",{type:"button",onClick:()=>de(!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(Ws,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),F.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[F.length," touchpoint",F.length!==1?"s":""," per year"]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:Re,children:"Cancel"}),e.jsxs(G,{onClick:T?ve:ct,disabled:!P.trim()||d.isPending||h.isPending,children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),T?"Save Changes":"Create Plan"]})]})]})}),e.jsx(vs,{open:ne,onOpenChange:de,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(bs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-title",children:"Script Title"}),e.jsx(ke,{id:"script-title",value:ce,onChange:at=>ae(at.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(zs,{value:be,onValueChange:Oe,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select tone..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"friendly",children:"Friendly"}),e.jsx(mt,{value:"professional",children:"Professional"}),e.jsx(mt,{value:"casual",children:"Casual"}),e.jsx(mt,{value:"formal",children:"Formal"})]})]})]}),((Ft=(Nt=l==null?void 0:l.find(at=>at.id===Q))==null?void 0:Nt.name)==null?void 0:Ft.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(ke,{id:"script-email-subject",value:oe,onChange:at=>ge(at.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-body",children:"Script Content"}),e.jsx(ur,{id:"script-body",value:ie,onChange:at=>me(at.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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsxs(G,{onClick:nt,disabled:!ce.trim()||!ie.trim()||g.isPending,children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})})]})}function XTs(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 Ymt="popby_geocode_cache_v1";function QTs(){try{return JSON.parse(localStorage.getItem(Ymt)||"{}")}catch{return{}}}function JTs(s){try{localStorage.setItem(Ymt,JSON.stringify(s))}catch{}}function eEs({contacts:s,onLogPopby:t}){const[r,n]=k.useState(null),[a,i]=k.useState("idle"),[l,o]=k.useState(5),[c,d]=k.useState(""),[h,m]=k.useState(new Map),[x,g]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:S}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S!=null&&S.value&&d(S.value)})()},[]);const v=k.useMemo(()=>s.filter(S=>S.isDue&&(S.address||S.city&&S.state||S.zip)),[s]),j=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(S=>{n({lat:S.coords.latitude,lng:S.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};k.useEffect(()=>{if(!c||!r||v.length===0)return;let S=!1;const T=QTs(),A=new Map;v.forEach(D=>{const B=[D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase();T[B]&&A.set(D.id,T[B])}),m(new Map(A));const P=v.filter(D=>!([D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase()in T));if(P.length!==0)return g(!0),(async()=>{const D=[...P],B=async()=>{var z,F;for(;D.length&&!S;){const $=D.shift(),X=[$.address,$.city,$.state,$.zip].filter(Boolean),K=X.join("|").toLowerCase(),Q=X.join(", ");try{const ne=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(Q)}.json?limit=1&access_token=${c}`)).json();if((F=(z=ne==null?void 0:ne.features)==null?void 0:z[0])!=null&&F.center){const[de,ce]=ne.features[0].center;T[K]={lat:ce,lng:de},A.set($.id,{lat:ce,lng:de})}else T[K]=null}catch{}}};await Promise.all([B(),B(),B(),B()]),S||(JTs(T),m(new Map(A)),g(!1))})(),()=>{S=!0}},[c,r,v]);const b=k.useMemo(()=>{if(!r)return[];const S=[];return v.forEach(T=>{const A=h.get(T.id);if(!A)return;const P=XTs(r.lat,r.lng,A.lat,A.lng);P<=l&&S.push({...T,distanceMiles:P,lat:A.lat,lng:A.lng})}),S.sort((T,A)=>T.distanceMiles-A.distanceMiles)},[r,v,h,l]),N=S=>{const A=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${S.lat},${S.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${S.lat},${S.lng}`;window.open(A,"_blank","noopener")};return e.jsxs(Ne,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(lM,{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(zs,{value:String(l),onValueChange:S=>o(Number(S)),children:[e.jsx(Os,{className:"w-[110px] h-9",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"2",children:"2 miles"}),e.jsx(mt,{value:"5",children:"5 miles"}),e.jsx(mt,{value:"10",children:"10 miles"}),e.jsx(mt,{value:"25",children:"25 miles"})]})]}),e.jsxs(G,{size:"sm",variant:a==="ok"?"outline":"default",onClick:j,disabled:a==="loading",children:[a==="loading"?e.jsx(Di,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(lM,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(De,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ja,{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(Hi,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&v.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&v.length>0&&x&&b.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Vs,{className:"h-14 w-full"}),e.jsx(Vs,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!x&&b.length===0&&v.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ge,{variant:"secondary",className:"font-medium",children:[b.length," nearby"]}),x&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Di,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:b.map(S=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[S.first_name," ",S.last_name]}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:S.distanceMiles<1?`${(S.distanceMiles*5280).toFixed(0)} ft`:`${S.distanceMiles.toFixed(1)} mi`}),S.daysOverdue>0&&e.jsxs(Ge,{variant:"destructive",className:"text-xs",children:[S.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[S.address,S.city,S.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.phone&&e.jsx(G,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${S.phone}`,children:e.jsx(Nn,{className:"h-4 w-4"})})}),e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>N(S),className:"h-9 w-9",title:"Directions",children:e.jsx(bO,{className:"h-4 w-4"})}),e.jsxs(G,{size:"sm",onClick:()=>t(S),children:[e.jsx(li,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},S.id))})]})]})]})}const tEs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",sEs=[{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 rEs(){const s=vr(),t=Mmt(),{data:r}=v5s(),{data:n}=qx(),{data:a}=lAe(),{data:i}=Tge(90),{data:l}=$m(),o=N5s(),c=w5s(),d=_5s(),h=j5s(),{data:m=[],isLoading:x}=gt({queryKey:["popby-templates"],queryFn:async()=>{const{data:ne,error:de}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",tEs).order("publish_date",{ascending:!1});if(de)throw de;const{data:ce}=await H.from("template_likes").select("template_id"),{data:ae}=await H.from("template_comments").select("template_id"),ie=new Map;ce==null||ce.forEach(oe=>{ie.set(oe.template_id,(ie.get(oe.template_id)||0)+1)});const me=new Map;return ae==null||ae.forEach(oe=>{me.set(oe.template_id,(me.get(oe.template_id)||0)+1)}),(ne||[]).map(oe=>({...oe,likesCount:ie.get(oe.id)||0,commentsCount:me.get(oe.id)||0}))}}),g=ne=>{const de=l==null?void 0:l.find(ce=>ce.id===ne);return de?`${de.first_name} ${de.last_name||""}`.trim():"Unknown"},v=ne=>{if(!ne)return null;const de=r==null?void 0:r.find(ce=>ce.id===ne);return(de==null?void 0:de.name)||null},[j,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[P,D]=k.useState(!1),[B,z]=k.useState({popby_item_id:"",notes:""}),[F,$]=k.useState({name:"",description:""}),X=async()=>{j&&(await c.mutateAsync({contact_id:j.id,popby_item_id:B.popby_item_id||void 0,notes:B.notes||void 0}),S(!1),b(null),z({popby_item_id:"",notes:""}))},K=async()=>{F.name.trim()&&(await d.mutateAsync({name:F.name.trim(),description:F.description.trim()||void 0}),D(!1),$({name:"",description:""}))},Q=async(ne,de)=>{await h.mutateAsync({relationship_type_id:ne,frequency_days:parseInt(de)})},Y=ne=>{var ce;const de=a==null?void 0:a.find(ae=>ae.relationship_type_id===ne);return((ce=de==null?void 0:de.frequency_days)==null?void 0:ce.toString())||"90"};return e.jsx(_s,{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(Ne,{children:e.jsxs(De,{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(Ne,{children:e.jsxs(De,{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(Ne,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(G,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(G,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(G,{variant:"outline",onClick:()=>D(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(Rn,{defaultValue:"due",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"due",children:"Due for Popby"}),e.jsx(Xt,{value:"activity",children:"Recent Activity"}),e.jsx(Xt,{value:"library",children:"Popby Library"}),e.jsx(Xt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(as,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(eEs,{contacts:t||[],onLogPopby:ne=>{b(ne),S(!0)}}),!t||t.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(li,{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(ne=>e.jsx(Ne,{className:"hover:shadow-md transition-shadow",children:e.jsx(De,{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:[ne.first_name," ",ne.last_name]}),ne.daysOverdue>0&&e.jsxs(Ge,{variant:"destructive",className:"text-xs",children:[ne.daysOverdue,"+ days overdue"]}),ne.daysSinceLastPopby===null&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[ne.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),ne.city||ne.address]}),ne.tags&&ne.tags.length>0&&e.jsx("span",{children:ne.tags.map(de=>{var ce;return(ce=de.relationship_type)==null?void 0:ce.name}).join(", ")})]}),ne.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Ss(new Date(ne.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ne.phone&&e.jsx(G,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${ne.phone}`,children:e.jsx(Nn,{className:"h-4 w-4"})})}),e.jsxs(G,{size:"sm",onClick:()=>{b(ne),S(!0)},children:[e.jsx(mi,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},ne.id))})]}),e.jsx(as,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(cn,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(De,{className:"space-y-3",children:i.map(ne=>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(li,{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:g(ne.contact_id)}),v(ne.popby_item_id)&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:v(ne.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ss(new Date(ne.completed_at),"MMM d, yyyy h:mm a")}),ne.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ne.notes})]})]},ne.id))})]})}),e.jsx(as,{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(ne=>e.jsx(Ne,{children:e.jsx(De,{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(li,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:ne.name}),ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ne.description}),!ne.owner_user_id&&e.jsx(Ge,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},ne.id)),e.jsx(Ne,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D(!0),children:e.jsx(De,{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(Ws,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(as,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length," template",m.length!==1?"s":""," found"]}),x&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((ne,de)=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(Vs,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Vs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Vs,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Vs,{className:"h-5 w-16"}),e.jsx(Vs,{className:"h-5 w-20"})]})]})},de))}),!x&&m.length===0&&e.jsx(Ne,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Pl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!x&&m.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:m.map(ne=>e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${ne.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:ne.preview_image_url?e.jsx("img",{src:ne.preview_image_url,alt:ne.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(De,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:ne.name}),ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:H8(ne.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"PopBys"})}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mh,{className:"h-3.5 w-3.5"}),ne.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tc,{className:"h-3.5 w-3.5"}),ne.commentsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:de=>{de.stopPropagation(),s(`/templates/${ne.id}`)},children:[e.jsx(Yr,{className:"h-4 w-4"}),"View Template"]})]})]},ne.id))})]})]}),e.jsx(vs,{open:N,onOpenChange:S,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsxs(bs,{children:["Log Popby for ",j==null?void 0:j.first_name," ",j==null?void 0:j.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Popby Item (optional)"}),e.jsxs(zs,{value:B.popby_item_id,onValueChange:ne=>z(de=>({...de,popby_item_id:ne})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a popby item..."})}),e.jsx(Fs,{children:r==null?void 0:r.map(ne=>e.jsx(mt,{value:ne.id,children:ne.name},ne.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes (optional)"}),e.jsx(ur,{placeholder:"Any notes about this popby...",value:B.notes,onChange:ne=>z(de=>({...de,notes:ne.target.value}))})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(G,{onClick:X,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(vs,{open:T,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{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(ne=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(he,{className:"font-medium",children:ne.name}),e.jsxs(zs,{value:Y(ne.id),onValueChange:de=>Q(ne.id,de),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:sEs.map(de=>e.jsx(mt,{value:de.value,children:de.label},de.value))})]})]},ne.id))]}),e.jsx(on,{children:e.jsx(G,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(vs,{open:P,onOpenChange:D,children:e.jsxs(ys,{children:[e.jsx(js,{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(he,{children:"Name *"}),e.jsx(ke,{placeholder:"e.g., Homemade cookies",value:F.name,onChange:ne=>$(de=>({...de,name:ne.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{placeholder:"Optional description...",value:F.description,onChange:ne=>$(de=>({...de,description:ne.target.value}))})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:!F.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const nEs=M_({property_address:oo().min(1,"Property address is required"),city:oo().optional(),state:oo().optional(),zip:oo().optional(),transaction_type:rtt(["buyer","seller"]),close_date:oo().min(1,"Close date is required"),sale_price:KO().min(0,"Sale price must be positive"),commission_amount:KO().optional(),lead_source_id:oo().optional(),client_type_id:oo().optional(),contact_id:oo().optional(),notes:oo().optional(),is_win:S6t()});function Zmt({open:s,onOpenChange:t,transaction:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(""),m=sxe(),x=pUt(),{data:g}=IP(),{data:v}=qx(),{data:j}=$m(),b=exe(),N=M5e(),{data:S}=rxe(),T=(S==null?void 0:S.show_commission)??!0,A=qpe({resolver:Vpe(nEs),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 P=async F=>{const $={property_address:F.property_address,transaction_type:F.transaction_type,close_date:F.close_date,sale_price:F.sale_price,is_win:F.is_win,commission_amount:F.commission_amount||null,lead_source_id:F.lead_source_id||null,client_type_id:F.client_type_id||null,contact_id:F.contact_id||null,city:F.city||null,state:F.state||null,zip:F.zip||null,notes:F.notes||null};r?await x.mutateAsync({id:r.id,...$}):await m.mutateAsync($),t(!1)},D=async()=>{if(!i.trim())return;const[F,...$]=i.trim().split(" "),X=$.join(" ")||null,K=await b.mutateAsync({first_name:F,last_name:X,tagIds:[]});K&&(A.setValue("contact_id",K.id),l(""),c(!1),a(!1))},B=async()=>{if(!d.trim())return;const F=await N.mutateAsync(d.trim());F&&(A.setValue("lead_source_id",F.id),h(""))},z=j==null?void 0:j.find(F=>F.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(js,{children:e.jsx(bs,{children:r?"Edit Transaction":"Add Transaction"})}),e.jsx(ti,{className:"max-h-[70vh] pr-4",children:e.jsx(Hpe,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(P),className:"space-y-4",children:[e.jsx(rd,{control:A.control,name:"property_address",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Property Address *"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"123 Main St",...F})}),e.jsx(yf,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(rd,{control:A.control,name:"city",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"City"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"City",...F})})]})}),e.jsx(rd,{control:A.control,name:"state",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"State"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"TX",...F})})]})}),e.jsx(rd,{control:A.control,name:"zip",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Zip"}),e.jsx(qc,{children:e.jsx(ke,{placeholder:"75001",...F})})]})})]}),e.jsx(rd,{control:A.control,name:"transaction_type",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Transaction Type *"}),e.jsxs(zs,{onValueChange:F.onChange,value:F.value,children:[e.jsx(qc,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"buyer",children:"Buyer"}),e.jsx(mt,{value:"seller",children:"Seller"})]})]}),e.jsx(yf,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(rd,{control:A.control,name:"close_date",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Close Date *"}),e.jsx(qc,{children:e.jsx(ke,{type:"date",...F})}),e.jsx(yf,{})]})}),e.jsx(rd,{control:A.control,name:"sale_price",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Sale Price *"}),e.jsx(qc,{children:e.jsx(ke,{type:"number",placeholder:"0",...F,onChange:$=>F.onChange(Number($.target.value))})}),e.jsx(yf,{})]})})]}),T&&e.jsx(rd,{control:A.control,name:"commission_amount",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Commission"}),e.jsx(qc,{children:e.jsx(ke,{type:"number",placeholder:"0",...F,value:F.value??"",onChange:$=>F.onChange($.target.value?Number($.target.value):void 0)})})]})}),e.jsx(rd,{control:A.control,name:"lead_source_id",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Lead Source"}),e.jsxs(zs,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(qc,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select source"})})}),e.jsx(Fs,{children:g==null?void 0:g.map($=>e.jsx(mt,{value:$.id,children:$.name},$.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Add custom source...",value:d,onChange:F=>h(F.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:B,disabled:!d.trim(),children:e.jsx(Ws,{className:"h-4 w-4"})})]}),e.jsx(rd,{control:A.control,name:"client_type_id",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Client Type"}),e.jsxs(zs,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(qc,{children:e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select client type"})})}),e.jsx(Fs,{children:v==null?void 0:v.map($=>e.jsx(mt,{value:$.id,children:$.name},$.id))})]})]})}),e.jsx(rd,{control:A.control,name:"contact_id",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Client Contact"}),e.jsxs(Ao,{open:n,onOpenChange:a,children:[e.jsx(Mo,{asChild:!0,children:e.jsx(qc,{children:e.jsxs(G,{variant:"outline",role:"combobox",className:Bt("w-full justify-between",!F.value&&"text-muted-foreground"),children:[z?`${z.first_name} ${z.last_name||""}`.trim():"Select contact",e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(wo,{className:"w-full p-0",align:"start",children:[e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search contacts..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Rx,{children:j==null?void 0:j.map($=>e.jsxs(vf,{value:`${$.first_name} ${$.last_name||""}`,onSelect:()=>{F.onChange($.id),a(!1)},children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",$.id===F.value?"opacity-100":"opacity-0")}),$.first_name," ",$.last_name||""]},$.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(ke,{placeholder:"Enter contact name...",value:i,onChange:$=>l($.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",onClick:D,disabled:!i.trim()||b.isPending,children:"Add Contact"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(rd,{control:A.control,name:"notes",render:({field:F})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Notes"}),e.jsx(qc,{children:e.jsx(ur,{placeholder:"Any notes about this transaction...",...F})})]})}),e.jsx(rd,{control:A.control,name:"is_win",render:({field:F})=>e.jsxs($c,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Uc,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(qc,{children:e.jsx(br,{checked:F.value,onCheckedChange:F.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:m.isPending||x.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}function uAe({transactions:s,showCommission:t,isLoading:r,agentNameMap:n,readOnly:a}){const[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState("all"),[g,v]=k.useState("all"),[j,b]=k.useState("all"),[N,S]=k.useState(!1),T=xUt(),A=sxe(),{data:P}=IP(),{data:D}=qx(),B=tL(),z=X=>{const{id:K,created_at:Q,updated_at:Y,lead_source:ne,client_type:de,contact:ce,...ae}=X;A.mutate(ae)},F=()=>{o&&(T.mutate(o),c(null))},$=s.filter(X=>{var ce,ae,ie,me;const K=d===""||X.property_address.toLowerCase().includes(d.toLowerCase())||((ae=(ce=X.contact)==null?void 0:ce.first_name)==null?void 0:ae.toLowerCase().includes(d.toLowerCase()))||((me=(ie=X.contact)==null?void 0:ie.last_name)==null?void 0:me.toLowerCase().includes(d.toLowerCase())),Q=m==="all"||X.transaction_type===m,Y=g==="all"||X.lead_source_id===g,ne=j==="all"||X.client_type_id===j,de=!N||X.is_win;return K&&Q&&Y&&ne&&de});return r?e.jsx(Ne,{children:e.jsx(De,{className:"p-6 space-y-4",children:[1,2,3].map(X=>e.jsx(Vs,{className:"h-16 w-full"},X))})}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{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(zt,{children:["Transactions (",$.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search...",value:d,onChange:X=>h(X.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{className:"w-[100px]",children:e.jsx(Us,{placeholder:"Type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),e.jsx(mt,{value:"buyer",children:"Buyer"}),e.jsx(mt,{value:"seller",children:"Seller"})]})]}),e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{className:"w-[130px]",children:e.jsx(Us,{placeholder:"Lead Source"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Sources"}),P==null?void 0:P.map(X=>e.jsx(mt,{value:X.id,children:X.name},X.id))]})]}),e.jsxs(G,{variant:N?"default":"outline",size:"sm",onClick:()=>S(!N),children:[e.jsx(Xl,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(De,{children:$.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):B?e.jsx("div",{className:"space-y-3",children:$.map(X=>e.jsxs(Ne,{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:X.property_address}),X.is_win&&e.jsx(Xl,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[X.city,X.state?`, ${X.state}`:""]})]}),e.jsx(Ge,{variant:X.transaction_type==="buyer"?"default":"secondary",children:X.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: "}),sRe(X.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),uc(X.sale_price)]}),t&&X.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),uc(X.commission_amount)]}),X.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),X.lead_source.name]}),X.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),X.contact.first_name," ",X.contact.last_name]}),n&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[X.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>l(X),children:e.jsx(nd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>z(X),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(X.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]},X.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[n&&e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Close Date"}),e.jsx(Tt,{children:"Sale Price"}),t&&e.jsx(Tt,{children:"Commission"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Client"}),!a&&e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(Bn,{children:$.map(X=>{var K;return e.jsxs(qs,{children:[n&&e.jsx(ft,{className:"font-medium text-sm",children:n[X.owner_user_id]||"Unknown"}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[X.is_win&&e.jsx(Xl,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:X.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[X.city,X.state?`, ${X.state}`:""]})]})]})}),e.jsx(ft,{children:e.jsx(Ge,{variant:X.transaction_type==="buyer"?"default":"secondary",children:X.transaction_type})}),e.jsx(ft,{children:sRe(X.close_date)}),e.jsx(ft,{children:uc(X.sale_price)}),t&&e.jsx(ft,{children:X.commission_amount?uc(X.commission_amount):"-"}),e.jsx(ft,{children:((K=X.lead_source)==null?void 0:K.name)||"-"}),e.jsx(ft,{children:X.contact?`${X.contact.first_name} ${X.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(ft,{children:e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",children:e.jsx(Eg,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",children:[e.jsxs(Da,{onClick:()=>l(X),children:[e.jsx(nd,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Da,{onClick:()=>z(X),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Da,{onClick:()=>c(X.id),className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},X.id)})})]})})})]}),e.jsx(Zmt,{open:!!i,onOpenChange:X=>!X&&l(null),transaction:i||void 0}),e.jsx(Yo,{open:!!o,onOpenChange:X=>!X&&c(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Transaction?"}),e.jsx(Uo,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:F,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Xmt({goals:s,stats:t,year:r,showCommission:n}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===r?a:12,l=12-i,o=(x,g)=>{if(!g||g===0)return null;const v=Math.min(x/g*100,100),j=Math.max(g-x,0),b=l>0?j/l:0,N=i/12*100,S=v>=N?"ahead":v>=N*.8?"on-track":"behind";return{percent:v,remaining:j,pace:b,status:S}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),h=n?o(t.totalCommission,s.gci_goal):null,m=x=>{switch(x){case"ahead":return e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(_o,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Ge,{variant:"secondary",children:[e.jsx(qv,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Ge,{variant:"destructive",children:[e.jsx(a_,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zd,{className:"h-5 w-5 text-primary"}),e.jsxs(zt,{children:[r," Goals Progress"]})]})}),e.jsx(De,{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(ri,{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(ri,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[uc(t.totalVolume,!0)," of ",uc(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 ",uc(d.pace,!0),"/month"]})]}),n&&s.gci_goal&&h&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"GCI"}),m(h.status)]}),e.jsx(ri,{value:h.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[uc(t.totalCommission,!0)," of ",uc(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(h.percent),"%"]})]}),h.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",uc(h.pace,!0),"/month"]})]})]})})]})}const aEs={light:"",dark:".dark"},Qmt=k.createContext(null);function Jmt(){const s=k.useContext(Qmt);if(!s)throw new Error("useChart must be used within a ");return s}const eft=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(Qmt.Provider,{value:{config:n},children:e.jsxs("div",{"data-chart":o,ref:i,className:Bt("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(iEs,{id:o,config:n}),e.jsx(IM,{children:r})]})})});eft.displayName="Chart";const iEs=({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(aEs).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},tft=k.forwardRef(({active:s,payload:t,className:r,indicator:n="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:h,nameKey:m,labelKey:x},g)=>{const{config:v}=Jmt(),j=k.useMemo(()=>{var P;if(a||!(t!=null&&t.length))return null;const[N]=t,S=`${x||N.dataKey||N.name||"value"}`,T=_Se(v,N,S),A=!x&&typeof l=="string"?((P=v[l])==null?void 0:P.label)||l:T==null?void 0:T.label;return o?e.jsx("div",{className:Bt("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:Bt("font-medium",c),children:A}):null},[l,o,t,a,c,v,x]);if(!s||!(t!=null&&t.length))return null;const b=t.length===1&&n!=="dot";return e.jsxs("div",{ref:g,className:Bt("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:j,e.jsx("div",{className:"grid gap-1.5",children:t.map((N,S)=>{const T=`${m||N.name||N.dataKey||"value"}`,A=_Se(v,N,T),P=h||N.payload.fill||N.color;return e.jsx("div",{className:Bt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:d&&(N==null?void 0:N.value)!==void 0&&N.name?d(N.value,N.name,N,S,N.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:Bt("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":P,"--color-border":P}}),e.jsxs("div",{className:Bt("flex flex-1 justify-between leading-none",b?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[b?j:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||N.name})]}),N.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:N.value.toLocaleString()})]})]})},N.dataKey)})})]})});tft.displayName="ChartTooltip";const oEs=k.forwardRef(({className:s,hideIcon:t=!1,payload:r,verticalAlign:n="bottom",nameKey:a},i)=>{const{config:l}=Jmt();return r!=null&&r.length?e.jsx("div",{ref:i,className:Bt("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=_Se(l,o,c);return e.jsxs("div",{className:Bt("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});oEs.displayName="ChartLegend";function _Se(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 KU=["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 hAe({stats:s,year:t}){const r=s.transactionsByMonth.some(a=>a.count>0),n=s.leadSourceBreakdown.length>0;return!r&&!n?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{className:"overflow-hidden",children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(De,{className:"overflow-hidden",children:e.jsx(eft,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(IM,{width:"100%",height:"100%",children:e.jsxs(umt,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(Kht,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(D5,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(R5,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(rp,{content:e.jsx(tft,{})}),e.jsx(j_,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(De,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(IM,{width:"100%",height:"100%",children:e.jsxs(hmt,{children:[e.jsx(w1,{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(wz,{fill:KU[i%KU.length]},`cell-${i}`))}),e.jsx(rp,{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:KU[i%KU.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function lEs(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=j3e(t,n,new Date);if(a2e(a))return Ss(a,"yyyy-MM-dd")}catch{}try{const n=new Date(t);if(a2e(n))return Ss(n,"yyyy-MM-dd")}catch{}return null}const cEs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function dEs({open:s,onOpenChange:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!1),[l,o]=k.useState(0),{data:c}=IP(),{data:d}=qx(),h=sxe(),m=()=>{const N=cEs.join(","),S=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),T=`${N} ${S}`,A=new Blob([T],{type:"text/csv"}),P=URL.createObjectURL(A),D=document.createElement("a");D.href=P,D.download="transaction-import-template.csv",D.click(),URL.revokeObjectURL(P)},x=N=>{const S=N.split(` `).filter(A=>A.trim());if(S.length<2)return[];const T=S[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return S.slice(1).map((A,P)=>{var ce,ae,ie,me;const D=[];let B="",z=!1;for(const oe of A)oe==='"'?z=!z:oe===","&&!z?(D.push(B.trim()),B=""):B+=oe;D.push(B.trim());const F=oe=>{var be;const ge=T.indexOf(oe);return ge>=0?(be=D[ge])==null?void 0:be.replace(/^["']|["']$/g,"").trim():""},$=(ce=F("transaction_type"))==null?void 0:ce.toLowerCase(),X=(ae=F("sale_price"))==null?void 0:ae.replace(/[$,]/g,""),K=(ie=F("commission_amount"))==null?void 0:ie.replace(/[$,]/g,""),Q=(me=F("is_win"))==null?void 0:me.toLowerCase(),Y=F("close_date"),ne=lEs(Y);let de;return F("property_address")?["buyer","seller"].includes($)?ne?(!X||isNaN(Number(X)))&&(de="Invalid sale price"):de=`Invalid date format: "${Y}" - use MM/DD/YYYY or YYYY-MM-DD`:de='Transaction type must be "buyer" or "seller"':de="Missing property address",{property_address:F("property_address"),city:F("city"),state:F("state"),zip:F("zip"),transaction_type:$==="seller"?"seller":"buyer",close_date:ne||"",sale_price:Number(X)||0,commission_amount:K?Number(K):null,lead_source_name:F("lead_source"),client_type_name:F("client_type"),is_win:["yes","true","1"].includes(Q),notes:F("notes"),error:de}})},g=N=>{var A;const S=(A=N.target.files)==null?void 0:A[0];if(!S)return;const T=new FileReader;T.onload=P=>{var z;const D=(z=P.target)==null?void 0:z.result,B=x(D);n(B)},T.readAsText(S)},v=async()=>{const N=r.filter(A=>!A.error);if(N.length===0){ue.error("No valid transactions to import");return}i(!0),o(0);let S=0,T=0;for(let A=0;Az.name.toLowerCase()===P.lead_source_name.toLowerCase()),B=d==null?void 0:d.find(z=>z.name.toLowerCase()===P.client_type_name.toLowerCase());await h.mutateAsync({property_address:P.property_address,city:P.city||null,state:P.state||null,zip:P.zip||null,transaction_type:P.transaction_type,close_date:P.close_date,sale_price:P.sale_price,commission_amount:P.commission_amount,lead_source_id:(D==null?void 0:D.id)||null,client_type_id:(B==null?void 0:B.id)||null,contact_id:null,notes:P.notes||null,is_win:P.is_win}),S++}catch(D){T++,console.error("Failed to import transaction:",D)}o(Math.round((A+1)/N.length*100))}i(!1),S>0&&ue.success(`Imported ${S} transaction${S>1?"s":""}`),T>0&&ue.error(`Failed to import ${T} transaction${T>1?"s":""}`),n([]),t(!1)},j=r.filter(N=>!N.error).length,b=r.filter(N=>N.error).length;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Import Transactions"}),e.jsx(Fr,{children:"Upload a CSV file with your past transactions"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Download Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),e.jsxs(G,{variant:"outline",onClick:m,children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(ke,{id:"csv-file",type:"file",accept:".csv",onChange:g})]}),r.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ge,{variant:"outline",children:[r.length," rows found"]}),j>0&&e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(Hn,{className:"h-3 w-3 mr-1"}),j," valid"]}),b>0&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"}),b," errors"]})]}),e.jsx(ti,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((N,S)=>e.jsxs("div",{className:`p-2 rounded text-sm ${N.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:N.property_address||"(no address)"}),e.jsx(Ge,{variant:N.transaction_type==="buyer"?"default":"secondary",children:N.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[N.close_date," • $",N.sale_price.toLocaleString()]}),N.error&&e.jsx(OTe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(FTe,{className:"text-xs",children:N.error})})]},S)),r.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:v,disabled:j===0||a,children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Import ",j," Transaction",j!==1?"s":""]})]})]})]})})}const uEs=M_({transactions_goal:KO().min(0).optional(),volume_goal:KO().min(0).optional(),gci_goal:KO().min(0).optional()});function hEs({open:s,onOpenChange:t,year:r,existingGoals:n}){const a=gUt(),{data:i}=rxe(),l=(i==null?void 0:i.show_commission)??!0,o=qpe({resolver:Vpe(uEs),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(js,{children:[e.jsxs(bs,{children:[r," Goals"]}),e.jsx(Fr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Hpe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(rd,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Transactions Goal"}),e.jsx(qc,{children:e.jsx(ke,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(Nde,{children:"Total number of deals you want to close"}),e.jsx(yf,{})]})}),e.jsx(rd,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"Volume Goal ($)"}),e.jsx(qc,{children:e.jsx(ke,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(Nde,{children:"Total sales volume you want to achieve"}),e.jsx(yf,{})]})}),l&&e.jsx(rd,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs($c,{children:[e.jsx(Uc,{children:"GCI Goal ($)"}),e.jsx(qc,{children:e.jsx(ke,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(Nde,{children:"Gross commission income target"}),e.jsx(yf,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function mAe({transactions:s,isLoading:t}){const r=k.useRef(null),n=k.useRef(null),a=k.useRef([]),i=k.useRef(null),{isAdmin:l}=As(),[o,c]=k.useState(""),[d,h]=k.useState(!0),[m,x]=k.useState(0),[g,v]=k.useState(!1),j=s.filter(N=>N.latitude!=null&&N.longitude!=null),b=s.filter(N=>N.latitude==null||N.longitude==null);return k.useEffect(()=>{(async()=>{h(!0);try{const{data:S}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S!=null&&S.value&&c(S.value)}catch(S){console.error("Error fetching mapbox token:",S)}h(!1)})()},[]),k.useEffect(()=>{if(!o||b.length===0||g)return;(async()=>{var T;v(!0);let S=0;for(const A of b){const P=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(P)try{const B=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(P)}.json?access_token=${o}&limit=1`)).json();if((T=B.features)!=null&&T[0]){const[z,F]=B.features[0].center;await H.from("scorecard_transactions").update({latitude:F,longitude:z}).eq("id",A.id),A.latitude=F,A.longitude=z,S++}}catch(D){console.error("Geocode error:",D)}}x(S),v(!1)})()},[o,s]),k.useEffect(()=>{if(!r.current||!o||n.current)return;El.accessToken=o;const N=s.filter(A=>A.latitude!=null&&A.longitude!=null);let S=[-98.5795,39.8283],T=4;if(N.length>0){const A=N.reduce((D,B)=>D+B.longitude,0)/N.length,P=N.reduce((D,B)=>D+B.latitude,0)/N.length;S=[A,P],T=N.length===1?12:10}return n.current=new El.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:T,center:S}),n.current.addControl(new El.NavigationControl,"top-right"),()=>{var A;(A=n.current)==null||A.remove(),n.current=null}},[o]),k.useEffect(()=>{var S;if(!n.current||!o)return;a.current.forEach(T=>T.remove()),a.current=[],(S=i.current)==null||S.remove();const N=s.filter(T=>T.latitude!=null&&T.longitude!=null);if(N.forEach(T=>{var F;const A=T.transaction_type==="buyer",P=A?"#3B82F6":"#10B981",D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
${A?'':''}
`;const B=new El.Popup({offset:25,closeButton:!0}).setHTML(`
${T.property_address}
${T.city?`
${T.city}${T.state?", "+T.state:""} ${T.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(T.sale_price).toLocaleString()}
Closed: ${Ul(T.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(F=T.lead_source)!=null&&F.name?" · "+T.lead_source.name:""}
${T.contact?`
Client: ${T.contact.first_name} ${T.contact.last_name||""}
`:""}
`),z=new El.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(B).addTo(n.current);a.current.push(z)}),N.length>1){const T=new El.LngLatBounds;N.forEach(A=>T.extend([A.longitude,A.latitude])),n.current.fitBounds(T,{padding:60,maxZoom:13})}else N.length===1&&n.current.flyTo({center:[N[0].longitude,N[0].latitude],zoom:12})},[s,o,g]),d||t?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ja,{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:[j.length," of ",s.length," mapped",g&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Hi,{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 sft=()=>{const{data:s}=Xg();return gt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:r}=await H.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 H.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"})},mEs=s=>{const{data:t}=Xg(),{data:r}=sft();return gt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const n=r.map(l=>l.id),{data:a,error:i}=await H.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",n).gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r&&r.length>0})};function fEs(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 pEs(s,t){return s?s.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function xEs({year:s}){var x;const{data:t,isLoading:r}=sft(),{data:n,isLoading:a}=mEs(s),i=vr(),l=r||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:h,teamChartStats:m}=k.useMemo(()=>{if(!t||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const g=t.map($=>fEs($,n));g.sort(($,X)=>X.totalVolume-$.totalVolume);const v={};t.forEach($=>{v[$.id]=$.name||$.email});const j=n.length,b=n.reduce(($,X)=>$+Number(X.sale_price),0),N=n.reduce(($,X)=>$+(Number(X.commission_amount)||0),0),S=n.filter($=>$.transaction_type==="buyer").length,T=n.filter($=>$.transaction_type==="seller").length,A={};n.forEach($=>{var K;const X=((K=$.lead_source)==null?void 0:K.name)||"Unknown";A[X]=(A[X]||0)+1});const P=Object.entries(A).sort(($,X)=>X[1]-$[1])[0],D={};n.forEach($=>{const X=Ul($.close_date).toLocaleString("default",{month:"short"});D[X]=(D[X]||0)+1});const z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map($=>({month:$,count:D[$]||0})),F=Object.entries(A).map(([$,X])=>({name:$,count:X})).sort(($,X)=>X.count-$.count);return{aggregate:{totalTxns:j,buyerCount:S,sellerCount:T,totalVolume:b,avgPrice:j>0?b/j:0,totalGCI:N,topSource:P?{name:P[0],count:P[1]}:null,memberCount:t.length},memberStats:g,topPerformer:g[0]||null,agentNameMap:v,teamChartStats:{transactionsByMonth:z,leadSourceBreakdown:F}}},[t,n]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(g=>e.jsx(Vs,{className:"h-24"},g))}),e.jsx(Vs,{className:"h-64"})]}):!o||c.length===0?e.jsx(Ne,{className:"py-12",children:e.jsxs(De,{className:"text-center space-y-2",children:[e.jsx(fr,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fr,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Cn,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_l,{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:uc(o.totalVolume,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(o.avgPrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_l,{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:uc(o.totalGCI,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{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:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((x=o.topSource)==null?void 0:x.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(Ne,{className:"border-primary/30 bg-primary/5",children:e.jsxs(De,{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(Zi,{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:uc(d.totalVolume,!0)})]})]})}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Member Performance"})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Transactions"}),e.jsx(Tt,{className:"text-center",children:"B / S"}),e.jsx(Tt,{className:"text-right",children:"Volume"}),e.jsx(Tt,{className:"text-right",children:"Avg Price"}),e.jsx(Tt,{className:"text-right",children:"GCI"}),e.jsx(Tt,{className:"text-right"})]})}),e.jsx(Bn,{children:c.map((g,v)=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[v===0&&g.totalTransactions>0&&e.jsx(Zi,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:g.member.avatar_url||void 0}),e.jsx(bn,{className:"text-xs",children:pEs(g.member.name,g.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:g.member.name||g.member.email}),g.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.member.email})]})]})}),e.jsx(ft,{className:"text-center font-semibold",children:g.totalTransactions}),e.jsxs(ft,{className:"text-center text-sm",children:[g.buyerCount," / ",g.sellerCount]}),e.jsx(ft,{className:"text-right font-medium",children:uc(g.totalVolume,!0)}),e.jsx(ft,{className:"text-right text-sm",children:uc(g.averagePrice,!0)}),e.jsx(ft,{className:"text-right font-medium",children:uc(g.totalGCI,!0)}),e.jsx(ft,{className:"text-right",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${g.member.id}`),children:e.jsx(jn,{className:"h-4 w-4"})})})]},g.member.id))})]})})})]}),e.jsxs(Rn,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"transactions",children:[e.jsx(lm,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Xt,{value:"charts",children:[e.jsx(ao,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Xt,{value:"map",children:[e.jsx(ja,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(as,{value:"transactions",children:e.jsx(uAe,{transactions:n||[],showCommission:!0,isLoading:a,agentNameMap:h,readOnly:!0})}),e.jsx(as,{value:"charts",children:m&&e.jsx(hAe,{stats:m,year:s})}),e.jsx(as,{value:"map",children:e.jsx(mAe,{transactions:n||[],isLoading:a})})]})]})}const rft=new Date().getFullYear(),Eqe=Array.from({length:10},(s,t)=>rft-t);function gEs(){var F;const[s,t]=k.useState(rft),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState("my"),{data:x}=Xg(),g=(x==null?void 0:x.role)==="team_leader",{data:v,isLoading:j}=I5e(s),{yearStats:b,lifetimeStats:N,showCommission:S}=lat(s),{data:T,isLoading:A}=oat(s),{data:P}=rxe(),D=yUt(),B=()=>{if(!v||v.length===0)return;const $=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...S?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],X=v.map(de=>{var ce,ae;return[de.property_address,de.city||"",de.state||"",de.zip||"",de.transaction_type,de.close_date,de.sale_price,...S?[de.commission_amount||""]:[],((ce=de.lead_source)==null?void 0:ce.name)||"",((ae=de.client_type)==null?void 0:ae.name)||"",de.contact?`${de.contact.first_name} ${de.contact.last_name||""}`.trim():"",de.is_win?"Yes":"No",de.notes||""]}),K=[$,...X].map(de=>de.map(ce=>`"${String(ce).replace(/"/g,'""')}"`).join(",")).join(` `),Q=new Blob([K],{type:"text/csv"}),Y=URL.createObjectURL(Q),ne=document.createElement("a");ne.href=Y,ne.download=`transactions-${s}.csv`,ne.click(),URL.revokeObjectURL(Y)},z=!v||v.length===0;return e.jsxs(_s,{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"})]}),g&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(G,{variant:h==="my"?"default":"ghost",size:"sm",onClick:()=>m("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(G,{variant:h==="team"?"default":"ghost",size:"sm",onClick:()=>m("team"),className:"h-8",children:[e.jsx(fr,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),h==="team"&&g?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(zs,{value:String(s),onValueChange:$=>t(Number($)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Eqe.map($=>e.jsx(mt,{value:String($),children:$},$))})]})]}),e.jsx(xEs,{year:s})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(zs,{value:String(s),onValueChange:$=>t(Number($)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:Eqe.map($=>e.jsx(mt,{value:String($),children:$},$))})]}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(!c),children:e.jsx(lo,{className:"h-4 w-4"})})]})]}),c&&e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-lg",children:"Settings"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(he,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(br,{checked:(P==null?void 0:P.show_commission)??!0,onCheckedChange:$=>D.mutate({show_commission:$})})]})})]}),z&&!j?e.jsx(Ne,{className:"py-12",children:e.jsxs(De,{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(ao,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(G,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx(G,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(G,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(G,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(G,{variant:"outline",onClick:B,disabled:z,children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Xa,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.totalTransactions," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_l,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[uc(N.totalVolume,!0)," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(b.averagePrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{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:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((F=b.topLeadSource)==null?void 0:F.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),S&&e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_l,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[uc(N.totalCommission,!0)," lifetime"]})]})}),S&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(Ne,{children:e.jsxs(De,{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(_l,{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:uc(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[uc(N.totalNetToAgent,!0)," lifetime"]})]})})]}),T&&e.jsx(Xmt,{goals:T,stats:b,year:s,showCommission:S}),e.jsxs(Rn,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"transactions",children:"Transactions"}),e.jsx(Xt,{value:"charts",children:"Charts"}),e.jsxs(Xt,{value:"map",children:[e.jsx(ja,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(as,{value:"transactions",children:e.jsx(uAe,{transactions:v||[],showCommission:S,isLoading:j})}),e.jsx(as,{value:"charts",children:e.jsx(hAe,{stats:b,year:s})}),e.jsx(as,{value:"map",children:e.jsx(mAe,{transactions:v||[],isLoading:j})})]})]})]})]}),e.jsx(Zmt,{open:r,onOpenChange:n}),e.jsx(dEs,{open:a,onOpenChange:i}),e.jsx(hEs,{open:l,onOpenChange:o,year:s,existingGoals:T})]})}function nft({open:s,onOpenChange:t,listingId:r,listingSlug:n,listingTitle:a}){const{user:i}=As(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(!1);k.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:b,error:N}=await H.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",r).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(N)throw N;if(b&&b.share_token)o(b);else if(b&&!b.share_token){const{data:S,error:T}=await H.from("listing_shares").update({share_type:"referral_link"}).eq("id",b.id).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(S)}else{const{data:S,error:T}=await H.from("listing_shares").insert({listing_id:r,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(S)}}catch(b){console.error("Error creating share link:",b),ue.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,r]);const x=l!=null&&l.share_token?`https://listings.relevelup.com/${n||r}?ref=${l.share_token}`:"",g=async()=>{try{await navigator.clipboard.writeText(x),m(!0),ue.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{ue.error("Failed to copy link")}},v=j=>{const b=encodeURIComponent(x),N=encodeURIComponent(`Check out this listing: ${a}`);switch(j){case"email":window.open(`mailto:?subject=${N}&body=${b}`);break;case"text":window.open(`sms:?body=${N}%20${b}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${b}`,"_blank");break}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Fr,{children:"Share this listing with your network. When someone submits a lead through your link, they'll become your contact!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:[e.jsx("strong",{children:"How it works:"})," The listing still shows the original agent's info, but any leads from your unique link go directly to you!"]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:c?"Generating...":x,readOnly:!0,className:"font-mono text-sm"}),e.jsx(G,{onClick:g,disabled:c||!x,variant:h?"default":"outline",children:h?e.jsx(Hn,{className:"h-4 w-4"}):e.jsx(Ra,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("email"),disabled:c,children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("text"),disabled:c,children:[e.jsx(bi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("facebook"),disabled:c,children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),l&&(l.click_count>0||l.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(he,{className:"mb-2 block",children:"Your Share Performance"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-muted rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground mb-1",children:[e.jsx(jn,{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(fr,{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 yEs={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},vEs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},bEs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function YU({listing:s,onClick:t,onEdit:r,onDelete:n,showActions:a}){var j,b;const{user:i}=As(),{data:l}=tat(s.id),o=eat(),[c,d]=k.useState(!1),h=N=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(N),m=((j=s.photos)==null?void 0:j.find(N=>N.is_primary))||((b=s.photos)==null?void 0:b[0]),x=(i==null?void 0:i.id)===s.agent_id,g=async N=>{N.stopPropagation();try{const S=await o.mutateAsync(s.id);ue.success(S.saved?"Listing saved!":"Listing removed from saved")}catch{ue.error("Failed to save listing")}},v=N=>{if(N.stopPropagation(),i)d(!0);else{const S=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(S),ue.success("Link copied to clipboard!")}};return e.jsxs(Ne,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[m?e.jsx("img",{src:m.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx($g,{className:"h-12 w-12"})}),e.jsx(Ge,{className:`absolute top-2 left-2 ${yEs[s.status]} text-white border-0`,children:vEs[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(Qn,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(G,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,children:e.jsx(hi,{className:`h-4 w-4 ${l?"fill-pink-500 text-pink-500":""}`})}),e.jsx(G,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:v,title:x?"Copy link":"Share & earn leads",children:x?e.jsx(Pc,{className:"h-4 w-4"}):e.jsx(jr,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(nft,{open:c,onOpenChange:d,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:h(s.price)}),s.open_to_referrals&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:[e.jsx(fr,{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(ja,{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(e0,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fp,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($g,{className:"h-4 w-4"}),s.square_footage.toLocaleString()," sqft"]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs",children:bEs[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(jn,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pc,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(hi,{className:"h-3 w-3"}),s.save_count]})]}),a&&(r||n)&&e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsxs(G,{variant:"outline",size:"sm",className:"flex-1",onClick:N=>{N.stopPropagation(),r()},children:[e.jsx(nd,{className:"h-4 w-4 mr-2"}),"Edit"]}),n&&e.jsx(G,{variant:"destructive",size:"sm",onClick:N=>{N.stopPropagation(),n()},children:e.jsx(yr,{className:"h-4 w-4"})})]})]})]})}const _Es=[{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"}],wEs=[{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 jEs({filters:s,onFiltersChange:t,onClose:r}){const n=()=>{t({sortBy:"newest"})};return e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(zt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:n,children:"Clear All"}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(_r,{className:"h-4 w-4"})})]})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Status"}),e.jsxs(zs,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"All statuses"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Statuses"}),_Es.map(a=>e.jsx(mt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Type"}),e.jsxs(zs,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"All types"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),wEs.map(a=>e.jsx(mt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Min Price"}),e.jsx(ke,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Max Price"}),e.jsx(ke,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(br,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function NEs({leaderboard:s}){const t=n=>{switch(n){case 0:return e.jsx(Zi,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(s_,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Xl,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:n+1})}},r=(n,a)=>!n||n.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:n.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(Ge,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(De,{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(Pc,{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(Cn,{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(s_,{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(Zi,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Community Leaderboard"})}),e.jsx(De,{children:e.jsxs(Rn,{defaultValue:"sharers",children:[e.jsxs(Dn,{className:"w-full",children:[e.jsxs(Xt,{value:"sharers",className:"flex-1",children:[e.jsx(Pc,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Xt,{value:"listers",className:"flex-1",children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(as,{value:"sharers",className:"mt-4",children:r(s==null?void 0:s.topSharers,"shares")}),e.jsx(as,{value:"listers",className:"mt-4",children:r(s==null?void 0:s.topListers,"listings")})]})})]})]})}const Aqe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},Mqe={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 kEs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function SEs({listings:s,isLoading:t}){const r=vr(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),{isAdmin:l}=As(),[o,c]=k.useState(""),[d,h]=k.useState(!0),[m,x]=k.useState(!1),g=s.filter(j=>j.latitude!=null&&j.longitude!=null),v=s.filter(j=>(j.latitude==null||j.longitude==null)&&(j.property_address||j.city));return k.useEffect(()=>{(async()=>{h(!0);try{const{data:b}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}h(!1)})()},[]),k.useEffect(()=>{if(!o||v.length===0||m)return;(async()=>{var b;x(!0);for(const N of v){const S=[N.property_address,N.city,N.state].filter(Boolean).join(", ");if(S)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(S)}.json?access_token=${o}&limit=1`)).json();if((b=A.features)!=null&&b[0]){const[P,D]=A.features[0].center;await H.from("listings").update({latitude:D,longitude:P}).eq("id",N.id),N.latitude=D,N.longitude=P}}catch(T){console.error("Geocode error:",T)}}x(!1)})()},[o,s]),k.useEffect(()=>{if(!n.current||!o||a.current)return;El.accessToken=o;const j=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],N=4;if(j.length>0){const S=j.reduce((A,P)=>A+P.longitude,0)/j.length,T=j.reduce((A,P)=>A+P.latitude,0)/j.length;b=[S,T],N=j.length===1?12:10}return a.current=new El.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:N,center:b}),a.current.addControl(new El.NavigationControl,"top-right"),()=>{var S;(S=a.current)==null||S.remove(),a.current=null}},[o]),k.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(b=>b.remove()),i.current=[];const j=s.filter(b=>b.latitude!=null&&b.longitude!=null);if(j.forEach(b=>{var D,B,z;const N=Aqe[b.status]||"#10B981",S=((D=b.photos)==null?void 0:D.find(F=>F.is_primary))||((B=b.photos)==null?void 0:B[0]),T=document.createElement("div");T.className="cursor-pointer",T.innerHTML=`
`;const A=new El.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${S!=null&&S.photo_url?``:""}
${kEs(b.price)}
${b.property_address||""}
${b.city}, ${b.state}
${Mqe[b.status]||b.status} ${b.bedrooms?`${b.bedrooms} bed`:""} ${b.bathrooms?`${b.bathrooms} bath`:""}
${(z=b.agent)!=null&&z.name?`
Listed by ${b.agent.name}
`:""}
Click to view details →
`),P=new El.Marker(T).setLngLat([b.longitude,b.latitude]).setPopup(A).addTo(a.current);i.current.push(P)}),j.length>1){const b=new El.LngLatBounds;j.forEach(N=>b.extend([N.longitude,N.latitude])),a.current.fitBounds(b,{padding:60,maxZoom:13})}else j.length===1&&a.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,m]),k.useEffect(()=>(window.__navigateToListing__=j=>{r(`/mission-control/listings/${j}`)},()=>{delete window.__navigateToListing__}),[r]),d||t?e.jsx(Ne,{children:e.jsx(De,{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(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ja,{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(Aqe).map(([j,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:Mqe[j]})]},j)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[g.length," of ",s.length," mapped",m&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Hi,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}function CEs(){var F,$,X,K,Q,Y,ne,de;const s=vr(),{brokerageId:t}=As(),{data:r,isLoading:n}=Ynt(),[a,i]=k.useState("feed"),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState({sortBy:"newest"}),{data:x,isLoading:g}=Znt({...h,city:c||h.city}),{data:v,isLoading:j}=eUt(),{data:b,isLoading:N}=Xnt(),{data:S,isLoading:T}=nUt(),{data:A,isLoading:P}=oUt(),{data:D}=iUt(),B=Jnt(),z=async ce=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await B.mutateAsync(ce),ue.success("Listing deleted successfully")}catch{ue.error("Failed to delete listing")}};return n?e.jsx(_s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):r?e.jsx(_s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ws,{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(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Cn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(x==null?void 0:x.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(hi,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(_3,{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(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(fr,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((F=S==null?void 0:S.sent)==null?void 0:F.length)||0)+((($=S==null?void 0:S.received)==null?void 0:$.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(Rn,{value:a,onValueChange:i,children:[e.jsxs(Dn,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Xt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Xt,{value:"brokerage",children:"Brokerage"}),e.jsx(Xt,{value:"my-listings",children:"My Listings"}),e.jsx(Xt,{value:"saved",children:"Saved"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"map",children:"Map"}),e.jsx(Xt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(as,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by city or neighborhood...",value:c,onChange:ce=>d(ce.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:h.sortBy,onValueChange:ce=>m({...h,sortBy:ce}),children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"Sort by"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"newest",children:"Newest First"}),e.jsx(mt,{value:"updated",children:"Recently Updated"}),e.jsx(mt,{value:"price_asc",children:"Price: Low to High"}),e.jsx(mt,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(G,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(s0,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(jEs,{filters:h,onFiltersChange:m,onClose:()=>o(!1)}),g?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ce,ae)=>e.jsxs(Ne,{children:[e.jsx(Vs,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(Vs,{className:"h-5 w-3/4"}),e.jsx(Vs,{className:"h-4 w-1/2"}),e.jsx(Vs,{className:"h-4 w-1/4"})]})]},ae))}):(x==null?void 0:x.length)===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Cn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:x==null?void 0:x.map(ce=>e.jsx(YU,{listing:ce,onClick:()=>s(`/mission-control/listings/${ce.id}`)},ce.id))})]}),e.jsx(as,{value:"my-listings",className:"space-y-4",children:N?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ae)=>e.jsxs(Ne,{children:[e.jsx(Vs,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(Vs,{className:"h-5 w-3/4"}),e.jsx(Vs,{className:"h-4 w-1/2"})]})]},ae))}):(b==null?void 0:b.length)===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(_3,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ws,{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(ce=>e.jsx(YU,{listing:ce,showActions:!0,onClick:()=>s(`/mission-control/listings/${ce.id}`),onEdit:()=>s(`/mission-control/listings/${ce.id}/edit`),onDelete:()=>z(ce.id)},ce.id))})}),e.jsx(as,{value:"saved",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((ce,ae)=>e.jsxs(Ne,{children:[e.jsx(Vs,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(Vs,{className:"h-5 w-3/4"}),e.jsx(Vs,{className:"h-4 w-1/2"})]})]},ae))}):(v==null?void 0:v.length)===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(hi,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v==null?void 0:v.map(ce=>e.jsx(YU,{listing:ce.listing,onClick:()=>s(`/mission-control/listings/${ce.listing.id}`)},ce.id))})}),e.jsx(as,{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(Pc,{className:"h-4 w-4"}),"Referrals Sent (",((X=S==null?void 0:S.sent)==null?void 0:X.length)||0,")"]}),((K=S==null?void 0:S.sent)==null?void 0:K.length)===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(Q=S==null?void 0:S.sent)==null?void 0:Q.map(ce=>{var ae,ie;return e.jsx(Ne,{children:e.jsx(De,{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:ce.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ae=ce.listing)==null?void 0:ae.property_address)||((ie=ce.listing)==null?void 0:ie.city)})]}),e.jsx(Ge,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]})})},ce.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Referrals Received (",((Y=S==null?void 0:S.received)==null?void 0:Y.length)||0,")"]}),((ne=S==null?void 0:S.received)==null?void 0:ne.length)===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(de=S==null?void 0:S.received)==null?void 0:de.map(ce=>{var ae;return e.jsx(Ne,{children:e.jsxs(De,{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:ce.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ae=ce.sender)==null?void 0:ae.name]})]}),e.jsx(Ge,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]}),e.jsx(G,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ce.listing_id}`),children:"View Listing"})]})},ce.id)})})]})]})}),t&&e.jsx(as,{value:"brokerage",className:"space-y-4",children:P?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ae)=>e.jsxs(Ne,{children:[e.jsx(Vs,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(Vs,{className:"h-5 w-3/4"}),e.jsx(Vs,{className:"h-4 w-1/2"})]})]},ae))}):(A==null?void 0:A.length)===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(_3,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ws,{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(ce=>e.jsx(YU,{listing:ce,onClick:()=>s(`/mission-control/listings/${ce.id}`)},ce.id))})}),e.jsx(as,{value:"map",children:e.jsx(SEs,{listings:x||[],isLoading:g})}),e.jsx(as,{value:"leaderboard",children:e.jsx(NEs,{leaderboard:D})})]})]})}):e.jsx(_s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Cn,{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 aft(s){return gt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:r}=await H.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 TEs(){const{user:s}=As(),t=es();return Lt({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 H.storage.from("listing-documents").upload(i,n,{contentType:n.type||void 0});if(l)throw l;const{data:o,error:c}=await H.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 EEs(){const s=es();return Lt({mutationFn:async({id:t,storage_path:r,listingId:n})=>{await H.storage.from("listing-documents").remove([r]);const{error:a}=await H.from("listing_documents").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function AEs(){const s=es();return Lt({mutationFn:async({id:t,visible:r,listingId:n})=>{const{error:a}=await H.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 ift(s){const{data:t,error:r}=await H.storage.from("listing-documents").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const MEs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function IEs({listingId:s,ownerOnly:t=!1}){const{data:r=[]}=aft(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 ift(i);window.open(l,"_blank")}catch{ue.error("Failed to open document")}};return e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Documents & Disclosures (",n.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:n.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(ln,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:i.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:MEs(i.file_size)})]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function PEs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const LEs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function DEs({open:s,onOpenChange:t,listing:r}){const{user:n}=As(),{data:a=[],isLoading:i}=$m(),{data:l=[]}=qx(),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[g,v]=k.useState(!1),[j,b]=k.useState(null);k.useEffect(()=>{s||(c(""),h("all"),x(new Set),v(!1))},[s]),k.useEffect(()=>{!s||!n||(async()=>{const{data:z}=await H.from("gmail_integrations").select("gmail_email").eq("user_id",n.id).maybeSingle();b((z==null?void 0:z.gmail_email)||null)})()},[s,n]);const N=k.useMemo(()=>a.filter(z=>z.email),[a]),S=k.useMemo(()=>{let z=N;if(d!=="all"&&(z=z.filter(F=>{var $;return($=F.tags)==null?void 0:$.some(X=>X.relationship_type_id===d)})),o.trim()){const F=o.toLowerCase();z=z.filter($=>`${$.first_name||""} ${$.last_name||""}`.toLowerCase().includes(F)||($.email||"").toLowerCase().includes(F))}return z},[N,o,d]),T=()=>{m.size===S.length?x(new Set):x(new Set(S.map(z=>z.id)))},A=z=>{const F=new Set(m);F.has(z)?F.delete(z):F.add(z),x(F)},P=k.useMemo(()=>N.filter(z=>m.has(z.id)).map(z=>({id:z.id,first_name:z.first_name||"there",last_name:z.last_name,email:z.email})),[N,m]),{defaultSubject:D,defaultBody:B}=k.useMemo(()=>{var oe,ge,be,Oe;const z=r.property_address||`${r.city}, ${r.state}`,F=PEs(r.price),$=LEs[r.property_type]||"home",X=r.bedrooms?`${r.bedrooms} bed`:"",K=r.bathrooms?`${r.bathrooms} bath`:"",Q=r.square_footage?`${r.square_footage.toLocaleString()} sqft`:"",Y=[X,K,Q].filter(Boolean).join(" • "),ne=`https://listings.relevelup.com/${r.slug||r.id}`,de=((ge=(oe=r.photos)==null?void 0:oe.find(Me=>Me.is_primary))==null?void 0:ge.photo_url)||((Oe=(be=r.photos)==null?void 0:be[0])==null?void 0:Oe.photo_url)||"",ae={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[r.status]||"New Listing",ie=`${ae}: ${z} — ${F}`,me=`

Hi {{first_name}},

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

${de?` ${z} `:""}
${ae}

${F}

${z}

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

${Y?`

${Y} • ${$}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ie,defaultBody:me}},[r]);return g?e.jsx(j1,{open:g,onOpenChange:z=>{v(z),z||t(!1)},bulkContacts:P,defaultSubject:D,defaultBody:B,gmailEmail:j}):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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Fr,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search contacts...",value:o,onChange:z=>c(z.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:d,onValueChange:h,children:[e.jsx(Os,{className:"sm:w-[180px]",children:e.jsx(Us,{placeholder:"Filter by tag"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All contacts"}),l.map(z=>e.jsx(mt,{value:z.id,children:z.name},z.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:T,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Ei,{checked:S.length>0&&m.size===S.length,className:"pointer-events-none"}),e.jsx("span",{children:m.size===S.length&&S.length>0?"Deselect all":`Select all (${S.length})`})]}),e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fr,{className:"h-3 w-3"}),m.size," selected"]})]}),e.jsx(ti,{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..."]}):S.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:N.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:S.map(z=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(Ei,{checked:m.has(z.id),onCheckedChange:()=>A(z.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[z.first_name," ",z.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.email})]}),z.tags&&z.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:z.tags.slice(0,2).map(F=>{var $;return e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:($=F.relationship_type)==null?void 0:$.name},F.id)})})]},z.id))})}),e.jsx(po,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:j?`Sending from ${j}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>v(!0),disabled:m.size===0,className:"gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"}),"Compose Email (",m.size,")"]})]})]})]})})}function Pg(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 Mge(){const s=na();return gt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function oft(){const s=na(),t=es();return Lt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:r}=await H.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function Ige(){const s=na();return gt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 lft(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 H.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 cft(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 REs(){const s=es();return Lt({mutationFn:async({dealId:t,stageId:r,stageName:n})=>{const{data:a,error:i}=await H.from("deal_pipeline").update({stage_id:r}).eq("id",t).select().single();if(i)throw i;return await H.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function OEs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 FEs(s){return gt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:r}=await H.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function BEs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 zEs(s){return gt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:r}=await H.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function $Es(){const s=es();return Lt({mutationFn:async({id:t,is_completed:r,deal_id:n})=>{const{data:a,error:i}=await H.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 UEs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 qEs(){const s=na();return gt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(r)throw r;const n=(t==null?void 0:t.filter(o=>{var c,d,h;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((h=o.deal_pipeline_stages)==null?void 0:h.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:n.length,wonDeals:a.length,pipelineValue:n.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:n.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:n.reduce((o,c)=>o+(Pg(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+(Pg(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Pg(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Pg(c)||0),0)+n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Pg(c)||0)*d},0)}},enabled:!!s})}function VEs(s){const t=na();return gt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:r,error:n}=await H.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 HEs(){const s=es();return Lt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await H.from("deal_pipeline").update({listing_id:r}).eq("id",t).select().single();if(a)throw a;return await H.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 GEs(){const s=es();return Lt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await H.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 WEs({listing:s}){const t=vr(),[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l,isLoading:o}=VEs(s.id),{data:c,isLoading:d}=Mge(),{data:h,isLoading:m}=Ige(),x=oft(),g=HEs(),v=GEs(),j=lft(),b=(h==null?void 0:h.filter(P=>!P.listing_id))||[],N=P=>{if(!(c!=null&&c.length))return null;switch(P){case"coming_soon":case"active":case"price_improvement":return c.find(D=>D.name==="Active");case"under_contract":return c.find(D=>D.name==="Under Contract");case"sold":return c.find(D=>D.is_won_stage);default:return c.find(D=>D.name==="Active")}},S=async()=>{i(!0);try{c!=null&&c.length||await x.mutateAsync();const P=N(s.status);await j.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(P==null?void 0:P.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),ue.success("Deal created and linked to listing!")}catch(P){console.error("Failed to create deal:",P),ue.error("Failed to create deal")}finally{i(!1)}},T=async()=>{if(!r){ue.error("Please select a deal");return}try{await g.mutateAsync({dealId:r,listingId:s.id}),ue.success("Listing linked to deal!"),n("")}catch{ue.error("Failed to link listing")}},A=async()=>{if(l)try{await v.mutateAsync({dealId:l.id,listingId:s.id}),ue.success("Listing unlinked from deal")}catch{ue.error("Failed to unlink listing")}};return o||d?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Uv,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(De,{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(Ne,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(rl,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx(Ge,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(Ga,{className:"h-3 w-3 ml-1"})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:A,disabled:v.isPending,children:v.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(W3,{className:"h-4 w-4"})})]})]})]}):e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(zt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Uv,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(G,{onClick:S,disabled:a||j.isPending,className:"w-full",size:"sm",children:[a||j.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ws,{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(zs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"flex-1 text-sm",children:e.jsx(Us,{placeholder:"Link to existing deal..."})}),e.jsx(Fs,{children:b.map(P=>e.jsx(mt,{value:P.id,children:P.deal_name},P.id))})]}),e.jsx(G,{variant:"secondary",size:"icon",onClick:T,disabled:!r||g.isPending,children:g.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(rl,{className:"h-4 w-4"})})]})]})]})]})}const KEs={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"},YEs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Iqe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function ZEs(){var ne,de,ce,ae,ie,me,oe,ge,be;const{listingId:s}=Xi(),t=vr(),{user:r}=As(),{data:n,isLoading:a}=Qnt(s||""),{data:i}=tat(s||""),{data:l}=sUt(s||""),o=eat(),c=tUt(),d=rUt(),h=Jnt(),m=aUt(),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(!1),[A,P]=k.useState(null),[D,B]=k.useState({buyerName:"",buyerType:"",notes:""}),z=(r==null?void 0:r.id)===(n==null?void 0:n.agent_id),F=Oe=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Oe),$=async Oe=>{const Me=`https://listings.relevelup.com/${(n==null?void 0:n.slug)||(n==null?void 0:n.id)}`,Pe=`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(Me)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Me),ue.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Pe} ${Me}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Pe)}&body=${encodeURIComponent(`Check out this listing: ${Me}`)}`);break}}catch(Ee){console.error("Share error:",Ee),ue.error("Failed to share")}},X=async()=>{try{await h.mutateAsync(n.id),ue.success("Listing deleted"),t("/mission-control/listings")}catch{ue.error("Failed to delete listing")}},K=async()=>{if(!D.buyerName.trim()){ue.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:n.id,listingAgentId:n.agent_id,buyerName:D.buyerName,buyerType:D.buyerType||void 0,notes:D.notes||void 0}),ue.success("Referral sent successfully!"),j(!1),B({buyerName:"",buyerType:"",notes:""})}catch{ue.error("Failed to send referral")}},Q=Oe=>{var Te,ye;const Me=(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`,Pe=F((n==null?void 0:n.price)||0),Ee=n!=null&&n.bedrooms?`${n.bedrooms}BD`:"",$e=n!=null&&n.bathrooms?`${n.bathrooms}BA`:"",Se=n!=null&&n.square_footage?`${n.square_footage.toLocaleString()}SF`:"",ze=[Ee,$e,Se].filter(Boolean).join(" | ");switch(Oe){case"just_listed":return`🏡 JUST LISTED! ${Me} ${Pe} ${ze} ${(n==null?void 0:n.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Te=n==null?void 0:n.city)==null?void 0:Te.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Me} Now ${Pe}! ${ze} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${Iqe[(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! ${ze} DM me for details! 📩 #ComingSoon #RealEstate #${(ye=n==null?void 0:n.city)==null?void 0:ye.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(_s,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-10 w-32"}),e.jsx(Vs,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Vs,{className:"h-48"}),e.jsx(Vs,{className:"h-48"}),e.jsx(Vs,{className:"h-48"})]})]})});if(!n)return e.jsx(_s,{title:"Listing Not Found",description:"",children:e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(G,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const Y=((ne=n.photos)==null?void 0:ne.find(Oe=>Oe.is_primary))||((de=n.photos)==null?void 0:de[0]);return e.jsxs(_s,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(wa,{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:()=>Y&&P(Y.photo_url),children:Y?e.jsx("img",{src:Y.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ce=n.photos)==null?void 0:ce.slice(1,5).map((Oe,Me)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>P(Oe.photo_url),children:e.jsx("img",{src:Oe.photo_url,alt:`Photo ${Me+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(Ne,{children:e.jsxs(De,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ge,{className:`${KEs[n.status]} text-white border-0`,children:YEs[n.status]}),n.is_featured&&e.jsxs(Ge,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),n.open_to_referrals&&e.jsxs(Ge,{variant:"outline",children:[e.jsx(fr,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:F(n.price)}),n.property_address&&e.jsx("p",{className:"text-xl font-medium",children:n.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ja,{className:"h-4 w-4"}),n.city,", ",n.state,n.neighborhood&&` • ${n.neighborhood}`]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>o.mutate(n.id),children:e.jsx(hi,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>c.mutate(n.id),children:l?e.jsx(Fv,{className:"h-4 w-4"}):e.jsx(Rm,{className:"h-4 w-4"})}),!z&&e.jsxs(G,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>N(!0),children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx(Pc,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Vd,{children:[e.jsxs(Da,{onClick:()=>$("copy"),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Da,{onClick:()=>$("facebook"),children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Da,{onClick:()=>$("text"),children:[e.jsx(bi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Da,{onClick:()=>$("email"),children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",onClick:()=>T(!0),className:"gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(G,{variant:"outline",onClick:()=>t(`/mission-control/listings/${n.id}/edit`),children:[e.jsx(nd,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(G,{variant:"destructive",size:"icon",onClick:()=>g(!0),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[n.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(e0,{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(fp,{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($g,{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(rn,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),Iqe[n.property_type]]}),n.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",n.lot_size]}),n.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),n.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})]}),n.agent_notes&&n.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.agent_notes})]}),n.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:n.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{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(jn,{className:"h-4 w-4"}),n.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pc,{className:"h-4 w-4"}),n.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(hi,{className:"h-4 w-4"}),n.save_count," saves"]})]})]})}),n.allow_sharing&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Share Content"})}),e.jsx(De,{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(G,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(Q(Oe)),ue.success("Caption copied!")},children:e.jsx(Ra,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:Q(Oe)})]},Oe))})]}),e.jsx(IEs,{listingId:n.id,ownerOnly:z})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(De,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((ie=(ae=n.agent)==null?void 0:ae.name)==null?void 0:ie.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((me=n.agent)==null?void 0:me.name)||"Unknown"}),((ge=(oe=n.agent)==null?void 0:oe.brokerage)==null?void 0:ge.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n.agent.brokerage.name})]})]}),!z&&e.jsx("div",{className:"space-y-2",children:((be=n.agent)==null?void 0:be.email)&&e.jsx(G,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${n.agent.email}`,children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),z&&e.jsx(WEs,{listing:n}),!z&&n.open_to_referrals&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx(G,{className:"w-full",onClick:()=>j(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(vs,{open:!!A,onOpenChange:()=>P(null),children:e.jsx(ys,{className:"max-w-4xl",children:e.jsx("img",{src:A||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(vs,{open:x,onOpenChange:g,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Delete Listing"}),e.jsx(Fr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:X,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(vs,{open:v,onOpenChange:j,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Send Buyer Referral"}),e.jsx(Fr,{children:"Submit buyer information to the listing agent"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Buyer Name *"}),e.jsx(ke,{value:D.buyerName,onChange:Oe=>B({...D,buyerName:Oe.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Buyer Type"}),e.jsxs(zs,{value:D.buyerType,onValueChange:Oe=>B({...D,buyerType:Oe}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"first_time",children:"First-Time Buyer"}),e.jsx(mt,{value:"investor",children:"Investor"}),e.jsx(mt,{value:"relocating",children:"Relocating"}),e.jsx(mt,{value:"upgrade",children:"Upgrading"}),e.jsx(mt,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes"}),e.jsx(ur,{value:D.notes,onChange:Oe=>B({...D,notes:Oe.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(nft,{open:b,onOpenChange:N,listingId:(n==null?void 0:n.id)||"",listingSlug:(n==null?void 0:n.slug)||null,listingTitle:(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`}),n&&e.jsx(DEs,{open:S,onOpenChange:T,listing:n})]})}function XEs({onImport:s}){const[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),m=k.useRef(),x=k.useRef(null);k.useEffect(()=>{const S=T=>{x.current&&!x.current.contains(T.target)&&c(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const g=async S=>{if(S.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:T,error:A}=await H.functions.invoke("mls-listing-search",{body:{query:S}});if(A)throw A;a((T==null?void 0:T.listings)||[]),c(!0)}catch(T){console.error("MLS search error:",T),a([])}finally{l(!1)}},v=S=>{r(S),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(S),400)},j=S=>{h(S.mlsNumber),s(S),c(!1),r(`${S.address}, ${S.city}`),ue.success(`Imported: ${S.address}`,{description:"Property details and photos have been auto-filled."}),h(null)},b=S=>S?`$${S.toLocaleString()}`:"",N=S=>{const T=(S||"").toLowerCase();return T.includes("single")||T.includes("detached")?"Single Family":T.includes("condo")?"Condo":T.includes("town")?"Townhouse":T.includes("land")||T.includes("lot")?"Land":T.includes("multi")?"Multi-Family":T.includes("commercial")?"Commercial":S||"Other"};return e.jsxs(Ne,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xa,{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(De,{children:e.jsxs("div",{ref:x,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:t,onChange:S=>v(S.target.value),onFocus:()=>n.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(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(S=>e.jsxs("button",{type:"button",onClick:()=>j(S),disabled:d===S.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[S.photos[0]?e.jsx("img",{src:S.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(ja,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:S.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[S.city,", ",S.state," ",S.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:b(S.price)}),S.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(e0,{className:"h-3 w-3"})," ",S.bedrooms]}),S.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(fp,{className:"h-3 w-3"})," ",S.bathrooms]}),S.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(U3,{className:"h-3 w-3"})," ",S.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:N(S.propertyType)}),S.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[S.photos.length," photos"]})]})]},S.mlsNumber))})]})})]})}function QEs({photo:s,onRemove:t,onSetPrimary:r}){const{attributes:n,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=Pxe({id:s.id}),d={transform:A2.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Bt("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(Su,{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(Qn,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>r(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function JEs({photos:s,uploading:t,onUpload:r,onRemove:n,onReorder:a,onSetPrimary:i}){const l=Nxe(CI(zP,{activationConstraint:{distance:5}})),o=[...s].sort((d,h)=>(d.sort_order??0)-(h.sort_order??0)),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const x=o.findIndex(N=>N.id===h.id),g=o.findIndex(N=>N.id===m.id),v=[...o],[j]=v.splice(x,1);v.splice(g,0,j);const b=v.map((N,S)=>({...N,sort_order:S}));a(b)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(Axe,{sensors:l,collisionDetection:kxe,onDragEnd:c,children:e.jsx(Ixe,{items:o.map(d=>d.id),strategy:yz,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(QEs,{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(oa,{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 eAs({selectedVideoId:s,onVideoSelect:t,listingId:r}){const n=vr(),{user:a}=As(),[i,l]=k.useState(!1),[o,c]=k.useState([]),[d,h]=k.useState(!1),[m,x]=k.useState(null),[g,v]=k.useState({});k.useEffect(()=>{s&&a?j():x(null)},[s,a]);const j=async()=>{if(!s)return;const{data:F,error:$}=await H.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();!$&&F&&(x(F),b(F))},b=async F=>{try{const{data:$,error:X}=await H.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:F.bunny_video_id,isAgentVideo:!0}});!X&&($!=null&&$.thumbnailUrl)&&v(K=>({...K,[F.id]:{thumbnailUrl:$.thumbnailUrl}}))}catch($){console.warn("Failed to get signed URL",$)}},N=async()=>{if(a){h(!0);try{const{data:F,error:$}=await H.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($)throw $;c(F||[]),F!=null&&F.length&&S(F)}catch(F){console.error("Error fetching videos:",F),ue.error("Failed to load videos")}finally{h(!1)}}},S=async F=>{var $;try{const X=F.map(de=>de.bunny_video_id),{data:K,error:Q}=await H.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:X,isAgentVideo:!0}});if(Q)throw Q;const Y=(K==null?void 0:K.assets)||{},ne={};for(const de of F)($=Y[de.bunny_video_id])!=null&&$.thumbnailUrl&&(ne[de.id]={thumbnailUrl:Y[de.bunny_video_id].thumbnailUrl});v(de=>({...de,...ne}))}catch(X){console.warn("Failed to bulk-fetch signed URLs",X)}},T=()=>{l(!0),N()},A=F=>{t(F.id),x(F),l(!1),ue.success("Video selected")},P=()=>{t(null),x(null)},D=()=>{const F=r?`/mission-control/listings/${r}/edit`:"/mission-control/listings/new";n(`/mission-control/video?returnUrl=${encodeURIComponent(F)}`)},B=F=>{if(!F)return"0:00";const $=Math.floor(F/60),X=F%60;return`${$}:${X.toString().padStart(2,"0")}`},z=F=>{var $;return(($=g[F.id])==null?void 0:$.thumbnailUrl)||F.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[m?e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(De,{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:[z(m)?e.jsx("img",{src:z(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(sn,{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(Ho,{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:B(m.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:T,children:"Change"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:P,className:"text-destructive hover:text-destructive",children:e.jsx(_r,{className:"h-4 w-4"})})]})]})})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(sn,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs(G,{type:"button",variant:"outline",onClick:T,className:"gap-2",children:[e.jsx(I3,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(G,{type:"button",variant:"outline",onClick:D,className:"gap-2",children:[e.jsx(pp,{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(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(I3,{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(sn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs(G,{onClick:D,className:"gap-2",children:[e.jsx(pp,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(F=>e.jsxs("button",{type:"button",onClick:()=>A(F),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===F.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[z(F)?e.jsx("img",{src:z(F),alt:F.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sn,{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(Ho,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),F.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:B(F.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:F.title||"Untitled Video"})})]},F.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(G,{type:"button",variant:"ghost",onClick:D,className:"gap-2",children:[e.jsx(pp,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const tAs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function sAs({listingId:s}){const t=k.useRef(null),{data:r=[],isLoading:n}=aft(s),a=TEs(),i=EEs(),l=AEs(),o=async d=>{if(!(!d||d.length===0)){for(const h of Array.from(d)){if(h.size>25*1024*1024){ue.error(`${h.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:h})}catch(m){ue.error(`Failed to upload ${h.name}: ${m.message}`)}}t.current&&(t.current.value=""),ue.success("Documents uploaded")}},c=async d=>{try{const h=await ift(d);window.open(h,"_blank")}catch{ue.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(G,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oa,{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(Ne,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ln,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:d.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:tAs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(jn,{className:"h-3 w-3"}):e.jsx(am,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(br,{checked:d.visible_on_exchange,onCheckedChange:h=>l.mutate({id:d.id,visible:h,listingId:s}),className:"ml-1"})]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(Xa,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(_r,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const rAs=[{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"}],nAs=[{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 aAs({id:s,url:t,index:r,onRemove:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Pxe({id:s}),h={transform:A2.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:h,className:`relative aspect-square rounded-lg overflow-hidden bg-muted group ${d?"opacity-50 ring-2 ring-primary z-50":""}`,children:[e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...a,...i,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Su,{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(Qn,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function iAs({photoUrls:s,pendingPhotos:t,onRemove:r,onReorder:n,uploading:a,onUpload:i}){const l=Nxe(CI(zP,{activationConstraint:{distance:5}})),o=s.map((d,h)=>`pending-${h}`),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const x=o.indexOf(h.id),g=o.indexOf(m.id),v=[...s],j=[...t],[b]=v.splice(x,1),[N]=j.splice(x,1);v.splice(g,0,b),j.splice(g,0,N),n(v,j)};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(Axe,{sensors:l,collisionDetection:kxe,onDragEnd:c,children:e.jsx(Ixe,{items:o,strategy:yz,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,h)=>e.jsx(aAs,{id:o[h],url:d,index:h,onRemove:r},o[h])),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[a?e.jsx(ls,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{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 Pqe(){const{listingId:s}=Xi(),[t]=Lc(),r=t.get("brokerage"),n=vr(),{user:a}=As(),{hasLeadSite:i}=ey(),l=!!s&&s!=="new",o=!!r&&!l,[c,d]=k.useState([]),{data:h,isLoading:m}=Qnt(l?s:""),x=W$t(),g=K$t(),v=Y$t(),j=Z$t(),b=X$t(),N=Q$t(),S=J$t(),{data:T=[]}=gt({queryKey:["brokerage-agents",r],queryFn:async()=>{if(!r)return[];const{data:oe,error:ge}=await H.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name");if(ge)throw ge;return oe||[]},enabled:o}),[A,P]=k.useState(""),[D,B]=k.useState(!1),[z,F]=k.useState([]),[$,X]=k.useState([]),[K,Q]=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 oe,ge,be,Oe,Me;h&&l&&Q({property_address:h.property_address||"",city:h.city||"",state:h.state||"",neighborhood:h.neighborhood||"",price:((oe=h.price)==null?void 0:oe.toString())||"",property_type:h.property_type,status:h.status,bedrooms:((ge=h.bedrooms)==null?void 0:ge.toString())||"",bathrooms:((be=h.bathrooms)==null?void 0:be.toString())||"",square_footage:((Oe=h.square_footage)==null?void 0:Oe.toString())||"",lot_size:h.lot_size||"",year_built:((Me=h.year_built)==null?void 0:Me.toString())||"",has_hoa:h.has_hoa,description:h.description||"",agent_notes:h.agent_notes||"",agent_notes_public:h.agent_notes_public,mls_link:h.mls_link||"",video_link:h.video_link||"",video_id:h.video_id||null,allow_sharing:h.allow_sharing,open_to_referrals:h.open_to_referrals,open_to_social_promotion:h.open_to_social_promotion,share_with_brokerage:h.share_with_brokerage??!1,is_public:h.is_public})},[h,l]);const Y=oe=>{var Me,Pe;const ge={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},be=(oe.propertyType||"").toLowerCase(),Oe=((Me=Object.entries(ge).find(([Ee])=>be.includes(Ee)))==null?void 0:Me[1])||"other";Q(Ee=>({...Ee,property_address:oe.address||Ee.property_address,city:oe.city||Ee.city,state:oe.state||Ee.state,price:oe.price?String(oe.price):Ee.price,property_type:Oe,bedrooms:oe.bedrooms?String(oe.bedrooms):Ee.bedrooms,bathrooms:oe.bathrooms?String(oe.bathrooms):Ee.bathrooms,square_footage:oe.sqft?String(oe.sqft):Ee.square_footage,lot_size:oe.lotSize?String(oe.lotSize):Ee.lot_size,year_built:oe.yearBuilt?String(oe.yearBuilt):Ee.year_built,description:oe.description||Ee.description})),((Pe=oe.photos)==null?void 0:Pe.length)>0&&(d(oe.photos),$.forEach(Ee=>URL.revokeObjectURL(Ee)),F([]),X([]))},ne=oe=>{if(!oe)return;const ge=Array.from(oe);F(Oe=>[...Oe,...ge]);const be=ge.map(Oe=>URL.createObjectURL(Oe));X(Oe=>[...Oe,...be])},de=oe=>{URL.revokeObjectURL($[oe]),F(ge=>ge.filter((be,Oe)=>Oe!==oe)),X(ge=>ge.filter((be,Oe)=>Oe!==oe))},ce=async oe=>{var ge;if(!(!oe||!h)){B(!0);try{for(const be of Array.from(oe)){const Oe=be.name.split(".").pop(),Me=`${a==null?void 0:a.id}/${h.id}/${Date.now()}.${Oe}`,{error:Pe}=await H.storage.from("listing-photos").upload(Me,be);if(Pe)throw Pe;const{data:{publicUrl:Ee}}=H.storage.from("listing-photos").getPublicUrl(Me);await j.mutateAsync({listingId:h.id,photoUrl:Ee,isPrimary:!((ge=h.photos)!=null&&ge.length)})}ue.success("Photos uploaded!")}catch(be){console.error("Upload error:",be),ue.error("Failed to upload photos")}finally{B(!1)}}},ae=async oe=>{for(let ge=0;ge{if(h)try{await b.mutateAsync({photoId:oe,listingId:h.id}),ue.success("Photo removed")}catch{ue.error("Failed to remove photo")}},me=async oe=>{if(oe.preventDefault(),!K.city.trim()||!K.state.trim()||!K.price){ue.error("Please fill in required fields (City, State, Price)");return}if(o&&!A){ue.error("Please select an agent to assign this listing to");return}try{const ge={property_address:K.property_address||null,city:K.city,state:K.state,neighborhood:K.neighborhood||null,price:Number(K.price),property_type:K.property_type,status:K.status,bedrooms:K.bedrooms?Number(K.bedrooms):null,bathrooms:K.bathrooms?Number(K.bathrooms):null,square_footage:K.square_footage?Number(K.square_footage):null,lot_size:K.lot_size||null,year_built:K.year_built?Number(K.year_built):null,has_hoa:K.has_hoa,description:K.description||null,agent_notes:K.agent_notes||null,agent_notes_public:K.agent_notes_public,mls_link:K.mls_link||null,video_link:K.video_link||null,video_id:K.video_id||null,allow_sharing:K.allow_sharing,open_to_referrals:K.open_to_referrals,open_to_social_promotion:K.open_to_social_promotion,share_with_brokerage:K.share_with_brokerage,is_public:K.is_public};if(l)await v.mutateAsync({id:s,...ge}),ue.success("Listing updated!"),n(`/mission-control/listings/${s}`);else{B(!0);let be;if(o&&A?be=await g.mutateAsync({agentId:A,...ge}):be=await x.mutateAsync(ge),z.length>0)try{await ae(be.id),$.forEach(Oe=>URL.revokeObjectURL(Oe)),F([]),X([])}catch(Oe){console.error("Photo upload error:",Oe),ue.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Oe=0;Oen(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(wa,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Assign to Agent *"})}),e.jsxs(De,{children:[e.jsxs(zs,{value:A,onValueChange:P,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select an agent..."})}),e.jsx(Fs,{children:T.map(oe=>e.jsx(mt,{value:oe.id,children:oe.name||oe.email},oe.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(XEs,{onImport:Y}),c.length>0&&e.jsxs(Ne,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xa,{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(De,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((oe,ge)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:oe,alt:"",className:"w-full h-full object-cover"})},ge)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(_r,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Property Details"})}),e.jsx(De,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(he,{children:"Property Address"}),e.jsx(ke,{value:K.property_address,onChange:oe=>Q({...K,property_address:oe.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"City *"}),e.jsx(ke,{value:K.city,onChange:oe=>Q({...K,city:oe.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"State *"}),e.jsx(ke,{value:K.state,onChange:oe=>Q({...K,state:oe.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Neighborhood"}),e.jsx(ke,{value:K.neighborhood,onChange:oe=>Q({...K,neighborhood:oe.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Price *"}),e.jsx(ke,{type:"number",value:K.price,onChange:oe=>Q({...K,price:oe.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Type"}),e.jsxs(zs,{value:K.property_type,onValueChange:oe=>Q({...K,property_type:oe}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:nAs.map(oe=>e.jsx(mt,{value:oe.value,children:oe.label},oe.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Status"}),e.jsxs(zs,{value:K.status,onValueChange:oe=>Q({...K,status:oe}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:rAs.map(oe=>e.jsx(mt,{value:oe.value,children:oe.label},oe.value))})]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Property Specs (Optional)"})}),e.jsx(De,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Bedrooms"}),e.jsx(ke,{type:"number",value:K.bedrooms,onChange:oe=>Q({...K,bedrooms:oe.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Bathrooms"}),e.jsx(ke,{type:"number",step:"0.5",value:K.bathrooms,onChange:oe=>Q({...K,bathrooms:oe.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Sq Ft"}),e.jsx(ke,{type:"number",value:K.square_footage,onChange:oe=>Q({...K,square_footage:oe.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Lot Size"}),e.jsx(ke,{value:K.lot_size,onChange:oe=>Q({...K,lot_size:oe.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Year Built"}),e.jsx(ke,{type:"number",value:K.year_built,onChange:oe=>Q({...K,year_built:oe.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(br,{checked:K.has_hoa,onCheckedChange:oe=>Q({...K,has_hoa:oe})}),e.jsx(he,{children:"Has HOA"})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Description & Links"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:K.description,onChange:oe=>Q({...K,description:oe.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Agent Notes"}),e.jsx(ur,{value:K.agent_notes,onChange:oe=>Q({...K,agent_notes:oe.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{checked:K.agent_notes_public,onCheckedChange:oe=>Q({...K,agent_notes_public:oe})}),e.jsx(he,{className:"text-sm text-muted-foreground",children:"Make notes visible to other agents"})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"MLS Link"}),e.jsx(ke,{value:K.mls_link,onChange:oe=>Q({...K,mls_link:oe.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Video Link"}),e.jsx(ke,{value:K.video_link,onChange:oe=>Q({...K,video_link:oe.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(De,{children:e.jsx(eAs,{selectedVideoId:K.video_id,onVideoSelect:oe=>Q({...K,video_id:oe}),listingId:l?s:void 0})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Photos"})}),e.jsx(De,{children:l&&(h!=null&&h.photos)?e.jsx(JEs,{photos:h.photos,uploading:D,onUpload:oe=>ce(oe),onRemove:oe=>ie(oe),onReorder:oe=>{N.mutate({photos:oe.map(ge=>({id:ge.id,sort_order:ge.sort_order,is_primary:ge.is_primary}))})},onSetPrimary:oe=>{h&&S.mutate({photoId:oe,listingId:h.id})}}):e.jsx(iAs,{photoUrls:$,onRemove:de,onReorder:(oe,ge)=>{X(oe),F(ge)},pendingPhotos:z,uploading:D,onUpload:ne})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(De,{children:l&&s?e.jsx(sAs,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Sharing & Collaboration"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(br,{checked:K.allow_sharing,onCheckedChange:oe=>Q({...K,allow_sharing:oe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(br,{checked:K.open_to_referrals,onCheckedChange:oe=>Q({...K,open_to_referrals:oe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(br,{checked:K.open_to_social_promotion,onCheckedChange:oe=>Q({...K,open_to_social_promotion:oe})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(br,{checked:K.share_with_brokerage,onCheckedChange:oe=>Q({...K,share_with_brokerage:oe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(br,{checked:K.is_public,onCheckedChange:oe=>Q({...K,is_public:oe})})]})]})]}),e.jsx(G,{type:"submit",className:"w-full",size:"lg",disabled:x.isPending||v.isPending,children:x.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]})})}let Qf=null;function oAs(){if(Qf)return Qf;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Qf={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Qf;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 Qf={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:n},Qf;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Qf={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:n},Qf):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Qf={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:n},Qf):(Qf={canRunVirtualBg:!0,renderer:n},Qf)}catch{return Qf={canRunVirtualBg:!0},Qf}}const lAs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function cAs({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(()=>oAs()),d=!c.canRunVirtualBg,{data:h=[],refetch:m}=gt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:b}}=await H.auth.getUser();if(!b)return[];const{data:N,error:S}=await H.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return S?(console.error("Failed to load backgrounds:",S),[]):N||[]}}),x=h.map(b=>({type:"image",label:b.name,imageUrl:b.image_url,thumbnail:b.thumbnail_url||b.image_url})),g=[...lAs,...x],v=b=>b.type!==s.type?!1:b.type==="image"?b.imageUrl===s.imageUrl:!0,j=async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){if(!N.type.startsWith("image/")){ue.error("Please select an image file");return}if(N.size>5*1024*1024){ue.error("Image must be under 5MB");return}o(!0);try{const{data:{user:T}}=await H.auth.getUser();if(!T)throw new Error("Not authenticated");const A=N.name.split(".").pop()||"jpg",P=`${T.id}/${crypto.randomUUID()}.${A}`,{error:D}=await H.storage.from("video-backgrounds").upload(P,N,{contentType:N.type});if(D)throw D;const{data:B}=H.storage.from("video-backgrounds").getPublicUrl(P),z=B.publicUrl,{error:F}=await H.from("video_backgrounds").insert({name:N.name.replace(/\.[^.]+$/,""),image_url:z,thumbnail_url:z,category:"custom",is_stock:!1,user_id:T.id});if(F)throw F;await m(),t({type:"image",imageUrl:z,blurRadius:15}),ue.success("Background uploaded!")}catch(T){console.error("Upload error:",T),ue.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Bt("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(od,{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…"})]}),g.map((b,N)=>{const S=v(b);return e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({type:b.type,imageUrl:b.imageUrl,blurRadius:15}),className:Bt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",S?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[b.type==="none"&&e.jsx(WR,{className:"h-4 w-4 text-muted-foreground"}),b.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),b.type==="image"&&b.thumbnail&&e.jsx("img",{src:b.thumbnail,alt:b.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:b.label})]},`${b.type}-${b.imageUrl||N}`)}),e.jsxs("button",{type:"button",disabled:n||l,onClick:()=>{var b;return(b=i.current)==null?void 0:b.click()},className:Bt("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(Ws,{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:j}),e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({...s,mirror:!s.mirror}),className:Bt("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(iO,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var JI=typeof self<"u"?self:{};function dft(s,t){e:{for(var r=["CLOSURE_FLAGS"],n=JI,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 hft(s){JI.setTimeout(()=>{throw s},0)}var wSe,mAs=dft(610401301,!1),Dqe=dft(748402147,!0);function Rqe(){var s=JI.navigator;return s&&(s=s.userAgent)?s:""}const Oqe=JI.navigator;function Pge(s){return Pge[" "](s),s}wSe=Oqe&&Oqe.userAgentData||null,Pge[" "]=function(){};const mft={};let TR=null;function fAs(s){const t=s.length;let r=3*t/4;r%3?r=Math.floor(r):"=.".indexOf(s[t-1])!=-1&&(r="=.".indexOf(s[t-2])!=-1?r-2:r-1);const n=new Uint8Array(r);let a=0;return function(i,l){function o(d){for(;c>4),m!=64&&(l(h<<4&240|m>>2),x!=64&&l(m<<6&192|x))}}(s,function(i){n[a++]=i}),a!==r?n.subarray(0,a):n}function fft(){if(!TR){TR={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let r=0;r<5;r++){const n=s.concat(t[r].split(""));mft[r]=n;for(let a=0;a0)&&(Rqe().indexOf("Trident")!=-1||Rqe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const Fqe=/[-_.]/g,xAs={"-":"+",_:"/",".":"="};function gAs(s){return xAs[s]||""}function xft(s){if(!pft)return fAs(s);s=Fqe.test(s)?s.replace(Fqe,gAs):s,s=atob(s);const t=new Uint8Array(s.length);for(let r=0;r=t||(r[s]=n+1,yft(s=Error(),"incident"),hft(s))}}function nL(){return typeof BigInt=="function"}var aL=typeof Symbol=="function"&&typeof Symbol()=="symbol";function N1(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 bAs=N1("jas",void 0,!0),Bqe=N1(void 0,"0di"),aR=N1(void 0,"1oa"),Cx=N1(void 0,Symbol()),_As=N1(void 0,"0ub"),wAs=N1(void 0,"0ubs"),NSe=N1(void 0,"0ubsb"),jAs=N1(void 0,"0actk"),sP=N1("m_m","Pa",!0),zqe=N1();const vft={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},bft=Object.defineProperties,Fa=aL?bAs:"Ga";var nT;const $qe=[];function Mz(s,t){aL||Fa in s||bft(s,vft),s[Fa]|=t}function th(s,t){aL||Fa in s||bft(s,vft),s[Fa]=t}function Iz(s){return Mz(s,34),s}function iB(s){return Mz(s,8192),s}th($qe,7),nT=Object.freeze($qe);var rP={};function Ox(s,t){return t===void 0?s.h!==F5&&!!(2&(0|s.v[Fa])):!!(2&t)&&s.h!==F5}const F5={};function xAe(s,t){if(s!=null){if(typeof s=="string")s=s?new r1(s,eP):O5();else if(s.constructor!==r1)if(fAe(s))s=s.length?new r1(new Uint8Array(s),eP):O5();else{if(!t)throw Error();s=void 0}}return s}class Uqe{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 NAs=Object.freeze({});function _ft(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"),qqe=Lge(s=>typeof s=="string"),SAs=Lge(s=>typeof s=="boolean"),Dge=typeof JI.BigInt=="function"&&typeof JI.BigInt(0)=="bigint";function Tx(s){var t=s;if(qqe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(kAs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return Dge?BigInt(s):s=SAs(s)?s?"1":"0":qqe(s)?s.trim()||"0":String(s)}var kSe=Lge(s=>Dge?s>=TAs&&s<=AAs:s[0]==="-"?Vqe(s,CAs):Vqe(s,EAs));const CAs=Number.MIN_SAFE_INTEGER.toString(),TAs=Dge?BigInt(Number.MIN_SAFE_INTEGER):void 0,EAs=Number.MAX_SAFE_INTEGER.toString(),AAs=Dge?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Vqe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(n>>0;ad=t,_u=(s-t)/4294967296>>>0}function nP(s){if(s<0){Hqe(-s);const[t,r]=vAe(ad,_u);ad=t>>>0,_u=r>>>0}else Hqe(s)}function gAe(s){const t=IAs||(IAs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),_u=0,ad=t.getUint32(0,!0)}function jft(s,t){const r=4294967296*t+(s>>>0);return Number.isSafeInteger(r)?r:oB(s,t)}function PAs(s,t){return Tx(nL()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):oB(s,t))}function Nft(s,t){return nL()?Tx(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var r=""+(4294967296*t+s);else nL()?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+Gqe(r)+Gqe(s));return r}function Gqe(s){return s=String(s),"0000000".slice(s.length)+s}function yAe(s,t){if(2147483648&t)if(nL())s=""+(BigInt(0|t)<>>0));else{const[r,n]=vAe(s,t);s="-"+oB(r,n)}else s=oB(s,t);return s}function Rge(s){if(s.length<16)nP(Number(s));else if(nL())s=BigInt(s),ad=Number(s&BigInt(4294967295))>>>0,_u=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");_u=ad=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));_u*=1e6,ad=1e6*ad+i,ad>=4294967296&&(_u+=Math.trunc(ad/4294967296),_u>>>=0,ad>>>=0)}if(t){const[n,a]=vAe(ad,_u);ad=n,_u=a}}}function vAe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function c0(s){return Array.prototype.slice.call(s)}const Pz=typeof BigInt=="function"?BigInt.asIntN:void 0,LAs=typeof BigInt=="function"?BigInt.asUintN:void 0,B5=Number.isSafeInteger,Oge=Number.isFinite,aP=Math.trunc,DAs=Tx(0);function ER(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 Pv(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function lB(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 kft(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const RAs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Lz(s){switch(typeof s){case"bigint":return!0;case"number":return Oge(s);case"string":return RAs.test(s);default:return!1}}function oL(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Oge(s)?0|s:void 0}function Sft(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Oge(s)?s>>>0:void 0}function Cft(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(Rge(s),yAe(ad,_u))}function bAe(s){if(s=aP(s),!B5(s)){nP(s);var t=ad,r=_u;(s=2147483648&r)&&(r=~r>>>0,(t=1+~t>>>0)==0&&(r=r+1>>>0)),s=typeof(t=jft(t,r))=="number"?s?-t:t:s?"-"+t:t}return s}function Tft(s){var t=aP(Number(s));return B5(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),Cft(s))}function Eft(s){var t=aP(Number(s));return B5(t)?Tx(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),nL()?Tx(Pz(64,BigInt(s))):Tx(Cft(s)))}function Aft(s){return B5(s)?s=Tx(bAe(s)):(s=aP(s),B5(s)?s=String(s):(nP(s),s=yAe(ad,_u)),s=Tx(s)),s}function nfe(s){const t=typeof s;return s==null?s:t==="bigint"?Tx(Pz(64,s)):Lz(s)?t==="string"?Eft(s):Aft(s):void 0}function Mft(s){if(typeof s!="string")throw Error();return s}function Dz(s){if(s!=null&&typeof s!="string")throw Error();return s}function dm(s){return s==null||typeof s=="string"?s:void 0}function _Ae(s,t,r,n){return s!=null&&s[sP]===rP?s:Array.isArray(s)?((n=(r=0|s[Fa])|32&n|2&n)!==r&&th(s,n),new t(s)):(r?2&n?((s=t[Bqe])||(Iz((s=new t).v),s=t[Bqe]=s),t=s):t=new t:t=void 0,t)}function OAs(s,t,r){if(t)e:{if(!Lz(t=s))throw jSe("int64");switch(typeof t){case"string":t=Eft(t);break e;case"bigint":t=Tx(Pz(64,t));break e;default:t=Aft(t)}}else t=nfe(s);return(s=t)==null?r?DAs:void 0:s}const FAs={};let BAs=function(){try{return Pge(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class v_e{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 zAs=BAs?(Object.setPrototypeOf(v_e.prototype,Map.prototype),Object.defineProperties(v_e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),v_e):class extends Map{constructor(){super()}};function Wqe(s){return s}function b_e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var N_=class extends zAs{constructor(s,t,r=Wqe,n=Wqe){super(),this.J=0|s[Fa],this.K=t,this.S=r,this.fa=this.K?$As:n;for(let a=0;a{s.call(t,a.get(n),n,a)}):super.forEach(s,t)}set(s,t){return b_e(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 $As(s,t,r,n,a,i){return s=_Ae(s,n,r,i),a&&(s=jAe(s)),s}function UAs(s){return[s,this.get(s)]}let qAs;function Kqe(){return qAs||(qAs=new N_(Iz([]),void 0,void 0,void 0,FAs))}function Fge(s){return Cx?s[Cx]:void 0}function afe(s,t){for(const r in s)!isNaN(r)&&t(s,+r,s[r])}N_.prototype.toJSON=void 0;var SSe=class{};const VAs={Ka:!0};function HAs(s,t){t<100||tP(wAs,1)}function Bge(s,t,r,n){const a=n!==void 0;n=!!n;var i,l=Cx;!a&&aL&&l&&(i=s[l])&&afe(i,HAs),l=[];var o=s.length;let c;i=4294967295;let d=!1;const h=!!(64&t),m=h?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!h||128&t||a||(d=!0,i=i-m+m)),t=void 0;for(var x=0;x=i){const v=x-m;(t??(t={}))[v]=g}else l[x]=g}if(c)for(let g in c){if((o=c[g])==null||(o=r(o,n))==null)continue;let v;x=+g,h&&!Number.isNaN(x)&&(v=x+m){v[b]=c0(N)}),v.da=g.da,v}(s)),l}function GAs(s){return s[0]=cB(s[0]),s[1]=cB(s[1]),s}function cB(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return kSe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Fa];return s.length===0&&1&t?void 0:Bge(s,t,cB)}if(s!=null&&s[sP]===rP)return Ift(s);if(s instanceof r1){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(pft){for(var r="",n=0,a=t.length-10240;n>2];i=r[(3&i)<<4|l>>4],l=r[(15&l)<<2|o>>6],o=r[63&o],n[h++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=r[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],n[h]=r[t>>2]+r[(3&t)<<4|c>>4]+o+a}t=n.join("")}s=s.g=t}return s}return s instanceof N_?s=s.size!==0?s.V(GAs):void 0:void 0}return s}let WAs,KAs;function Ift(s){return Bge(s=s.v,0|s[Fa],cB)}function r5(s,t){return Pft(s,t[0],t[1])}function Pft(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[Fa],Dqe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(Dqe)throw Error("carr");tP(jAs,5)}(),256&a)throw Error("farr");if(64&a)return(a|n)!==a&&th(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 th(s,64|a|n),s}function YAs(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var r=0|s[Fa];return s.length===0&&1&r?void 0:Yqe(s,r,t)}if(s!=null&&s[sP]===rP)return Zqe(s);if(s instanceof N_){if(2&(t=s.J))return s;if(!s.size)return;if(r=Iz(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 zl(s,t,r,n){dL(s),Ju(s=s.v,0|s[Fa],t,r,n)}function Ju(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[Fa]))>>14&1023||536870912)?n!=null&&(s[l+(a?0:-1)]={[r]:n}):s[i]=n),t)}function s3(){return NAs===void 0?2:4}function r3(s,t,r,n,a){let i=s.v,l=0|i[Fa];n=Ox(s,l)?1:n,a=!!a||n===3,n===2&&cL(s)&&(i=s.v,l=0|i[Fa]);let o=(s=kAe(i,t))===nT?7:0|s[Fa],c=SAe(o,l);var d=!(4&c);if(d){4&c&&(s=c0(s),o=0,c=a5(c,l),l=Ju(i,l,t,s));let h=0,m=0;for(;h{const o=_Ae(l,r,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!Ox(n)&&aT(s,t),n}function sl(s,t,r,n){let a=s.v,i=0|a[Fa];if((t=Bft(a,i,t,r,n))==null)return t;if(i=0|a[Fa],!Ox(s,i)){const l=jAe(t);l!==t&&(cL(s)&&(a=s.v,i=0|a[Fa]),i=Ju(a,i,r,t=l,n),aT(a,i))}return t}function zft(s,t,r,n,a,i,l,o){var c=Ox(s,r);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&cL(s)&&(r=0|(t=s.v)[Fa]);var d=(s=kAe(t,a))===nT?7:0|s[Fa],h=SAe(d,r);if(o=!(4&h)){var m=s,x=r;const g=!!(2&h);g&&(x|=2);let v=!g,j=!0,b=0,N=0;for(;b32)for(a|=(127&r)>>4,i=3;i<32&&128&r;i+=7)r=l[o++],a|=(127&r)<>>0,a>>>0);throw Error()}function PAe(s){let t=0,r=s.g;const n=r+10,a=s.h;for(;r>>0}function ofe(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],i5(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 ZAs(s){return M2(s)}function i5(s,t){if(s.g=t,t>s.l)throw Error()}function Uft(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 qft(s,t){if(t==0)return O5();var r=Uft(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):MAs?s.slice(r,t):new Uint8Array(s.subarray(r,t))),r.length==0?O5():new r1(r,eP)}var Xqe=[];function Vft(s,t,r,n){if(lfe.length){const a=lfe.pop();return a.o(n),a.g.init(s,t,r,n),a}return new XAs(s,t,r,n)}function Hft(s){s.g.clear(),s.l=-1,s.h=-1,lfe.length<100&&lfe.push(s)}function Gft(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var r=h1(s.g);if(t=r>>>3,!((r&=7)>=0&&r<=5)||t<1)throw Error();return s.l=t,s.h=r,!0}function Rde(s){switch(s.h){case 0:s.h!=0?Rde(s):PAe(s.g);break;case 1:i5(s=s.g,s.g+8);break;case 2:if(s.h!=2)Rde(s);else{var t=h1(s.g);i5(s=s.g,s.g+t)}break;case 5:i5(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!Gft(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}Rde(s)}break;default:throw Error()}}function Rz(s,t,r){const n=s.g.l;var a=h1(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 LAe(s){var t=h1(s.g),r=Uft(s=s.g,t);if(s=s.h,dAs){var n,a=s;(n=y_e)||(n=y_e=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(ZU===void 0){try{n.decode(new Uint8Array([128]))}catch{}try{n.decode(new Uint8Array([97])),ZU=!0}catch{ZU=!1}}throw!ZU&&(y_e=void 0),o}}else{t=(i=r)+t,r=[];let o,c=null;for(;i=t?hk():(o=s[i++],l<194||(192&o)!=128?(i--,hk()):r.push((31&l)<<6|63&o)):l<240?i>=t-1?hk():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(n=s[i++]))!=128?(i--,hk()):r.push((15&l)<<12|(63&o)<<6|63&n)):l<=244?i>=t-2?hk():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(n=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,hk()):(l=(7&l)<<18|(63&o)<<12|(63&n)<<6|63&a,l-=65536,r.push(55296+(l>>10&1023),56320+(1023&l)))):hk(),r.length>=8192&&(c=Lqe(c,r),r.length=0)}i=Lqe(c,r)}return i}function Wft(s){const t=h1(s.g);return qft(s.g,t)}function $ge(s,t,r){var n=h1(s.g);for(n=s.g.g+n;s.g.g>>0,this.g=t>>>0}};let QAs;function Jqe(s){return s?/^-?\d+$/.test(s)?(Rge(s),new TSe(ad,_u)):null:JAs||(JAs=new TSe(0,0))}var TSe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let JAs;function DM(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 hL(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function Uge(s,t){if(t>=0)hL(s,t);else{for(let r=0;r<9;r++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function DAe(s){var t=ad;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 iP(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function ry(s,t,r){hL(s.g,8*t+r)}function RAe(s,t){return ry(s,t,2),t=s.g.end(),iP(s,t),t.push(s.h),t}function OAe(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 qge(s,t,r){ry(s,t,2),hL(s.g,r.length),iP(s,s.g.end()),iP(s,r)}function cfe(s,t,r,n){r!=null&&(t=RAe(s,t),n(r,s),OAe(s,t))}function k1(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var FAe=k1(),Kft=k1(),BAe=k1(),zAe=k1(),$Ae=k1(),Yft=k1(),eMs=k1(),Vge=k1(),Zft=k1(),Xft=k1();function S1(s,t,r){var n=s.v;Cx&&Cx in n&&(n=n[Cx])&&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 Ba=class{constructor(s,t){this.v=Pft(s,t,void 0,2048)}toJSON(){return Ift(this)}j(){var a;var s=DMs,t=this.v,r=s.g,n=Cx;if(aL&&n&&((a=t[n])==null?void 0:a[r])!=null&&tP(_As,3),t=s.g,zqe&&Cx&&zqe===void 0&&(n=(r=this.v)[Cx])&&(n=n.da))try{n(r,t,VAs)}catch(i){hft(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[Fa];return NAe(this,s,t)?wAe(this,s,!0):new this.constructor(lL(s,t,!1))}};Ba.prototype[sP]=rP,Ba.prototype.toString=function(){return this.v.toString()};var mL=class{constructor(s,t,r){this.g=s,this.h=t,s=FAe,this.l=!!s&&r===s||!1}};function Hge(s,t){return new mL(s,t,FAe)}function Qft(s,t,r,n,a){cfe(s,r,spt(t,n),a)}const tMs=Hge(function(s,t,r,n,a){return s.h===2&&(Rz(s,EAe(t,n,r),a),!0)},Qft),sMs=Hge(function(s,t,r,n,a){return s.h===2&&(Rz(s,EAe(t,n,r),a),!0)},Qft);var Gge=Symbol(),Wge=Symbol(),ESe=Symbol(),eVe=Symbol(),tVe=Symbol();let Jft,ept;function iT(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 WAs||(WAs=[0,void 0,!0]);case"number":return m>0?void 0:m===0?KAs||(KAs=[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,Jft??(Jft=i),ept??(ept=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 qAe(s,t,r,n,a){const i=r.g;let l,o;s[t]=(c,d,h)=>i(c,d,h,o||(o=iT(Wge,UAe,qAe,n).T),l||(l=VAe(n)),a)}function VAe(s){let t=s[ESe];if(t!=null)return t;const r=iT(Wge,UAe,qAe,s);return t=r.ma?(n,a)=>Jft(n,a,r):(n,a)=>{for(;Gft(a)&&a.h!=4;){var i=a.l,l=r[i];if(l==null){var o=r.ba;o&&(o=o[i])&&(o=nMs(o))!=null&&(l=r[i]=o)}if(l==null||!l(a,n,i)){if(l=(o=a).m,Rde(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=qft(o.g,c);l=void 0,o=n,c&&((l=o[Cx]??(o[Cx]=new SSe))[i]??(l[i]=[])).push(c)}}return(n=Fge(n))&&(n.da=r.qa[tVe]),!0},s[ESe]=t,s[tVe]=rMs.bind(s),t}function rMs(s,t,r,n){var a=this[Wge];const i=this[ESe],l=r5(void 0,a.T),o=Fge(s);if(o){var c=!1,d=a.ba;if(d){if(a=(h,m,x)=>{if(x.length!==0)if(d[m])for(const g of x){h=Vft(g);try{c=!0,i(l,h)}finally{Hft(h)}}else n==null||n(s,m,x)},t==null)afe(o,a);else if(o!=null){const h=o[t];h&&a(o,t,h)}if(c){let h=0|s[Fa];if(2&h&&2048&h&&!(r!=null&&r.Ka))throw Error();const m=iL(h),x=(g,v)=>{if(k_(s,g,m)!=null){if((r==null?void 0:r.Qa)===1)return;throw Error()}v!=null&&(h=Ju(s,h,g,v,m)),delete o[g]};t==null?_ft(l,0|l[Fa],(g,v)=>{x(g,v)}):x(t,k_(l,t,m))}}}}function nMs(s){const t=(s=tpt(s))[0].g;if(s=s[1]){const r=VAe(s),n=iT(Wge,UAe,qAe,s).T;return(a,i,l)=>t(a,i,l,n,r)}return t}function Kge(s,t,r){s[t]=r.h}function Yge(s,t,r,n){let a,i;const l=r.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=iT(Gge,Kge,Yge,n).T),a||(a=rpt(n)))}function rpt(s){let t=s[eVe];if(!t){const r=iT(Gge,Kge,Yge,s);t=(n,a)=>npt(n,a,r),s[eVe]=t}return t}function npt(s,t,r){_ft(s,0|s[Fa],(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=tpt(c))[0].h;if(c=c[1]){const h=rpt(c),m=iT(Gge,Kge,Yge,c).T;c=l.ma?ept(m,h):(x,g,v)=>d(x,g,v,m,h)}else c=d;return l[o]=c}}(r,n);i?i(t,a,n):n<500||tP(NSe,3)}}),(s=Fge(s))&&afe(s,(n,a,i)=>{for(iP(t,t.g.end()),n=0;n{cfe(s,r,r5([l,i],n),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),DM(s.g,r.h,r.g);break;default:r=Jqe(t),DM(s.g,r.h,r.g)}}function opt(s,t,r){(t=oL(t))!=null&&t!=null&&(ry(s,r,0),Uge(s.g,t))}function lpt(s,t,r){(t=kft(t))!=null&&(ry(s,r,0),s.g.g.push(t?1:0))}function cpt(s,t,r){(t=dm(t))!=null&&qge(s,r,uft(t))}function dpt(s,t,r,n,a){cfe(s,r,spt(t,n),a)}function upt(s,t,r){(t=t==null||typeof t=="string"||t instanceof r1?t:void 0)!=null&&qge(s,r,MAe(t,!0).buffer)}function hpt(s,t,r){(t=Sft(t))!=null&&t!=null&&(ry(s,r,0),hL(s.g,t))}function mpt(s,t,r){return(s.h===5||s.h===2)&&(t=uL(t,0|t[Fa],r),s.h==2?$ge(s,ofe,t):t.push(ofe(s.g)),!0)}var Nu=Hm(function(s,t,r){return s.h===5&&(Gm(t,r,ofe(s.g)),!0)},apt,Vge),oMs=pL(mpt,function(s,t,r){if((t=fL(Pv,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"))||(Rge(n),n=oB(ad,_u))),n;if(a==="number")return(n=aP(n))>=0&&B5(n)||(nP(n),n=jft(ad,_u)),n}}(t),t!=null&&(typeof t=="string"&&Qqe(t),t!=null))switch(ry(s,r,0),typeof t){case"number":s=s.g,nP(t),DM(s,ad,_u);break;case"bigint":r=BigInt.asUintN(64,t),r=new CSe(Number(r&BigInt(4294967295)),Number(r>>BigInt(32))),DM(s.g,r.h,r.g);break;default:r=Qqe(t),DM(s.g,r.h,r.g)}},eMs),Wu=Hm(function(s,t,r){return s.h===0&&(Gm(t,r,M2(s.g)),!0)},opt,zAe),Oz=pL(function(s,t,r){return(s.h===0||s.h===2)&&(t=uL(t,0|t[Fa],r),s.h==2?$ge(s,M2,t):t.push(M2(s.g)),!0)},function(s,t,r){if((t=fL(oL,t))!=null&&t.length){r=RAe(s,r);for(let n=0;n{{const i={ea:!0};n&&Object.assign(i,n),r=Vft(r,void 0,void 0,i);try{const l=new s,o=l.v;VAe(t)(o,r);var a=l}finally{Hft(r)}}return a}}function Zge(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}}}};npt(this.v,t,iT(Gge,Kge,Yge,s)),iP(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=nVe.createPolicy("goog#html",{createHTML:n,createScript:n,createScriptURL:n})}catch{}return r}()),s=(t=j_e)?t.createScriptURL(s):s,new class{constructor(r){this.g=r}toString(){return this.g+""}}(s)}function XU(s,...t){if(t.length===0)return aVe(s[0]);let r=s[0];for(let n=0;n({index:Og(n,1)??0??-1,score:Jd(n,2)??0,categoryName:dm(ud(n,3))??""??"",displayName:dm(ud(n,4))??""??""})),headIndex:t,headName:r}}function BMs(s){const t={classifications:S_(s,bMs,1).map(r=>{var n;return JAe(((n=sl(r,wpt,4))==null?void 0:n.g())??[],Og(r,2)??0,dm(ud(r,3))??"")})};return function(r){return r==null?r:typeof r=="bigint"?(kSe(r)?r=Number(r):(r=Pz(64,r),r=kSe(r)?Number(r):String(r)),r):Lz(r)?typeof r=="number"?bAe(r):Tft(r):void 0}(ud(s,2,void 0,void 0,nfe))!=null&&(t.timestampMs=Ypt(ud(s,2,void 0,void 0,nfe)??Lft)),t}function Zpt(s){var l,o;var t=r3(s,3,Pv,s3()),r=r3(s,2,oL,s3()),n=r3(s,1,dm,s3()),a=r3(s,9,dm,s3());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function gVe(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 yVe(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;{const r=self.import;r?await r(s.toString()):await import(s.toString())}}}function Jpt(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 qa(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 vVe(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]=Jpt(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 bVe(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 sv(s,t,r){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=r}function Ow(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)}}fA.forVisionTasks=function(s,t=!1){return JU("vision",s??XU``,t)},fA.forTextTasks=function(s,t=!1){return JU("text",s??XU``,t)},fA.forGenAiTasks=function(s,t=!1){return JU("genai",s??XU``,t)},fA.forAudioTasks=function(s,t=!1){return JU("audio",s??XU``,t)},fA.isSimdSupported=function(s=!1){return Xpt(s)};async function $Ms(s,t,r,n){return s=await(async(a,i,l,o,c)=>{if(i&&await yVe(i),!self.ModuleFactory||l&&(await yVe(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 S_e(s,t){const r=sl(s.baseOptions,dfe,1)||new dfe;typeof t=="string"?(zl(r,2,Dz(t)),zl(r,1)):t instanceof Uint8Array&&(zl(r,1,xAe(t,!1)),zl(r,2)),ui(s.baseOptions,0,1,r)}function _Ve(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 _a(s,t){s.C=Math.max(s.C,t)}function eye(s,t){s.B=new jp,Fx(s.B,2,"PassThroughCalculator"),Yc(s.B,"free_memory"),Oo(s.B,"free_memory_unused_out"),xd(t,"free_memory"),ny(t,s.B)}function oP(s,t){Yc(s.B,t),Oo(s.B,t+"_unused_out")}function tye(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var LSe=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=sl(this.baseOptions,dfe,1))!=null&&a.g()||(i=sl(this.baseOptions,dfe,1))!=null&&i.l()||(l=s.baseOptions)!=null&&l.modelAssetBuffer||(o=s.baseOptions)!=null&&o.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(d,h){let m=sl(d.baseOptions,hVe,3);if(!m){var x=m=new hVe,g=new iVe;w8(x,4,Ode,g)}"delegate"in h&&(h.delegate==="GPU"?(h=m,x=new mMs,w8(h,2,Ode,x)):(h=m,x=new iVe,w8(h,4,Ode,x))),ui(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),S_e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)S_e(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const h=[];for(var m=0;;){const{done:x,value:g}=await d.read();if(x)break;h.push(g),m+=g.length}if(h.length===0)return new Uint8Array(0);if(h.length===1)return h[0];d=new Uint8Array(m),m=0;for(const x of h)d.set(x,m),m+=x.length;return d}(c.modelAssetBuffer).then(d=>{S_e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=fMs(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,_Ve(this)}finishProcessing(){this.g.finishProcessing(),_Ve(this)}close(){this.B=void 0,this.g.closeGraph()}};function m2(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}LSe.prototype.close=LSe.prototype.close;class UMs{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 wVe(s,t,r){const n=s.g;if(r=m2(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 jVe(s,t){const r=s.g,n=m2(r.createVertexArray(),"Failed to create vertex array");r.bindVertexArray(n);const a=m2(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=m2(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 UMs(r,n,a,i)}function eMe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function qMs(s,t,r,n){return eMe(s,t),s.h||(s.m(),s.D()),r?(s.u||(s.u=jVe(s,!0)),r=s.u):(s.A||(s.A=jVe(s,!1)),r=s.A),t.useProgram(s.h),r.bind(),s.l(),s=n(),r.g.bindVertexArray(null),s}function ext(s,t,r){return eMe(s,t),s=m2(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 txt(s,t,r){eMe(s,t),s.B||(s.B=m2(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 VMs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var sxt=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=m2(s.createProgram(),"Failed to create WebGL program"),this.X=wVe(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=wVe(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 Bb(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 DSe(s){var t=Bb(s,1);if(!t){if(t=Bb(s,0))t=new Float32Array(t).map(n=>n/255);else{t=new Float32Array(s.width*s.height);const n=lP(s);var r=tMe(s);if(txt(r,n,rxt(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 DSe(this)}N(){return rxt(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=lP(this),a=tMe(this);n.activeTexture(n.TEXTURE1),r=ext(a,n,this.m?n.LINEAR:n.NEAREST),n.bindTexture(n.TEXTURE_2D,r);const i=nxt(this);n.texImage2D(n.TEXTURE_2D,0,i,this.width,this.height,0,n.RED,n.FLOAT,null),n.bindTexture(n.TEXTURE_2D,null),txt(a,n,r),qMs(a,n,!1,()=>{axt(this),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLE_FAN,0,4),RSe(this)}),VMs(a),RSe(this)}}s.push(r)}return new ph(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&lP(this).deleteTexture(Bb(this,2)),NVe=-1}};ph.prototype.close=ph.prototype.close,ph.prototype.clone=ph.prototype.clone,ph.prototype.getAsWebGLTexture=ph.prototype.N,ph.prototype.getAsFloat32Array=ph.prototype.ia,ph.prototype.getAsUint8Array=ph.prototype.ja,ph.prototype.hasWebGLTexture=ph.prototype.R,ph.prototype.hasFloat32Array=ph.prototype.ka,ph.prototype.hasUint8Array=ph.prototype.Fa;var NVe=250;function b0(...s){return s.map(([t,r])=>({start:t,end:r}))}const HMs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((kVe=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:Qpt()?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?'),qa(this,n||"input_audio",i=>{qa(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){sv(this,"__graph_config__",t=>{s(t)}),qa(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),qa(this,n,l=>{this.i._addAudioToInputStream(this.g,t,r,l,a)})}addGpuBufferToStream(s,t,r){qa(this,t,n=>{const[a,i]=vVe(this,s,n);this.i._addBoundTextureToStream(n,a,i,r)})}addBoolToStream(s,t,r){qa(this,t,n=>{this.i._addBoolToInputStream(s,n,r)})}addDoubleToStream(s,t,r){qa(this,t,n=>{this.i._addDoubleToInputStream(s,n,r)})}addFloatToStream(s,t,r){qa(this,t,n=>{this.i._addFloatToInputStream(s,n,r)})}addIntToStream(s,t,r){qa(this,t,n=>{this.i._addIntToInputStream(s,n,r)})}addUintToStream(s,t,r){qa(this,t,n=>{this.i._addUintToInputStream(s,n,r)})}addStringToStream(s,t,r){qa(this,t,n=>{qa(this,s,a=>{this.i._addStringToInputStream(a,n,r)})})}addStringRecordToStream(s,t,r){qa(this,t,n=>{bVe(this,Object.keys(s),a=>{bVe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,n,r)})})})}addProtoToStream(s,t,r,n){qa(this,r,a=>{qa(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){qa(this,s,r=>{this.i._addEmptyPacketToInputStream(r,t)})}addBoolVectorToStream(s,t,r){qa(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){qa(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){qa(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){qa(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){qa(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){qa(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)qa(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,n,r)})}addBoolToInputSidePacket(s,t){qa(this,t,r=>{this.i._addBoolToInputSidePacket(s,r)})}addDoubleToInputSidePacket(s,t){qa(this,t,r=>{this.i._addDoubleToInputSidePacket(s,r)})}addFloatToInputSidePacket(s,t){qa(this,t,r=>{this.i._addFloatToInputSidePacket(s,r)})}addIntToInputSidePacket(s,t){qa(this,t,r=>{this.i._addIntToInputSidePacket(s,r)})}addUintToInputSidePacket(s,t){qa(this,t,r=>{this.i._addUintToInputSidePacket(s,r)})}addStringToInputSidePacket(s,t){qa(this,t,r=>{qa(this,s,n=>{this.i._addStringToInputSidePacket(n,r)})})}addProtoToInputSidePacket(s,t,r){qa(this,r,n=>{qa(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){qa(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){qa(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){qa(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){qa(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){qa(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){qa(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)qa(this,a,i=>{this.i._addStringVectorEntry(n,i)});this.i._addStringVectorToInputSidePacket(n,r)})}attachBoolListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachBoolListener(r)})}attachBoolVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachBoolVectorListener(r)})}attachIntListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachIntListener(r)})}attachIntVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachIntVectorListener(r)})}attachUintListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachUintListener(r)})}attachUintVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachUintVectorListener(r)})}attachDoubleListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachDoubleListener(r)})}attachDoubleVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachDoubleVectorListener(r)})}attachFloatListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachFloatListener(r)})}attachFloatVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachFloatVectorListener(r)})}attachStringListener(s,t){sv(this,s,t),qa(this,s,r=>{this.i._attachStringListener(r)})}attachStringVectorListener(s,t){Ow(this,s,t),qa(this,s,r=>{this.i._attachStringVectorListener(r)})}attachProtoListener(s,t,r){sv(this,s,t),qa(this,s,n=>{this.i._attachProtoListener(n,r||!1)})}attachProtoVectorListener(s,t,r){Ow(this,s,t),qa(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?'),sv(this,s,(n,a)=>{n=new Float32Array(n.buffer,n.byteOffset,n.length/4),t(n,a)}),qa(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 kVe{get ga(){return this.i}pa(s,t,r){qa(this,t,n=>{const[a,i]=vVe(this,s,n);this.ga._addBoundTextureAsImageToStream(n,a,i,r)})}Z(s,t){sv(this,s,t),qa(this,s,r=>{this.ga._attachImageListener(r)})}aa(s,t){Ow(this,s,t),qa(this,s,r=>{this.ga._attachImageVectorListener(r)})}}));var kVe,_0=class extends HMs{};async function Zo(s,t,r){return async function(n,a,i,l){return $Ms(n,a,i,l)}(s,r.canvas??(Qpt()?void 0:document.createElement("canvas")),t,r)}function ixt(s,t,r,n){if(s.U){const i=new Cpt;if(r!=null&&r.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=r.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error("Expected RectF values to be in [0,1].");Ka(i,1,(a.left+a.right)/2),Ka(i,2,(a.top+a.bottom)/2),Ka(i,4,a.right-a.left),Ka(i,3,a.bottom-a.top)}else Ka(i,1,.5),Ka(i,2,.5),Ka(i,4,1),Ka(i,3,1);if(r!=null&&r.rotationDegrees){if((r==null?void 0:r.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ka(i,5,-Math.PI*r.rotationDegrees/180),(r==null?void 0:r.rotationDegrees)%180!=0){const[l,o]=Jpt(t);r=Jd(i,3)*o/l,a=Jd(i,4)*l/o,Ka(i,4,r),Ka(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,n)}s.g.pa(t,s.X,n??performance.now()),s.finishProcessing()}function w0(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'.");ixt(s,t,r,s.C+1)}function T1(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'.");ixt(s,t,r,n)}function cP(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 ph([a],r,!1,s.g.i.canvas,s.P,i,t),n?s.clone():s}var Bx=class extends LSe{constructor(s,t,r,n){super(s),this.g=s,this.X=t,this.U=r,this.oa=n,this.P=new sxt}l(s,t=!0){if("runningMode"in s&&zl(this.baseOptions,2,lB(!!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()}};Bx.prototype.close=Bx.prototype.close;var xg=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},ui(s=this.h=new Qge,0,1,t=new Ud),Ka(this.h,2,.5),Ka(this.h,3,.3)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ka(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ka(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},w0(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},T1(this,s,r,t),this.j}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect_in"),ml(s,"detections");const t=new Vx;S1(t,SMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect_in"),Oo(r,"DETECTIONS:detections"),r.o(t),ny(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=Npt(i),this.j.detections.push(Zpt(n));_a(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};xg.prototype.detectForVideo=xg.prototype.G,xg.prototype.detect=xg.prototype.F,xg.prototype.setOptions=xg.prototype.o,xg.createFromModelPath=async function(s,t){return Zo(xg,s,{baseOptions:{modelAssetPath:t}})},xg.createFromModelBuffer=function(s,t){return Zo(xg,s,{baseOptions:{modelAssetBuffer:t}})},xg.createFromOptions=function(s,t){return Zo(xg,s,t)};var sMe=b0([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]),rMe=b0([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]),nMe=b0([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),oxt=b0([474,475],[475,476],[476,477],[477,474]),aMe=b0([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]),iMe=b0([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),lxt=b0([469,470],[470,471],[471,472],[472,469]),oMe=b0([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]),cxt=[...sMe,...rMe,...nMe,...aMe,...iMe,...oMe],dxt=b0([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 SVe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var jd=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,ui(s=this.h=new Ipt,0,1,t=new Ud),this.A=new Mpt,ui(this.h,0,3,this.A),this.u=new Qge,ui(this.h,0,2,this.u),C_(this.u,4,1),Ka(this.u,2,.5),Ka(this.A,2,.5),Ka(this.h,4,.5)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return"numFaces"in s&&C_(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ka(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ka(this.A,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in s&&(this.outputFacialTransformationMatrixes=!!s.outputFacialTransformationMatrixes),this.l(s)}F(s,t){return SVe(this),w0(this,s,t),this.j}G(s,t,r){return SVe(this),T1(this,s,r,t),this.j}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect"),ml(s,"face_landmarks");const t=new Vx;S1(t,TMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"NORM_LANDMARKS:face_landmarks"),r.o(t),ny(s,r),this.g.attachProtoVectorListener("face_landmarks",(n,a)=>{for(const i of n)n=Fz(i),this.j.faceLandmarks.push(Jge(n));_a(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",n=>{_a(this,n)}),this.outputFaceBlendshapes&&(ml(s,"blendshapes"),Oo(r,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(n,a)=>{if(this.outputFaceBlendshapes)for(const i of n)n=Xge(i),this.j.faceBlendshapes.push(JAe(n.g()??[]));_a(this,a)}),this.g.attachEmptyPacketListener("blendshapes",n=>{_a(this,n)})),this.outputFacialTransformationMatrixes&&(ml(s,"face_geometry"),Oo(r,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(n,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of n)(n=sl(n=CMs(i),yMs,2))&&this.j.facialTransformationMatrixes.push({rows:Og(n,1)??0??0,columns:Og(n,2)??0??0,data:r3(n,3,Pv,s3()).slice()??[]});_a(this,a)}),this.g.attachEmptyPacketListener("face_geometry",n=>{_a(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};jd.prototype.detectForVideo=jd.prototype.G,jd.prototype.detect=jd.prototype.F,jd.prototype.setOptions=jd.prototype.o,jd.createFromModelPath=function(s,t){return Zo(jd,s,{baseOptions:{modelAssetPath:t}})},jd.createFromModelBuffer=function(s,t){return Zo(jd,s,{baseOptions:{modelAssetBuffer:t}})},jd.createFromOptions=function(s,t){return Zo(jd,s,t)},jd.FACE_LANDMARKS_LIPS=sMe,jd.FACE_LANDMARKS_LEFT_EYE=rMe,jd.FACE_LANDMARKS_LEFT_EYEBROW=nMe,jd.FACE_LANDMARKS_LEFT_IRIS=oxt,jd.FACE_LANDMARKS_RIGHT_EYE=aMe,jd.FACE_LANDMARKS_RIGHT_EYEBROW=iMe,jd.FACE_LANDMARKS_RIGHT_IRIS=lxt,jd.FACE_LANDMARKS_FACE_OVAL=oMe,jd.FACE_LANDMARKS_CONTOURS=cxt,jd.FACE_LANDMARKS_TESSELATION=dxt;var lMe=b0([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 CVe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function TVe(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 EVe(s,t=!0){const r=[];for(const a of s){var n=Xge(a);s=[];for(const i of n.g())n=t&&Og(i,1)!=null?Og(i,1)??0:-1,s.push({score:Jd(i,2)??0,index:n,categoryName:dm(ud(i,3))??""??"",displayName:dm(ud(i,4))??""??""});r.push(s)}return r}var Up=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ui(s=this.j=new Dpt,0,1,t=new Ud),this.u=new YAe,ui(this.j,0,2,this.u),this.D=new KAe,ui(this.u,0,3,this.D),this.A=new Lpt,ui(this.u,0,2,this.A),this.h=new EMs,ui(this.j,0,3,this.h),Ka(this.A,2,.5),Ka(this.u,4,.5),Ka(this.D,2,.5)}get baseOptions(){return sl(this.j,Ud,1)}set baseOptions(s){ui(this.j,0,1,s)}o(s){var a,i,l,o;if(C_(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ka(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ka(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new ZE,r=t,n=PSe(s.cannedGesturesClassifierOptions,(a=sl(this.h,ZE,3))==null?void 0:a.l());ui(r,0,2,n),ui(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=sl(this.h,ZE,3))==null||i.g());return s.customGesturesClassifierOptions?(ui(r=t=new ZE,0,2,n=PSe(s.customGesturesClassifierOptions,(l=sl(this.h,ZE,4))==null?void 0:l.l())),ui(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=sl(this.h,ZE,4))==null||o.g()),this.l(s)}Ha(s,t){return CVe(this),w0(this,s,t),TVe(this)}Ia(s,t,r){return CVe(this),T1(this,s,r,t),TVe(this)}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect"),ml(s,"hand_gestures"),ml(s,"hand_landmarks"),ml(s,"world_hand_landmarks"),ml(s,"handedness");const t=new Vx;S1(t,AMs,this.j);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"HAND_GESTURES:hand_gestures"),Oo(r,"LANDMARKS:hand_landmarks"),Oo(r,"WORLD_LANDMARKS:world_hand_landmarks"),Oo(r,"HANDEDNESS:handedness"),r.o(t),ny(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n){n=Fz(i);const l=[];for(const o of S_(n,Spt,1))l.push({x:Jd(o,1)??0,y:Jd(o,2)??0,z:Jd(o,3)??0,visibility:Jd(o,4)??0});this.landmarks.push(l)}_a(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{_a(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n){n=RM(i);const l=[];for(const o of S_(n,kpt,1))l.push({x:Jd(o,1)??0,y:Jd(o,2)??0,z:Jd(o,3)??0,visibility:Jd(o,4)??0});this.worldLandmarks.push(l)}_a(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{_a(this,n)}),this.g.attachProtoVectorListener("hand_gestures",(n,a)=>{this.gestures.push(...EVe(n,!1)),_a(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",n=>{_a(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{this.handedness.push(...EVe(n)),_a(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function AVe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}Up.prototype.recognizeForVideo=Up.prototype.Ia,Up.prototype.recognize=Up.prototype.Ha,Up.prototype.setOptions=Up.prototype.o,Up.createFromModelPath=function(s,t){return Zo(Up,s,{baseOptions:{modelAssetPath:t}})},Up.createFromModelBuffer=function(s,t){return Zo(Up,s,{baseOptions:{modelAssetBuffer:t}})},Up.createFromOptions=function(s,t){return Zo(Up,s,t)},Up.HAND_CONNECTIONS=lMe;var qp=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ui(s=this.h=new YAe,0,1,t=new Ud),this.u=new KAe,ui(this.h,0,3,this.u),this.j=new Lpt,ui(this.h,0,2,this.j),C_(this.j,3,1),Ka(this.j,2,.5),Ka(this.u,2,.5),Ka(this.h,4,.5)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return"numHands"in s&&C_(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ka(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ka(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],w0(this,s,t),AVe(this)}G(s,t,r){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],T1(this,s,r,t),AVe(this)}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect"),ml(s,"hand_landmarks"),ml(s,"world_hand_landmarks"),ml(s,"handedness");const t=new Vx;S1(t,MMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"LANDMARKS:hand_landmarks"),Oo(r,"WORLD_LANDMARKS:world_hand_landmarks"),Oo(r,"HANDEDNESS:handedness"),r.o(t),ny(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n)n=Fz(i),this.landmarks.push(Jge(n));_a(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{_a(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n)n=RM(i),this.worldLandmarks.push(N8(n));_a(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{_a(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of n){n=Xge(c);const d=[];for(const h of n.g())d.push({score:Jd(h,2)??0,index:Og(h,1)??0??-1,categoryName:dm(ud(h,3))??""??"",displayName:dm(ud(h,4))??""??""});o.push(d)}l.call(i,...o),_a(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};qp.prototype.detectForVideo=qp.prototype.G,qp.prototype.detect=qp.prototype.F,qp.prototype.setOptions=qp.prototype.o,qp.createFromModelPath=function(s,t){return Zo(qp,s,{baseOptions:{modelAssetPath:t}})},qp.createFromModelBuffer=function(s,t){return Zo(qp,s,{baseOptions:{modelAssetBuffer:t}})},qp.createFromOptions=function(s,t){return Zo(qp,s,t)},qp.HAND_CONNECTIONS=lMe;var uxt=b0([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 MVe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function IVe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{tye(s)}}function tq(s,t){s=Fz(s),t.push(Jge(s))}var Bc=class extends Bx{constructor(s,t){super(new _0(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,ui(s=this.j=new zpt,0,1,t=new Ud),this.I=new KAe,ui(this.j,0,2,this.I),this.W=new IMs,ui(this.j,0,3,this.W),this.u=new Qge,ui(this.j,0,4,this.u),this.O=new Mpt,ui(this.j,0,5,this.O),this.A=new Fpt,ui(this.j,0,6,this.A),this.M=new Bpt,ui(this.j,0,7,this.M),Ka(this.u,2,.5),Ka(this.u,3,.3),Ka(this.O,2,.5),Ka(this.A,2,.5),Ka(this.A,3,.3),Ka(this.M,2,.5),Ka(this.I,2,.5)}get baseOptions(){return sl(this.j,Ud,1)}set baseOptions(s){ui(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ka(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ka(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ka(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ka(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ka(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ka(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ka(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:r,MVe(this),w0(this,s,n),IVe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.D=typeof r=="function"?r:n,MVe(this),T1(this,s,a,t),IVe(this)}m(){var s=new Hx;xd(s,"input_frames_image"),ml(s,"pose_landmarks"),ml(s,"pose_world_landmarks"),ml(s,"face_landmarks"),ml(s,"left_hand_landmarks"),ml(s,"left_hand_world_landmarks"),ml(s,"right_hand_landmarks"),ml(s,"right_hand_world_landmarks");const t=new Vx,r=new sVe;Fx(r,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))zl(a,2,Bge(i,0,cB));else{if(!(typeof i=="string"||i instanceof r1||fAe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");oj(a,2,xAe(i,!1),O5())}}(r,this.j.g());const n=new jp;Fx(n,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),AAe(n,8,sVe,r),Yc(n,"IMAGE:input_frames_image"),Oo(n,"POSE_LANDMARKS:pose_landmarks"),Oo(n,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Oo(n,"FACE_LANDMARKS:face_landmarks"),Oo(n,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Oo(n,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Oo(n,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Oo(n,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),n.o(t),ny(s,n),eye(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{tq(a,this.h.poseLandmarks),_a(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{_a(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=RM(a),l.push(N8(a)),_a(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{_a(this,a)}),this.outputPoseSegmentationMasks&&(Oo(n,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),oP(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[cP(this,a,!0,!this.D)],_a(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],_a(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{tq(a,this.h.faceLandmarks),_a(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{_a(this,a)}),this.outputFaceBlendshapes&&(ml(s,"extra_blendshapes"),Oo(n,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=Xge(a),l.push(JAe(a.g()??[]))),_a(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{_a(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{tq(a,this.h.leftHandLandmarks),_a(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{_a(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=RM(a),l.push(N8(a)),_a(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{_a(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{tq(a,this.h.rightHandLandmarks),_a(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{_a(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=RM(a),l.push(N8(a)),_a(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{_a(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Bc.prototype.detectForVideo=Bc.prototype.G,Bc.prototype.detect=Bc.prototype.F,Bc.prototype.setOptions=Bc.prototype.o,Bc.createFromModelPath=function(s,t){return Zo(Bc,s,{baseOptions:{modelAssetPath:t}})},Bc.createFromModelBuffer=function(s,t){return Zo(Bc,s,{baseOptions:{modelAssetBuffer:t}})},Bc.createFromOptions=function(s,t){return Zo(Bc,s,t)},Bc.HAND_CONNECTIONS=lMe,Bc.POSE_CONNECTIONS=uxt,Bc.FACE_LANDMARKS_LIPS=sMe,Bc.FACE_LANDMARKS_LEFT_EYE=rMe,Bc.FACE_LANDMARKS_LEFT_EYEBROW=nMe,Bc.FACE_LANDMARKS_LEFT_IRIS=oxt,Bc.FACE_LANDMARKS_RIGHT_EYE=aMe,Bc.FACE_LANDMARKS_RIGHT_EYEBROW=iMe,Bc.FACE_LANDMARKS_RIGHT_IRIS=lxt,Bc.FACE_LANDMARKS_FACE_OVAL=oMe,Bc.FACE_LANDMARKS_CONTOURS=cxt,Bc.FACE_LANDMARKS_TESSELATION=dxt;var gg=class extends Bx{constructor(s,t){super(new _0(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},ui(s=this.h=new $pt,0,1,t=new Ud)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return ui(this.h,0,2,PSe(s,sl(this.h,GAe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},w0(this,s,t),this.j}ta(s,t,r){return this.j={classifications:[]},T1(this,s,r,t),this.j}m(){var s=new Hx;xd(s,"input_image"),xd(s,"norm_rect"),ml(s,"classifications");const t=new Vx;S1(t,PMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Yc(r,"IMAGE:input_image"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"CLASSIFICATIONS:classifications"),r.o(t),ny(s,r),this.g.attachProtoListener("classifications",(n,a)=>{this.j=BMs(_Ms(n)),_a(this,a)}),this.g.attachEmptyPacketListener("classifications",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};gg.prototype.classifyForVideo=gg.prototype.ta,gg.prototype.classify=gg.prototype.sa,gg.prototype.setOptions=gg.prototype.o,gg.createFromModelPath=function(s,t){return Zo(gg,s,{baseOptions:{modelAssetPath:t}})},gg.createFromModelBuffer=function(s,t){return Zo(gg,s,{baseOptions:{modelAssetBuffer:t}})},gg.createFromOptions=function(s,t){return Zo(gg,s,t)};var Vp=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!0),this.h=new Upt,this.embeddings={embeddings:[]},ui(s=this.h,0,1,t=new Ud)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){var t=this.h,r=sl(this.h,uVe,2);return r=r?r.clone():new uVe,s.l2Normalize!==void 0?zl(r,1,lB(s.l2Normalize)):"l2Normalize"in s&&zl(r,1),s.quantize!==void 0?zl(r,2,lB(s.quantize)):"quantize"in s&&zl(r,2),ui(t,0,2,r),this.l(s)}za(s,t){return w0(this,s,t),this.embeddings}Aa(s,t,r){return T1(this,s,r,t),this.embeddings}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect"),ml(s,"embeddings_out");const t=new Vx;S1(t,LMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"EMBEDDINGS:embeddings_out"),r.o(t),ny(s,r),this.g.attachProtoListener("embeddings_out",(n,a)=>{n=NMs(n),this.embeddings=function(i){return{embeddings:S_(i,jMs,1).map(l=>{var d,h;const o={headIndex:Og(l,3)??0??-1,headName:dm(ud(l,4))??""??""};var c=l.v;return Bft(c,0|c[Fa],dVe,__e(l,1))!==void 0?(l=r3(l=sl(l,dVe,__e(l,1),void 0),1,Pv,s3()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((h=(d=sl(l,wMs,__e(l,2),void 0))==null?void 0:d.na())==null?void 0:h.h())??c),o}),timestampMs:Ypt(ud(i,2,void 0,void 0,nfe)??Lft)}}(n),_a(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Vp.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=gVe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=gVe(xVe(s.quantizedEmbedding),xVe(t.quantizedEmbedding))}return s},Vp.prototype.embedForVideo=Vp.prototype.Aa,Vp.prototype.embed=Vp.prototype.za,Vp.prototype.setOptions=Vp.prototype.o,Vp.createFromModelPath=function(s,t){return Zo(Vp,s,{baseOptions:{modelAssetPath:t}})},Vp.createFromModelBuffer=function(s,t){return Zo(Vp,s,{baseOptions:{modelAssetBuffer:t}})},Vp.createFromOptions=function(s,t){return Zo(Vp,s,t)};var OSe=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 GMs(s){var r,n;const t=function(a){return S_(a,jp,1)}(s.ca()).filter(a=>(dm(ud(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=sl(t[0],Vx,7))==null?void 0:r.j())==null?void 0:n.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=dm(ud(a,1))??""})}function PVe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function LVe(s){try{const t=new OSe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{tye(s)}}OSe.prototype.close=OSe.prototype.close;var lf=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QAe,this.A=new qpt,ui(this.h,0,3,this.A),ui(s=this.h,0,1,t=new Ud)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?zl(this.h,2,Dz(s.displayNamesLocale)):"displayNamesLocale"in s&&zl(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){GMs(this)}segment(s,t,r){const n=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:r,PVe(this),w0(this,s,n),LVe(this)}La(s,t,r,n){const a=typeof r!="function"?r:{};return this.j=typeof r=="function"?r:n,PVe(this),T1(this,s,a,t),LVe(this)}Da(){return this.u}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect");const t=new Vx;S1(t,Hpt,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),r.o(t),ny(s,r),eye(this,s),this.outputConfidenceMasks&&(ml(s,"confidence_masks"),Oo(r,"CONFIDENCE_MASKS:confidence_masks"),oP(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>cP(this,i,!0,!this.j)),_a(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],_a(this,n)})),this.outputCategoryMask&&(ml(s,"category_mask"),Oo(r,"CATEGORY_MASK:category_mask"),oP(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=cP(this,n,!1,!this.j),_a(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,_a(this,n)})),ml(s,"quality_scores"),Oo(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,_a(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};lf.prototype.getLabels=lf.prototype.Da,lf.prototype.segmentForVideo=lf.prototype.La,lf.prototype.segment=lf.prototype.segment,lf.prototype.setOptions=lf.prototype.o,lf.createFromModelPath=function(s,t){return Zo(lf,s,{baseOptions:{modelAssetPath:t}})},lf.createFromModelBuffer=function(s,t){return Zo(lf,s,{baseOptions:{modelAssetBuffer:t}})},lf.createFromOptions=function(s,t){return Zo(lf,s,t)};var FSe=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()}};FSe.prototype.close=FSe.prototype.close;var rv=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QAe,this.u=new qpt,ui(this.h,0,3,this.u),ui(s=this.h,0,1,t=new Ud)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(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 Gpt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new k_e;oj(i,3,lB(!0),!1),oj(i,1,ER(t.keypoint.x),0),oj(i,2,ER(t.keypoint.y),0),w8(n,1,ISe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new RMs;for(i of t.scribble)oj(t=new k_e,3,lB(!0),!1),oj(t,1,ER(i.x),0),oj(t,2,ER(i.y),0),AAe(o,1,k_e,t);w8(n,2,ISe,o)}}this.g.addProtoToStream(n.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",r),w0(this,s,a);e:{try{const o=new FSe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{tye(this)}l=void 0}return l}m(){var s=new Hx;xd(s,"image_in"),xd(s,"roi_in"),xd(s,"norm_rect_in");const t=new Vx;S1(t,Hpt,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Yc(r,"IMAGE:image_in"),Yc(r,"ROI:roi_in"),Yc(r,"NORM_RECT:norm_rect_in"),r.o(t),ny(s,r),eye(this,s),this.outputConfidenceMasks&&(ml(s,"confidence_masks"),Oo(r,"CONFIDENCE_MASKS:confidence_masks"),oP(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>cP(this,i,!0,!this.j)),_a(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],_a(this,n)})),this.outputCategoryMask&&(ml(s,"category_mask"),Oo(r,"CATEGORY_MASK:category_mask"),oP(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=cP(this,n,!1,!this.j),_a(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,_a(this,n)})),ml(s,"quality_scores"),Oo(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,_a(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};rv.prototype.segment=rv.prototype.segment,rv.prototype.setOptions=rv.prototype.o,rv.createFromModelPath=function(s,t){return Zo(rv,s,{baseOptions:{modelAssetPath:t}})},rv.createFromModelBuffer=function(s,t){return Zo(rv,s,{baseOptions:{modelAssetBuffer:t}})},rv.createFromOptions=function(s,t){return Zo(rv,s,t)};var yg=class extends Bx{constructor(s,t){super(new _0(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},ui(s=this.h=new Wpt,0,1,t=new Ud)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?zl(this.h,2,Dz(s.displayNamesLocale)):"displayNamesLocale"in s&&zl(this.h,2),s.maxResults!==void 0?C_(this.h,3,s.maxResults):"maxResults"in s&&zl(this.h,3),s.scoreThreshold!==void 0?Ka(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&zl(this.h,4),s.categoryAllowlist!==void 0?ife(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&zl(this.h,5),s.categoryDenylist!==void 0?ife(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&zl(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},w0(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},T1(this,s,r,t),this.j}m(){var s=new Hx;xd(s,"input_frame_gpu"),xd(s,"norm_rect"),ml(s,"detections");const t=new Vx;S1(t,OMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Yc(r,"IMAGE:input_frame_gpu"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"DETECTIONS:detections"),r.o(t),ny(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=Npt(i),this.j.detections.push(Zpt(n));_a(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{_a(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};yg.prototype.detectForVideo=yg.prototype.G,yg.prototype.detect=yg.prototype.F,yg.prototype.setOptions=yg.prototype.o,yg.createFromModelPath=async function(s,t){return Zo(yg,s,{baseOptions:{modelAssetPath:t}})},yg.createFromModelBuffer=function(s,t){return Zo(yg,s,{baseOptions:{modelAssetBuffer:t}})},yg.createFromOptions=function(s,t){return Zo(yg,s,t)};var BSe=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 DVe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function RVe(s){try{const t=new BSe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{tye(s)}}BSe.prototype.close=BSe.prototype.close;var Hp=class extends Bx{constructor(s,t){super(new _0(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,ui(s=this.h=new Kpt,0,1,t=new Ud),this.A=new Bpt,ui(this.h,0,3,this.A),this.j=new Fpt,ui(this.h,0,2,this.j),C_(this.j,4,1),Ka(this.j,2,.5),Ka(this.A,2,.5),Ka(this.h,4,.5)}get baseOptions(){return sl(this.h,Ud,1)}set baseOptions(s){ui(this.h,0,1,s)}o(s){return"numPoses"in s&&C_(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ka(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ka(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:r,DVe(this),w0(this,s,n),RVe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.u=typeof r=="function"?r:n,DVe(this),T1(this,s,a,t),RVe(this)}m(){var s=new Hx;xd(s,"image_in"),xd(s,"norm_rect"),ml(s,"normalized_landmarks"),ml(s,"world_landmarks"),ml(s,"segmentation_masks");const t=new Vx;S1(t,FMs,this.h);const r=new jp;Fx(r,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Yc(r,"IMAGE:image_in"),Yc(r,"NORM_RECT:norm_rect"),Oo(r,"NORM_LANDMARKS:normalized_landmarks"),Oo(r,"WORLD_LANDMARKS:world_landmarks"),r.o(t),ny(s,r),eye(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(n,a)=>{this.landmarks=[];for(const i of n)n=Fz(i),this.landmarks.push(Jge(n));_a(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",n=>{this.landmarks=[],_a(this,n)}),this.g.attachProtoVectorListener("world_landmarks",(n,a)=>{this.worldLandmarks=[];for(const i of n)n=RM(i),this.worldLandmarks.push(N8(n));_a(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",n=>{this.worldLandmarks=[],_a(this,n)}),this.outputSegmentationMasks&&(Oo(r,"SEGMENTATION_MASK:segmentation_masks"),oP(this,"segmentation_masks"),this.g.aa("segmentation_masks",(n,a)=>{this.segmentationMasks=n.map(i=>cP(this,i,!0,!this.u)),_a(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",n=>{this.segmentationMasks=[],_a(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Hp.prototype.detectForVideo=Hp.prototype.G,Hp.prototype.detect=Hp.prototype.F,Hp.prototype.setOptions=Hp.prototype.o,Hp.createFromModelPath=function(s,t){return Zo(Hp,s,{baseOptions:{modelAssetPath:t}})},Hp.createFromModelBuffer=function(s,t){return Zo(Hp,s,{baseOptions:{modelAssetBuffer:t}})},Hp.createFromOptions=function(s,t){return Zo(Hp,s,t)},Hp.POSE_CONNECTIONS=uxt;let n3=null,AR=null;async function WMs(){return n3||AR||(AR=(async()=>{const s=await fA.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return n3=await lf.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}),n3})(),AR)}function KMs(s,t,r,n,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+h]);const x=Math.min(m,r-1)-Math.max(h+1,0)+1;i[c+d]=o/x}}for(let l=0;l=0&&(o-=i[d*r+l]);const m=Math.min(h,n-1)-Math.max(d+1,0)+1;t[c*r+l]=o/m}}}function YMs(){n3&&(n3.close(),n3=null,AR=null)}function ZMs(s,t){const r=k.useRef(null),n=k.useRef(null),a=k.useRef(null),i=k.useRef(null),l=k.useRef(0),o=k.useRef(0),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,g]=k.useState(null),v=t.type!=="none"&&s!==null;return k.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const j=new Image;j.crossOrigin="anonymous",j.src=t.imageUrl,j.onload=()=>{i.current=j}}else i.current=null},[t.type,t.imageUrl]),k.useEffect(()=>{if(!v||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const j=document.createElement("video");return j.srcObject=s,j.muted=!0,j.playsInline=!0,j.autoplay=!0,j.play().catch(()=>{}),a.current=j,()=>{j.srcObject=null,a.current=null}},[v,s]),k.useEffect(()=>{if(!v){d(null),g(null);return}let j=!1;return(async()=>{m(!0),g(null);try{const N=await WMs();if(j)return;m(!1);const S=a.current;if(!S||(await new Promise(ge=>{if(S.videoWidth>0)return ge();S.onloadedmetadata=()=>ge(),setTimeout(ge,2e3)}),j))return;const T=S.videoWidth||640,A=S.videoHeight||480,P=r.current;if(!P)return;P.width=T,P.height=A;const D=P.getContext("2d",{willReadFrequently:!1});n.current||(n.current=document.createElement("canvas"));const B=n.current;B.width=T,B.height=A;const z=B.getContext("2d",{willReadFrequently:!0}),F=document.createElement("canvas");F.width=T,F.height=A;const $=F.getContext("2d"),X=P.captureStream(30);((s==null?void 0:s.getAudioTracks())||[]).forEach(ge=>X.addTrack(ge)),j||d(X);const Q=t.blurRadius??15,Y=t.mirror??!1,ne=new Float32Array(T*A),de=new Float32Array(T*A),ce=new Float32Array(T*A);let ae=!1;const ie=4,me=.6,oe=()=>{if(j||!a.current)return;const ge=performance.now();if(ge-o.current<30){l.current=requestAnimationFrame(oe);return}o.current=ge;const be=a.current;if(be.readyState<2){l.current=requestAnimationFrame(oe);return}try{const Me=N.segmentForVideo(be,ge).confidenceMasks;if(Me&&Me.length>0){de.fill(0);for(let $e=1;$eze?(ct=$e.height*ze,Te=($e.width-ct)/2):(ve=$e.width/ze,ye=($e.height-ve)/2),D.drawImage($e,Te,ye,ct,ve,0,0,T,A)}z.clearRect(0,0,T,A),z.drawImage(be,0,0,T,A);const Pe=z.getImageData(0,0,T,A),Ee=Pe.data;for(let $e=0;$e{j=!0,l.current&&cancelAnimationFrame(l.current),d(null)}},[v,t.type,t.blurRadius,t.imageUrl,s]),k.useEffect(()=>()=>{YMs()},[]),{canvasRef:r,compositedStream:c,isLoading:h,isActive:v,error:x}}function xL({maxDurationSeconds:s=600,onRecordingComplete:t,onError:r,onRecordingStateChange:n,className:a,teleprompterContent:i}){const l=k.useRef(null),o=k.useRef(null),c=k.useRef(null),[d,h]=k.useState(null),m=k.useRef([]),x=k.useRef(null),g=k.useRef(null),v=k.useRef(null),j=k.useRef(null),b=tL(),[N,S]=k.useState("camera"),T=k.useRef(null),A=k.useRef(null),P=k.useRef(null),D=k.useRef(null),B=k.useRef(null),z=k.useRef(null),[F,$]=k.useState(!0),[X,K]=k.useState(!0),[Q,Y]=k.useState(null),[ne,de]=k.useState(!1),[ce,ae]=k.useState(!1),[ie,me]=k.useState(null),[oe,ge]=k.useState(null),[be,Oe]=k.useState(0),[Me,Pe]=k.useState("user"),[Ee,$e]=k.useState(0),[Se,ze]=k.useState(!1),[Te,ye]=k.useState(!0),[ct,ve]=k.useState(null),[rt,Re]=k.useState(!1),[Qe,Ke]=k.useState(null),Ce=k.useRef(null),[nt,$t]=k.useState(()=>{try{const pr=localStorage.getItem("video-bg-config");if(pr)return JSON.parse(pr)}catch{}return{type:"none"}});k.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(nt))}catch{}},[nt]);const[lt,it]=k.useState([]),[Nt,Ft]=k.useState([]),[at,Ie]=k.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[et,Dt]=k.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});k.useEffect(()=>{try{localStorage.setItem("video-mic-id",at)}catch{}},[at]),k.useEffect(()=>{try{localStorage.setItem("video-cam-id",et)}catch{}},[et]),k.useEffect(()=>{var Hr,aa,Na;if(!((Hr=navigator.mediaDevices)!=null&&Hr.enumerateDevices))return;const pr=async()=>{try{const Je=await navigator.mediaDevices.enumerateDevices();it(Je.filter(Fe=>Fe.kind==="audioinput")),Ft(Je.filter(Fe=>Fe.kind==="videoinput"))}catch(Je){console.warn("[VideoRecorder] enumerateDevices failed",Je)}};return pr(),(Na=(aa=navigator.mediaDevices).addEventListener)==null||Na.call(aa,"devicechange",pr),()=>{var Je,Fe;return(Fe=(Je=navigator.mediaDevices).removeEventListener)==null?void 0:Fe.call(Je,"devicechange",pr)}},[Q]);const{canvasRef:Jt,compositedStream:cs,isLoading:Ht,isActive:dt}=ZMs(d,nt),Qt=k.useRef(r);Qt.current=r;const yt=k.useCallback(pr=>{$(pr)},[]),ss=k.useRef(F),Is=k.useCallback(()=>{P.current&&(cancelAnimationFrame(P.current),P.current=null),D.current&&(D.current.terminate(),D.current=null),T.current&&(T.current.getTracks().forEach(pr=>pr.stop()),T.current=null),B.current&&(B.current.getTracks().forEach(pr=>pr.stop()),B.current=null),z.current&&(z.current.srcObject=null,z.current=null)},[]),fs=k.useCallback(async()=>{var pr;try{const Hr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});T.current=Hr;let aa=null;try{aa=await navigator.mediaDevices.getUserMedia({video:et?{deviceId:{exact:et},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Na=null;try{Na=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...at?{deviceId:{exact:at}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Na.getAudioTracks().map(Qr=>Qr.label))}catch(Qr){console.warn("[VideoRecorder] No mic audio for screen recording",Qr);try{Na=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Je=Hr.getVideoTracks()[0],Fe=Je.getSettings(),We=Fe.width||1920,He=Fe.height||1080,bt=document.createElement("canvas");bt.width=We,bt.height=He,A.current=bt;const ut=bt.getContext("2d");let kt=null;aa&&(kt=document.createElement("video"),kt.srcObject=aa,kt.muted=!0,kt.playsInline=!0,kt.autoplay=!0,await kt.play(),z.current=kt);const Gt=document.createElement("video");Gt.srcObject=Hr,Gt.muted=!0,Gt.playsInline=!0,Gt.autoplay=!0,await Gt.play();const Mt=()=>{if(ut.drawImage(Gt,0,0,We,He),kt&&kt.readyState>=2){const Qr=Math.round(We*.2),$s=Math.round(Qr*(kt.videoHeight/kt.videoWidth||.75)),Kr=We-Qr-20,In=He-$s-20,Ja=12;ut.save(),ut.beginPath(),ut.moveTo(Kr+Ja,In),ut.lineTo(Kr+Qr-Ja,In),ut.quadraticCurveTo(Kr+Qr,In,Kr+Qr,In+Ja),ut.lineTo(Kr+Qr,In+$s-Ja),ut.quadraticCurveTo(Kr+Qr,In+$s,Kr+Qr-Ja,In+$s),ut.lineTo(Kr+Ja,In+$s),ut.quadraticCurveTo(Kr,In+$s,Kr,In+$s-Ja),ut.lineTo(Kr,In+Ja),ut.quadraticCurveTo(Kr,In,Kr+Ja,In),ut.closePath(),ut.clip(),ut.translate(Kr+Qr,In),ut.scale(-1,1),ut.drawImage(kt,0,0,Qr,$s),ut.restore(),ut.strokeStyle="rgba(255,255,255,0.6)",ut.lineWidth=2,ut.beginPath(),ut.moveTo(Kr+Ja,In),ut.lineTo(Kr+Qr-Ja,In),ut.quadraticCurveTo(Kr+Qr,In,Kr+Qr,In+Ja),ut.lineTo(Kr+Qr,In+$s-Ja),ut.quadraticCurveTo(Kr+Qr,In+$s,Kr+Qr-Ja,In+$s),ut.lineTo(Kr+Ja,In+$s),ut.quadraticCurveTo(Kr,In+$s,Kr,In+$s-Ja),ut.lineTo(Kr,In+Ja),ut.quadraticCurveTo(Kr,In,Kr+Ja,In),ut.closePath(),ut.stroke()}},Kt="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}}",Es=new Blob([Kt],{type:"application/javascript"}),Ls=new Worker(URL.createObjectURL(Es));D.current=Ls,Ls.onmessage=()=>Mt(),Ls.postMessage({type:"start",fps:30}),Mt();const gr=bt.captureStream(30),qr=[],Xr=Hr.getAudioTracks();Xr.length&&qr.push(...Xr),Na&&qr.push(...Na.getAudioTracks());const Yn=new MediaStream([...gr.getVideoTracks(),...qr]);return B.current=Yn,Je.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Is()},Yn}catch(Hr){return console.error("[VideoRecorder] Screen capture error:",Hr),Hr.name!=="NotAllowedError"&&((pr=Qt.current)==null||pr.call(Qt,"Failed to start screen capture: "+(Hr.message||"Unknown error"))),null}},[Is]),ar=k.useCallback(async()=>{var Hr,aa;K(!0),ve(null);const pr=b&&F;console.log("[VideoRecorder] initCamera start",{isMobile:b,usePortraitMode:F,shouldBePortrait:pr,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(ut=>ut.stop()));const Na=b&&pr?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Je=et?{...Na,deviceId:{exact:et}}:{...Na,facingMode:{ideal:Me}},Fe={echoCancellation:!0,noiseSuppression:!0,...at?{deviceId:{exact:at}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Je);const We=await navigator.mediaDevices.getUserMedia({video:Je,audio:Fe});if(console.log("[VideoRecorder] getUserMedia success"),We.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=We,h(We),Y(!0);const bt=We.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",bt.width,"x",bt.height),l.current){const ut=l.current;ut.srcObject=We,ut.muted=!0,ut.playsInline=!0,ut.autoplay=!0,ut.setAttribute("muted",""),ut.setAttribute("playsinline",""),ut.setAttribute("autoplay","");try{(Hr=ut.load)==null||Hr.call(ut)}catch(Gt){console.warn("[VideoRecorder] videoEl.load failed",Gt)}const kt=async()=>{try{return await ut.play(),console.log("[VideoRecorder] preview play ok"),Re(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:ut.readyState,videoWidth:ut.videoWidth,videoHeight:ut.videoHeight})},300),!0}catch(Gt){return console.warn("[VideoRecorder] preview play blocked",Gt),Re(!0),!1}};await new Promise(Gt=>{let Mt=!1;const Kt=()=>{Mt||(Mt=!0,Gt())},Es=()=>{kt().finally(Kt)};ut.onloadedmetadata=Es,ut.onloadeddata=Es,setTimeout(Kt,1500)})}try{g.current=new AudioContext;const ut=g.current.createMediaStreamSource(We);v.current=g.current.createAnalyser(),v.current.fftSize=256,ut.connect(v.current);const kt=()=>{if(v.current){const Gt=new Uint8Array(v.current.frequencyBinCount);v.current.getByteFrequencyData(Gt);const Mt=Gt.reduce((Kt,Es)=>Kt+Es)/Gt.length;$e(Math.min(100,Mt/128*100))}j.current=requestAnimationFrame(kt)};kt()}catch(ut){console.warn("Audio context not available:",ut)}}catch(Na){console.error("Camera initialization error:",Na),Y(!1);let Je="Failed to access camera or microphone.";Na.name==="NotAllowedError"?Je="Camera permission denied. Please allow camera access in your browser settings.":Na.name==="NotFoundError"?Je="No camera found. Please connect a camera and try again.":Na.name==="NotReadableError"?Je="Camera is in use by another application. Please close other apps using the camera.":Na.message&&(Je=Na.message),ve(Je),(aa=Qt.current)==null||aa.call(Qt,Je)}finally{K(!1)}},[Me,b,F,at,et]);k.useEffect(()=>{ss.current!==F&&Q&&!ne&&!oe&&(ss.current=F,ar())},[F,Q,ne,oe,ar]),k.useEffect(()=>(ar(),()=>{c.current&&c.current.getTracks().forEach(pr=>pr.stop()),x.current&&clearInterval(x.current),j.current&&cancelAnimationFrame(j.current),g.current&&g.current.close(),Ce.current&&clearInterval(Ce.current),oe&&URL.revokeObjectURL(oe),Is()}),[ar,oe]),k.useEffect(()=>{if(X||Q!==!0||oe)return;const pr=c.current,Hr=l.current;!pr||!Hr||dt||(Hr.srcObject!==pr&&(Hr.srcObject=pr,Hr.muted=!0,Hr.playsInline=!0,Hr.autoplay=!0,Hr.setAttribute("muted",""),Hr.setAttribute("playsinline",""),Hr.setAttribute("autoplay","")),Hr.play().then(()=>Re(!1)).catch(aa=>{Re(!0),console.warn("Live preview play blocked on mount:",aa)}))},[Q,X,oe,dt]),k.useEffect(()=>{n==null||n(ne)},[ne,n]);const Er=k.useCallback(async()=>{if(oe)return;const pr=l.current;if(pr)try{await pr.play(),Re(!1)}catch(Hr){Re(!0),console.warn("Live preview still blocked (needs user gesture):",Hr)}},[oe]),Tr=k.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),x.current&&(clearInterval(x.current),x.current=null),Is(),de(!1),ae(!1)},[Is]),Lr=k.useCallback(async()=>{let pr=null;if(N==="screen"){if(pr=await fs(),!pr)return}else pr=dt&&cs?cs:c.current;if(!pr)return;Er(),m.current=[],Oe(0);const aa=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Je=>MediaRecorder.isTypeSupported(Je)),Na=new MediaRecorder(pr,aa?{mimeType:aa,videoBitsPerSecond:N==="screen"?4e6:25e5}:{videoBitsPerSecond:N==="screen"?4e6:25e5});Na.ondataavailable=Je=>{Je.data.size>0&&m.current.push(Je.data)},Na.onstop=()=>{var He;const Je=Na.mimeType||aa||((He=m.current[0])==null?void 0:He.type)||"video/webm",Fe=new Blob(m.current,{type:Je});me(Fe);const We=URL.createObjectURL(Fe);ge(We)},o.current=Na,Na.start(100),de(!0),x.current=setInterval(()=>{Oe(Je=>Je>=s-1?(Tr(),s):Je+1)},1e3)},[Er,s,Tr,dt,cs,N,fs]),$r=k.useCallback(()=>{Ce.current&&(clearInterval(Ce.current),Ce.current=null),Ke(3);let pr=3;Ce.current=setInterval(()=>{pr-=1,pr<=0?(Ce.current&&clearInterval(Ce.current),Ce.current=null,Ke(null),Lr()):Ke(pr)},1e3)},[Lr]),kr=k.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ae(!0),x.current&&clearInterval(x.current))},[]),Sr=k.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ae(!1),x.current=setInterval(()=>{Oe(pr=>pr>=s-1?(Tr(),s):pr+1)},1e3))},[s,Tr]),hn=k.useCallback(()=>{oe&&URL.revokeObjectURL(oe),me(null),ge(null),Oe(0),ze(!1),ye(!0),l.current&&c.current&&!dt&&(l.current.srcObject=c.current,l.current.muted=!0,Er())},[Er,oe,dt]),zn=k.useCallback(()=>{Pe(pr=>pr==="user"?"environment":"user")},[]),Xs=k.useCallback(()=>{ie&&t(ie,be)},[ie,be,t]),Ur=k.useCallback(()=>{l.current&&oe&&(Se?l.current.pause():(ye(!1),l.current.muted=!1,l.current.play()),ze(!Se))},[oe,Se]);k.useEffect(()=>{if(!oe)return;const pr=l.current;if(!pr)return;ye(!1),pr.pause(),pr.removeAttribute("src"),pr.srcObject=null,pr.load(),pr.src=oe,pr.currentTime=0,pr.playsInline=!0,pr.muted=!1,pr.onended=()=>ze(!1);const Hr=()=>{var Je;const aa=pr.error,Na=aa?`Recorded video failed to play (code ${aa.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",aa),(Je=Qt.current)==null||Je.call(Qt,Na)};return pr.addEventListener("error",Hr),pr.load(),()=>{pr.removeEventListener("error",Hr)}},[oe]);const xn=pr=>{const Hr=Math.floor(pr/60),aa=pr%60;return`${Hr}:${aa.toString().padStart(2,"0")}`},us=N==="screen"?"aspect-video":b&&F?"aspect-[9/16]":"aspect-video";return X?e.jsx("div",{className:Bt("flex items-center justify-center bg-black rounded-lg",us,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:Bt("flex items-center justify-center bg-black rounded-lg",us,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Hi,{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:ct||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(G,{onClick:()=>ar(),variant:"secondary",className:"w-full",children:[e.jsx(Di,{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:Bt("flex flex-col gap-2",a),children:[!ne&&!oe&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(G,{variant:N==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>S("camera"),children:[e.jsx(pp,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(G,{variant:N==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>S("screen"),children:[e.jsx(O3,{className:"h-4 w-4"}),"Screen"]})]}),N==="camera"&&!ne&&!oe&&e.jsx(cAs,{value:nt,onChange:$t,isLoading:Ht,disabled:ne}),!ne&&!oe&&(lt.length>0||Nt.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[lt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(R3,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(zs,{value:at||"default",onValueChange:pr=>Ie(pr==="default"?"":pr),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{placeholder:"Default microphone"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"default",children:"Default microphone"}),lt.map(pr=>e.jsx(mt,{value:pr.deviceId,children:pr.label||`Microphone ${pr.deviceId.slice(0,6)}`},pr.deviceId))]})]})]}),Nt.length>1&&N==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(pp,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(zs,{value:et||"default",onValueChange:pr=>Dt(pr==="default"?"":pr),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{placeholder:"Default camera"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"default",children:"Default camera"}),Nt.map(pr=>e.jsx(mt,{value:pr.deviceId,children:pr.label||`Camera ${pr.deviceId.slice(0,6)}`},pr.deviceId))]})]})]})]}),N==="camera"&&b&&!ne&&!oe&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(Zj,{className:Bt("h-4 w-4",F?"text-muted-foreground":"text-primary")}),e.jsx(he,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(br,{id:"orientation-toggle",checked:F,onCheckedChange:yt}),e.jsx(he,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(zg,{className:Bt("h-4 w-4",F?"text-primary":"text-muted-foreground")})]}),N==="screen"&&!ne&&!oe&&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(O3,{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:Bt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Er()},children:[e.jsx("video",{ref:l,src:oe??void 0,className:Bt("w-full bg-black",F&&!oe?"object-contain":"object-cover",us,!oe&&Me==="user"!==(nt.mirror??!1)&&"scale-x-[-1]",dt&&!oe&&"hidden"),playsInline:!0,controls:!!oe,muted:oe?Te:!0,autoPlay:!oe},oe??"live"),dt&&!oe&&e.jsx("canvas",{ref:Jt,className:Bt("w-full bg-black",F?"object-contain":"object-cover",us,Me==="user"!==(nt.mirror??!1)&&"scale-x-[-1]")}),dt&&Ht&&!oe&&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…"})]})}),!oe&&rt&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(G,{type:"button",variant:"secondary",onClick:()=>void Er(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!oe&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Qe!==null&&!oe&&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:Qe},Qe),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),ne&&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:Bt("w-3 h-3 rounded-full",ce?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[xn(be)," / ",xn(s)]})]}),ne&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ri,{value:be/s*100,className:"h-1 rounded-none"})}),!oe&&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(R3,{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:`${Ee}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:oe?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:hn,children:[e.jsx(Di,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Ur,children:Se?e.jsx(cm,{className:"h-5 w-5"}):e.jsx(Ho,{className:"h-5 w-5"})}),e.jsxs(G,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Xs,children:[e.jsx(Hn,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[N==="camera"?e.jsx(G,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:zn,disabled:ne||Qe!==null,children:e.jsx(Wv,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!ne&&Qe===null?e.jsx(G,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:N==="screen"?Lr:$r,children:N==="screen"?e.jsx(O3,{className:"h-6 w-6"}):e.jsx(sn,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ce?Sr:kr,children:ce?e.jsx(Ho,{className:"h-5 w-5"}):e.jsx(cm,{className:"h-5 w-5"})}),e.jsx(G,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Tr,children:e.jsx($g,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}const hxt="teleprompter_settings",C_e={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function XMs(){try{const s=localStorage.getItem(hxt);return s?{...C_e,...JSON.parse(s)}:C_e}catch{return C_e}}function QMs(s){try{localStorage.setItem(hxt,JSON.stringify(s))}catch{}}function cMe({text:s,isVisible:t,onToggleVisibility:r,isRecording:n=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=k.useRef(null),c=k.useRef(null),d=k.useRef(0),h=k.useRef(0),[m,x]=k.useState(XMs),{scrollSpeed:g,fontSize:v,lineHeight:j,opacity:b,position:N,isMirrored:S}=m,T=k.useCallback((K,Q)=>{x(Y=>{const ne={...Y,[K]:Q};return QMs(ne),ne})},[]),[A,P]=k.useState(!1),[D,B]=k.useState(null),z=k.useCallback(K=>{if(!o.current)return;d.current===0&&(d.current=K);const Q=K-d.current;d.current=K,h.current+=g*Q/1e3;const Y=Math.floor(h.current);Y>0&&(o.current.scrollTop+=Y,h.current-=Y);const{scrollTop:ne,scrollHeight:de,clientHeight:ce}=o.current;if(ne+ce>=de){P(!1);return}c.current=requestAnimationFrame(z)},[g]);k.useEffect(()=>(A?(d.current=0,h.current=0,c.current=requestAnimationFrame(z)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,z]),k.useEffect(()=>{if(n&&t)if(o.current&&(o.current.scrollTop=0),a){B(3);let K=3;const Q=setInterval(()=>{K-=1,K<=0?(clearInterval(Q),B(null),i==null||i(),P(!0)):B(K)},1e3);return()=>clearInterval(Q)}else setTimeout(()=>P(!0),100);else n||(P(!1),B(null))},[n,t,a,i]);const F=k.useCallback(()=>{o.current&&(o.current.scrollTop=0),P(!1)},[]),$=k.useCallback(()=>{P(K=>!K)},[]);if(!t)return e.jsx("div",{className:Bt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(G,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const X={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Bt("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:Bt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",X[N],D!==null&&"opacity-30"),style:{opacity:D!==null?.3:b},children:e.jsxs("div",{ref:o,className:Bt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",S&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${v}px`,lineHeight:j,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(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsx(G,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(lo,{className:"h-4 w-4"})})}),e.jsx(wo,{className:"w-72",side:"left",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Teleprompter Settings"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g})]}),e.jsx(Xy,{value:[g],onValueChange:([K])=>T("scrollSpeed",K),min:1,max:100,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v,"px"]})]}),e.jsx(Xy,{value:[v],onValueChange:([K])=>T("fontSize",K),min:16,max:48,step:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:j.toFixed(1)})]}),e.jsx(Xy,{value:[j*10],onValueChange:([K])=>T("lineHeight",K/10),min:12,max:24,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(b*100),"%"]})]}),e.jsx(Xy,{value:[b*100],onValueChange:([K])=>T("opacity",K/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:N==="top"?"default":"outline",size:"sm",onClick:()=>T("position","top"),children:e.jsx(xp,{className:"h-4 w-4"})}),e.jsx(G,{variant:N==="center"?"default":"outline",size:"sm",onClick:()=>T("position","center"),children:e.jsx(qv,{className:"h-4 w-4"})}),e.jsx(G,{variant:N==="bottom"?"default":"outline",size:"sm",onClick:()=>T("position","bottom"),children:e.jsx(so,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Mirror Mode"}),e.jsx(br,{checked:S,onCheckedChange:K=>T("isMirrored",K)})]})]})})]}),e.jsx(G,{variant:"secondary",size:"icon",onClick:$,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(cm,{className:"h-4 w-4"}):e.jsx(Ho,{className:"h-4 w-4"})}),e.jsx(G,{variant:"secondary",size:"icon",onClick:F,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Wv,{className:"h-4 w-4"})}),e.jsxs(G,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(am,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function JMs({onSelectScript:s,onCreateNew:t,selectedScriptId:r,className:n}){const{toast:a}=Ea(),[i,l]=k.useState(""),[o,c]=k.useState(null),[d,h]=k.useState("levelup"),{data:m,isLoading:x}=Q5s(),{data:g,isLoading:v}=J5s(),{data:j,isLoading:b}=eTs(),N=tTs(),S=k.useMemo(()=>g?g.filter(B=>{const z=!i||B.title.toLowerCase().includes(i.toLowerCase())||B.script_text.toLowerCase().includes(i.toLowerCase())||B.tags.some($=>$.toLowerCase().includes(i.toLowerCase())),F=!o||B.category_id===o;return z&&F}):[],[g,i,o]),T=k.useMemo(()=>j?j.filter(B=>!i||B.title.toLowerCase().includes(i.toLowerCase())||B.script_text.toLowerCase().includes(i.toLowerCase())):[],[j,i]),A=B=>{s({title:B.title,text:B.script_text})},P=async B=>{try{await N.mutateAsync(B),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},D=x||v||b;return e.jsxs("div",{className:Bt("flex flex-col h-full",n),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search scripts...",value:i,onChange:B=>l(B.target.value),className:"pl-9"})]})}),e.jsxs(Rn,{value:d,onValueChange:B=>h(B),className:"flex-1 flex flex-col",children:[e.jsxs(Dn,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Xt,{value:"levelup",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Xt,{value:"my-scripts",children:[e.jsx(Bg,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(as,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx(Ge,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),m==null?void 0:m.map(B=>e.jsx(Ge,{variant:o===B.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(B.id),children:B.name},B.id))]}),e.jsx(ti,{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"})}):S.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:S.map(B=>e.jsxs(Ne,{className:Bt("cursor-pointer hover:bg-accent/50 transition-colors",r===B.id&&"ring-2 ring-primary"),onClick:()=>A(B),children:[e.jsx(Ot,{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(zt,{className:"text-sm font-medium truncate",children:B.title}),B.category&&e.jsx(Ge,{variant:"secondary",className:"mt-1 text-xs",children:B.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:z=>{z.stopPropagation(),P(B)},children:e.jsx(Bg,{className:"h-4 w-4"})}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(De,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:B.script_text})})]},B.id))})})]}),e.jsxs(as,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(G,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(ti,{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"})}):T.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bg,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No saved scripts"}),e.jsx("p",{className:"text-sm mt-1",children:"Save LevelUp scripts or create your own"})]}):e.jsx("div",{className:"space-y-2",children:T.map(B=>e.jsxs(Ne,{className:Bt("cursor-pointer hover:bg-accent/50 transition-colors",r===B.id&&"ring-2 ring-primary"),onClick:()=>A(B),children:[e.jsx(Ot,{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(zt,{className:"text-sm font-medium truncate",children:B.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:B.is_custom?e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(De,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:B.script_text})})]},B.id))})})]})]})]})}function eIs({selectedTemplate:s,onSelect:t,contactName:r,saving:n=!1}){const[a,i]=k.useState(()=>{const o=kM(s);return new Set([o.category])}),l=o=>{i(c=>{const d=new Set(c);return d.has(o)?d.delete(o):d.add(o),d})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Share Page Template"}),n&&e.jsx(ls,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:n$t.map(o=>{const c=a$t(o.id),d=a.has(o.id),h=c.some(m=>m.id===s);return e.jsxs(bx,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(_x,{className:"flex items-center justify-between w-full p-2.5 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:o.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",c.length,")"]}),h&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(so,{className:Bt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(wx,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(m=>{const x=s===m.id;return e.jsxs("button",{type:"button",onClick:()=>t(m.id),disabled:n,className:Bt("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",x?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[x&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:e.jsx(Hn,{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: "',kM(s).headerText(r),'"']})]})}function mxt({open:s,onOpenChange:t,video:r,contactName:n,onTemplateUpdated:a}){const[i,l]=k.useState(r.page_template||"default"),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState(r.page_template||"default"),[g,v]=k.useState([]),[j,b]=k.useState(r.contact_id&&n?{id:r.contact_id,name:n,email:null}:null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),P=r.share_token?`https://video.relevelup.com/${r.share_token}`:"";k.useEffect(()=>{s&&g.length===0&&D()},[s]);const D=async()=>{A(!0);try{const{data:ne,error:de}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(de)throw de;const ce=(ne||[]).map(ae=>({id:ae.id,name:[ae.first_name,ae.last_name].filter(Boolean).join(" ")||"Unnamed",email:ae.email||null}));v(ce)}catch(ne){console.error("Failed to fetch contacts:",ne)}finally{A(!1)}},B=async ne=>{b(ne),S(!1),c(!0);try{const{error:de}=await H.from("agent_videos").update({contact_id:(ne==null?void 0:ne.id)||null,recipient_name:(ne==null?void 0:ne.name)||null}).eq("id",r.id);if(de)throw de;ue.success(ne?`Assigned to ${ne.name}`:"Contact removed"),a==null||a()}catch(de){console.error("Failed to update contact:",de),ue.error("Failed to update contact")}finally{c(!1)}},z=async ne=>{l(ne),c(!0);try{const{error:de}=await H.from("agent_videos").update({page_template:ne}).eq("id",r.id);if(de)throw de;x(ne),ue.success("Template saved!"),a==null||a()}catch(de){console.error("Failed to save template:",de),ue.error("Failed to save template"),l(m)}finally{c(!1)}},F=(j==null?void 0:j.name)||null,$=()=>{const ne=r.title||"Video Message",de=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:r.thumbnail_url||"";return``},X=async()=>{if(!r.thumbnail_url){ue.error("Video thumbnail not available yet");return}const ne=$(),de=`Watch: ${r.title||"Video Message"} ${P}`;try{const ce=new Blob([ne],{type:"text/html"}),ae=new Blob([de],{type:"text/plain"}),ie=new ClipboardItem({"text/html":ce,"text/plain":ae});await navigator.clipboard.write([ie]),ue.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(de+` `+ne),ue.success("Copied! Paste into your email.")}},K=async()=>{await navigator.clipboard.writeText(P),h(!0),ue.success("Share link copied!"),setTimeout(()=>h(!1),2e3)},Q=()=>{const de=kM(i).headerText(F),ce=i==="default"?`Check out this video: ${P}`:`${de} Check out this special video: ${P}`;window.open(`sms:?body=${encodeURIComponent(ce)}`,"_self")},Y=()=>{const ne=kM(i),de=ne.headerText(F),ce=i==="default"?r.title||"Video Message":de,ae=`${ne.subText} Watch the video: ${P}`,ie=j!=null&&j.email?encodeURIComponent(j.email):"";window.open(`mailto:${ie}?subject=${encodeURIComponent(ce)}&body=${encodeURIComponent(ae)}`,"_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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Fr,{children:"Choose a themed page template and share your video"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ao,{open:N,onOpenChange:S,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":N,className:"flex-1 justify-between",disabled:o,children:[j?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Bi,{className:"h-4 w-4 text-muted-foreground"}),j.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search contacts..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:T?"Loading...":"No contacts found."}),e.jsx(Rx,{children:g.map(ne=>e.jsxs(vf,{value:ne.name,onSelect:()=>B(ne),children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",(j==null?void 0:j.id)===ne.id?"opacity-100":"opacity-0")}),ne.name]},ne.id))})]})]})})]}),j&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>B(null),disabled:o,className:"shrink-0",children:e.jsx(_r,{className:"h-4 w-4"})})]}),j&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',kM(i).headerText(j.name),'"']})]}),e.jsx(eIs,{selectedTemplate:i,onSelect:z,contactName:F,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:P,readOnly:!0,className:"font-mono text-sm"}),e.jsx(G,{onClick:K,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy"]})})]})]}),r.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share for Email"}),e.jsxs(G,{variant:"outline",className:"w-full gap-2",onClick:X,children:[e.jsx(fl,{className:"h-4 w-4"}),"Copy with Thumbnail (for Gmail)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Gmail to embed a clickable video thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",className:"flex-1 gap-2",onClick:Q,children:[e.jsx(bi,{className:"h-4 w-4"}),"Text"]}),e.jsxs(G,{variant:"outline",className:"flex-1 gap-2",onClick:Y,children:[e.jsx(Qs,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(on,{children:e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function tIs(){var Qe;const s=vr(),[t]=Lc(),{toast:r}=Ea(),n=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c}=Bmt(),{data:d}=$m(),h=O_(),m=iTs(),[x,g]=k.useState("record"),[v,j]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),[A,P]=k.useState(!1),[D,B]=k.useState(null),[z,F]=k.useState(0),[$,X]=k.useState(0),[K,Q]=k.useState(null),[Y,ne]=k.useState(null),[de,ce]=k.useState(n||""),[ae,ie]=k.useState(""),[me,oe]=k.useState(""),[ge,be]=k.useState(null),[Oe,Me]=k.useState(null),[Pe,Ee]=k.useState(null),[$e,Se]=k.useState(!1),ze=k.useCallback(async(Ke,Ce)=>{B(Ke),g("uploading");try{const{videoId:nt,uploadUrl:$t}=await sT(ae||"Quick Video Touch");Q(nt);const{apiKey:lt}=await rT(nt),it=new XMLHttpRequest;it.upload.onprogress=Ie=>{Ie.lengthComputable&&F(Ie.loaded/Ie.total*100)},await new Promise((Ie,et)=>{it.onload=()=>{it.status>=200&&it.status<300?Ie():et(new Error(`Upload failed: ${it.status}`))},it.onerror=()=>et(new Error("Upload failed")),it.open("PUT",$t),it.setRequestHeader("AccessKey",lt),it.send(Ke)}),g("processing");let Nt=0;const Ft=Date.now(),at=90*1e3;for(;Nt<4;){if(await new Promise(et=>setTimeout(et,3e3)),Date.now()-Ft>at){const et=Ke.size/1048576,Dt=`https://iframe.mediadelivery.net/play/${nt}/${nt}`;await h.mutateAsync({bunny_video_id:nt,playback_url:Dt,file_size_mb:et,title:ae||"Quick Video Touch",notes:me||void 0,contact_id:de&&de!=="none"?de: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 Ie=await u1(nt);if(Nt=Ie.status,X(Ie.encodeProgress||0),Nt===4)ne({playbackUrl:Ie.directPlayUrl,thumbnailUrl:Ie.thumbnailUrl,previewUrl:Ie.previewUrl||null,duration:Ie.length||Ce,fileSizeMb:(Ie.storageSize||Ke.size)/(1024*1024)});else if(Nt===5||Nt===6)throw new Error("Video processing failed")}g("details")}catch(nt){console.error("Upload error:",nt),r({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),g("record")}},[ae,r]),Te=async()=>{if(!(!K||!Y))try{const Ke=de&&de!=="none"?de:null,Ce=await h.mutateAsync({bunny_video_id:K,contact_id:Ke,playback_url:Y.playbackUrl,thumbnail_url:Y.thumbnailUrl,preview_url:Y.previewUrl,duration_seconds:Y.duration,file_size_mb:Y.fileSizeMb,title:ae||"Quick Video Touch",notes:me,task_id:a||null,status:"ready"});be(Ce.id),Me(Ce.share_token||null),Ke&&await m.mutateAsync({contactId:Ke,videoId:Ce.id,notes:me}),r({title:"Video saved successfully!"}),g("share")}catch(Ke){console.error("Save video error:",Ke),r({title:"Failed to save video",description:(Ke==null?void 0:Ke.message)||"Please try again.",variant:"destructive"})}},ye=(Ke,Ce)=>{navigator.clipboard.writeText(Ce),Ee(Ke),setTimeout(()=>Ee(null),2e3),r({title:"Copied to clipboard!"})},ct=()=>Oe?`https://video.relevelup.com/${Oe}`:(Y==null?void 0:Y.playbackUrl)||"",ve=()=>{const Ke=d==null?void 0:d.find(it=>it.id===de),Ce=Ke?`${Ke.first_name}`:"",nt=(Ke==null?void 0:Ke.phone)||"",$t=(Ke==null?void 0:Ke.email)||"",lt=ct();return{text:`Hey${Ce?` ${Ce}`:""}! I recorded a quick video for you: ${lt}`,link:lt,contactPhone:nt,contactEmail:$t}},rt=()=>{const{text:Ke,contactPhone:Ce}=ve(),nt=Ce?`sms:${Ce}?body=${encodeURIComponent(Ke)}`:`sms:?body=${encodeURIComponent(Ke)}`;window.open(nt,"_self")},Re=()=>{const{link:Ke,contactEmail:Ce}=ve(),nt="Check out this video",$t=`I recorded a quick video for you: ${Ke}`,lt=Ce?`mailto:${Ce}?subject=${encodeURIComponent(nt)}&body=${encodeURIComponent($t)}`:`mailto:?subject=${encodeURIComponent(nt)}&body=${encodeURIComponent($t)}`;window.open(lt,"_self")};return i?e.jsx(_s,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(ln,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),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(xL,{maxDurationSeconds:600,onRecordingComplete:ze,onRecordingStateChange:P,className:"w-full",teleprompterContent:b&&v&&e.jsx(cMe,{text:v,isVisible:b,onToggleVisibility:()=>N(!1),isRecording:A,startCountdown:!1})}),!b&&v&&e.jsxs(G,{variant:"outline",className:"mt-4",onClick:()=>N(!0),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(Ne,{className:"lg:col-span-1",children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(ur,{placeholder:"Type or paste your script here...",value:v,onChange:Ke=>j(Ke.target.value),rows:6}),e.jsxs(G2,{open:S,onOpenChange:T,children:[e.jsx(C3e,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"w-full",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(I_,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(W2,{className:"p-4 border-b",children:e.jsx(K2,{children:"Select a Script"})}),e.jsx(JMs,{onSelectScript:Ke=>{j(Ke.text),T(!1),N(!0)},className:"h-[calc(100vh-80px)]"})]})]}),v&&e.jsx(G,{className:"w-full",onClick:()=>N(!0),children:"Use Script"})]})]})]}),x==="uploading"&&e.jsx(Ne,{className:"max-w-md mx-auto",children:e.jsxs(De,{className:"pt-6 text-center",children:[e.jsx(oa,{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(ri,{value:z,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[z.toFixed(0),"%"]})]})}),x==="processing"&&e.jsx(Ne,{className:"max-w-md mx-auto",children:e.jsxs(De,{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(ri,{value:$,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[$.toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`This usually takes 30-60 seconds. If it takes longer, we'll auto-save your video and you can find it in your Video Library — look for the "processing" badge.`})]})}),x==="details"&&e.jsxs(Ne,{className:"max-w-lg mx-auto",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Video Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:ae,onChange:Ke=>ie(Ke.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Attach to Contact (Optional)"}),e.jsxs(zs,{value:de,onValueChange:ce,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"No contact - use anywhere"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(xo,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),d==null?void 0:d.map(Ke=>e.jsx(mt,{value:Ke.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bi,{className:"h-4 w-4"}),Ke.first_name," ",Ke.last_name]})},Ke.id))]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(ur,{value:me,onChange:Ke=>oe(Ke.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(G,{className:"w-full",onClick:Te,disabled:h.isPending,children:[h.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),x==="share"&&e.jsxs(Ne,{className:"max-w-lg mx-auto",children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Hn,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs(G,{variant:"outline",className:"justify-start",onClick:rt,children:[e.jsx(bi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:Re,children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:()=>ye("link",ve().link),children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Pe==="link"&&e.jsx(Hn,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:()=>Se(!0),children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(G,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(G,{onClick:()=>{g("record"),B(null),Q(null),ne(null)},children:"Record Another"})]})]})]}),ge&&Oe&&e.jsx(mxt,{open:$e,onOpenChange:Se,video:{id:ge,share_token:Oe,title:ae||null,contact_id:de||null,thumbnail_url:(Y==null?void 0:Y.thumbnailUrl)||null},contactName:((Qe=d==null?void 0:d.find(Ke=>Ke.id===de))==null?void 0:Qe.first_name)||null})]})}):e.jsx(_s,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(od,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),e.jsx(G,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function sIs({open:s,onOpenChange:t,video:r,gmailEmail:n,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=k.useState([]),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,P]=k.useState(!1),D=Pmt(),B=r.share_token?`https://video.relevelup.com/share/video/${r.share_token}`:"",z=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:a||r.thumbnail_url||"",F=r.title||"Video Message";k.useEffect(()=>{s&&l.length===0&&$()},[s]),k.useEffect(()=>{if(s&&(N(`I recorded a video for you — ${F}`),T("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),j(""),r.contact_id)){const de=l.find(ce=>ce.id===r.contact_id);de&&(d(de),j(de.email||""))}},[s,r.contact_id,l]);const $=async()=>{g(!0);try{const{data:de,error:ce}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ce)throw ce;o(de||[])}catch{console.error("Failed to fetch contacts")}finally{g(!1)}},X=de=>{d(de),m(!1),j(de.email||""),T(`Hey ${de.first_name}! I recorded a quick video just for you. Click below to watch it:`),N(`I recorded a video for you — ${F}`)},K=()=>{d(null),j(""),T("Hey! I recorded a quick video just for you. Click below to watch it:")},Q=de=>`${de.first_name} ${de.last_name||""}`.trim(),Y=de=>{const ce=S.split(/\n\n+/).map(me=>`

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

`).join(""),ae=de?Dmt(de):B,ie=de?``:"";return`
${ce}

▶ Watch Video

${ie}
`},ne=async()=>{var de;if(!v){ue.error("Please enter a recipient email");return}if(!B){ue.error("Video does not have a share link");return}P(!0);try{let ce;try{const ge=c?Q(c):v.split("@")[0];ce=(await D.mutateAsync({video_id:r.id,recipient_email:v,recipient_name:ge,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ge){console.warn("Failed to create tracking record, sending without tracking:",ge)}const ae=Y(ce),{data:ie,error:me}=await H.functions.invoke("gmail-send",{body:{to:v,subject:b,body:ae,contactId:(c==null?void 0:c.id)||null}});let oe=null;if(me&&((de=me.context)!=null&&de.json))try{oe=await me.context.json()}catch{}if((oe==null?void 0:oe.error)==="insufficient_scope"||(ie==null?void 0:ie.error)==="insufficient_scope"){ue.error((oe==null?void 0:oe.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(me)throw new Error((oe==null?void 0:oe.message)||me.message);if(!(ie!=null&&ie.success))throw new Error((ie==null?void 0:ie.error)||"Failed to send");ue.success("Video email sent!"),t(!1),i==null||i()}catch(ce){console.error("Gmail send error:",ce),ue.error("Failed to send: "+(ce instanceof Error?ce.message:"Unknown error"))}finally{P(!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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),n&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:n})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ao,{open:h,onOpenChange:m,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Bi,{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(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search contacts..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:x?"Loading...":"No contacts found."}),e.jsx(Rx,{children:l.filter(de=>de.email).map(de=>e.jsxs(vf,{value:`${de.first_name} ${de.last_name||""} ${de.email||""}`,onSelect:()=>X(de),children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",(c==null?void 0:c.id)===de.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Q(de)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:de.email})]})]},de.id))})]})]})})]}),c&&e.jsx(G,{variant:"ghost",size:"icon",onClick:K,className:"shrink-0",children:e.jsx(_r,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(ke,{id:"video-to",value:v,onChange:de=>j(de.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-subject",children:"Subject"}),e.jsx(ke,{id:"video-subject",value:b,onChange:de=>N(de.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(ur,{id:"video-message",value:S,onChange:de=>T(de.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Video Preview (embedded in email)"}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black",style:{maxWidth:320},children:[z?e.jsx("img",{src:z,alt:F,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(Ho,{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(Ho,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(G,{onClick:ne,disabled:A||!v||!b,className:"gap-2",children:[A?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const rIs=()=>{const{user:s}=As();return gt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.rpc("get_team_videos",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})};function nIs({recipient:s}){return s.watched_at?e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Ho,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Ge,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(tm,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Ge,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(jn,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function aIs({open:s,onOpenChange:t,videoId:r,videoTitle:n}){const{data:a=[],isLoading:i}=D5s(r);return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(ao,{className:"h-5 w-5"}),"Send Analytics: ",n]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Vs,{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(ti,{className:"h-[400px]",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Recipient"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Sent"}),e.jsx(Tt,{children:"Last Activity"})]})}),e.jsx(Bn,{children:a.map(l=>e.jsxs(qs,{children:[e.jsx(ft,{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(ft,{children:e.jsx(nIs,{recipient:l})}),e.jsx(ft,{className:"text-xs text-muted-foreground",children:Ss(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(ft,{className:"text-xs text-muted-foreground",children:l.last_activity_at?al(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function iIs(){const{data:s,isLoading:t}=R5s(),{data:r=[],isLoading:n}=O5s(),[a,i]=k.useState(null),l=t||n,o=r.reduce((c,d)=>{const h=d.agent_videos,m=(h==null?void 0:h.id)||d.video_id;return c[m]||(c[m]={videoId:m,title:(h==null?void 0:h.title)||"Untitled",thumbnailUrl:h==null?void 0:h.thumbnail_url,recipients:[]}),c[m].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Vs,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(Vs,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(jn,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(tm,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(De,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Nr,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(De,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(m=>m.opened_at).length,h=c.recipients.filter(m=>m.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:m=>{const x=m.currentTarget;x.style.display="none",x.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(sn,{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(Zr,{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(jn,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(tm,{className:"h-3 w-3"})," ",h]})]})]}),e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(aIs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function oIs({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(sn,{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 lIs({video:s,previewSrc:t,thumbnailSrc:r,onOpen:n,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:h,onSendViaGmail:m,isGmailConnected:x,getContactName:g,getShareUrl:v,copyToClipboard:j,formatDuration:b}){const[N,S]=k.useState(!1);return e.jsxs(Ne,{className:"overflow-hidden group cursor-pointer",onClick:n,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(oIs,{previewSrc:t,thumbnailSrc:r,alt:s.title||"Video preview",isHovered:N}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(Ho,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:b(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Ge,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(De,{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(Bi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:g(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(cn,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(jn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),x&&s.share_token&&e.jsxs(G,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:T=>{T.stopPropagation(),m==null||m()},children:[e.jsx(Qs,{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(Bi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:g(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(cn,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(jn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:T=>T.stopPropagation(),children:e.jsx(Eg,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",className:"bg-popover",children:[e.jsxs(Da,{onClick:T=>{T.stopPropagation(),n()},children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(y_,{}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),h()},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),j(v(s),"Share link")},children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),o()},children:[e.jsx(j3,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),c()},children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),d()},children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),x&&s.share_token&&e.jsxs(Da,{onClick:T=>{T.stopPropagation(),m==null||m()},children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),i()},children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(y_,{}),s.contact_id&&e.jsxs(Da,{onClick:T=>{T.stopPropagation(),l()},children:[e.jsx(Bi,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Da,{onClick:T=>{T.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function cIs(){var Jt,cs;const s=vr(),{data:t,isLoading:r,refetch:n}=sTs(),{data:a}=Age(),{data:i}=$m(),l=aTs(),o=nTs(),{isGmailConnected:c,gmailEmail:d}=Oh(),{data:h}=Xg(),{data:m=[],isLoading:x}=rIs(),[g,v]=k.useState("my"),[j,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(!1),[P,D]=k.useState(!1),[B,z]=k.useState(!1),[F,$]=k.useState(!1),[X,K]=k.useState(!1),[Q,Y]=k.useState(""),[ne,de]=k.useState(!1),[ce,ae]=k.useState(!1),[ie,me]=k.useState(!1),[oe,ge]=k.useState(!1),[be,Oe]=k.useState(""),[Me,Pe]=k.useState({}),Ee=Ht=>{if(!Ht)return"Unassigned";const dt=i==null?void 0:i.find(Qt=>Qt.id===Ht);return dt?`${dt.first_name} ${dt.last_name||""}`.trim():"Unknown"},$e=Ht=>{if(!Ht)return"0:00";const dt=Math.floor(Ht/60),Qt=Ht%60;return`${dt}:${Qt.toString().padStart(2,"0")}`},[Se,ze]=k.useState("all"),Te=t==null?void 0:t.filter(Ht=>{const dt=Ht.category||"general";if(Se==="general"&&dt!=="general"||Se==="open_house"&&dt!=="open_house")return!1;if(!j)return!0;const Qt=Ee(Ht.contact_id).toLowerCase(),yt=(Ht.title||"").toLowerCase(),ss=(Ht.notes||"").toLowerCase();return Qt.includes(j.toLowerCase())||yt.includes(j.toLowerCase())||ss.includes(j.toLowerCase())}),ye=(t==null?void 0:t.filter(Ht=>(Ht.category||"general")==="open_house").length)||0,ct=(t==null?void 0:t.filter(Ht=>(Ht.category||"general")==="general").length)||0,ve=(t||[]).filter(Ht=>Ht.status==="processing"&&Ht.bunny_video_id).map(Ht=>Ht.id).join(",");k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const dt=t.filter(yt=>yt.status==="processing"&&yt.bunny_video_id);if(!dt.length)return;let Qt=!1;for(const yt of dt)try{const{data:ss,error:Is}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:yt.bunny_video_id,isAgentVideo:!0}});if(Is||!ss)continue;ss.status===4&&(await H.from("agent_videos").update({status:"ready",playback_url:ss.directPlayUrl,thumbnail_url:ss.thumbnailUrl,preview_url:ss.previewUrl,duration_seconds:ss.length||yt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",yt.id),Qt=!0)}catch(ss){console.warn("Reconcile check failed for video",yt.id,ss)}Qt&&n()})()},[ve,n]),k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const dt=t.filter(fs=>(fs==null?void 0:fs.bunny_video_id)&&!Me[fs.id]);if(!dt.length)return;const Qt=dt.map(fs=>fs.bunny_video_id),{data:yt,error:ss}=await H.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Qt,isAgentVideo:!0}});if(ss)throw ss;const Is=(yt==null?void 0:yt.assets)||{};Pe(fs=>{const ar={...fs};for(const Er of dt)Is[Er.bunny_video_id]&&(ar[Er.id]={previewUrl:Is[Er.bunny_video_id].previewUrl,thumbnailUrl:Is[Er.bunny_video_id].thumbnailUrl});return ar})})().catch(dt=>console.warn("Failed to load signed Bunny asset URLs",dt))},[t,Me]);const rt=(a==null?void 0:a.total_storage_mb)||0,Re=(a==null?void 0:a.max_storage_mb)||1024,Qe=rt/Re*100,Ke=Qe>=80,Ce=Qe>=100,nt=async(Ht,dt)=>{await navigator.clipboard.writeText(Ht),ue.success(`${dt} copied to clipboard`)},$t=Ht=>Ht.share_token?`https://video.relevelup.com/${Ht.share_token}`:Ht.playback_url||"",lt=Ht=>{const dt=$t(Ht),Qt=i==null?void 0:i.find(Er=>Er.id===Ht.contact_id),yt=Ee(Ht.contact_id),ss=yt!=="Unassigned"?yt.split(" ")[0]:"",Is=(Qt==null?void 0:Qt.phone)||"",fs=`Hey${ss?` ${ss}`:""}! I recorded a quick video message for you. Check it out: ${dt}`,ar=Is?`sms:${Is}?body=${encodeURIComponent(fs)}`:`sms:?body=${encodeURIComponent(fs)}`;window.open(ar,"_self")},it=Ht=>{const dt=i==null?void 0:i.find(ar=>ar.id===Ht.contact_id),Qt=(dt==null?void 0:dt.email)||"",yt=$t(Ht),ss="Check out this video",Is=`I recorded a quick video for you: ${yt}`,fs=Qt?`mailto:${Qt}?subject=${encodeURIComponent(ss)}&body=${encodeURIComponent(Is)}`:`mailto:?subject=${encodeURIComponent(ss)}&body=${encodeURIComponent(Is)}`;window.open(fs,"_self")},Nt=Ht=>{var ss;const dt=$t(Ht),Qt=Ht.title||"Video Message",yt=Ht.share_token?`https://video.relevelup.com/thumb/${Ht.share_token}`:((ss=Me[Ht.id])==null?void 0:ss.thumbnailUrl)||Ht.thumbnail_url||"";return``},Ft=async Ht=>{if(!Ht.thumbnail_url&&!Ht.share_token){ue.error("Video thumbnail not available yet");return}const dt=Nt(Ht),Qt=$t(Ht),yt=`Watch: ${Ht.title||"Video Message"} ${Qt}`;try{const ss=new Blob([dt],{type:"text/html"}),Is=new Blob([yt],{type:"text/plain"}),fs=new ClipboardItem({"text/html":ss,"text/plain":Is});await navigator.clipboard.write([fs]),ue.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(yt+` `+dt),ue.success("Copied! Paste into your email.")}},at=async Ht=>{try{ue.loading("Preparing download...",{id:"download"});const{data:dt,error:Qt}=await H.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Ht.bunny_video_id,isAgentVideo:!0}});if(Qt||!(dt!=null&&dt.downloadUrl))throw new Error((Qt==null?void 0:Qt.message)||"Failed to get download URL");const ss=`${((Ht.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Is=await fetch(dt.downloadUrl);if(!Is.ok)throw new Error("Failed to fetch video file");const fs=await Is.blob(),ar=URL.createObjectURL(fs),Er=document.createElement("a");Er.href=ar,Er.download=ss,Er.rel="noreferrer",document.body.appendChild(Er),Er.click(),Er.remove(),URL.revokeObjectURL(ar),ue.success("Download started",{id:"download"})}catch(dt){console.error("Download error:",dt),ue.error("Could not force download (your browser may block it).",{id:"download"})}},Ie=async Ht=>{S(Ht),de(!0),Y(""),K(!0);try{const{data:dt,error:Qt}=await H.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Ht.bunny_video_id,title:Ht.title,isAgentVideo:!0,shareToken:Ht.share_token}});if(Qt||!(dt!=null&&dt.html))throw new Error("Failed to generate CRM embed code");Y(dt.html)}catch(dt){console.error("CRM embed error:",dt),ue.error("Failed to generate CRM embed code"),K(!1)}finally{de(!1)}},et=Ht=>{S(Ht),A(!0)},Dt=async()=>{if(N)try{await l.mutateAsync({id:N.id,bunnyVideoId:N.bunny_video_id,hardDelete:!0}),D(!1),S(null),ue.success("Video deleted successfully")}catch{ue.error("Failed to delete video")}};return e.jsx(_s,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>v("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${g==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),h&&((Jt=h.team)==null?void 0:Jt.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>v("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${g==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>v("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${g==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(ao,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),g==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>z(!0),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(G,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),g==="team"?e.jsx(dIs,{videos:m,isLoading:x,searchTerm:j,setSearchTerm:b}):g==="analytics"?e.jsx(iIs,{}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:Ke?"border-amber-500":Ce?"border-destructive":"",children:e.jsxs(De,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(cO,{className:`h-5 w-5 ${Ce?"text-destructive":Ke?"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:[rt.toFixed(1)," MB / ",Re>=1024?`${(Re/1024).toFixed(0)} GB`:`${Re} MB`]})]}),e.jsx(ri,{value:Math.min(Qe,100),className:`h-2 ${Ce?"[&>div]:bg-destructive":Ke?"[&>div]:bg-amber-500":""}`})]}),Ke&&!Ce&&e.jsxs(Ge,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ce&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Hi,{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:ct},{id:"open_house",label:"Open House Tours",count:ye}].map(Ht=>e.jsxs("button",{onClick:()=>ze(Ht.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Se===Ht.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Ht.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Ht.count})]},Ht.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search videos by contact, title, or notes...",value:j,onChange:Ht=>b(Ht.target.value),className:"pl-10"})]}),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(Te==null?void 0:Te.length)===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(sn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs(G,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Te==null?void 0:Te.map(Ht=>{var dt,Qt;return e.jsx(lIs,{video:Ht,previewSrc:(dt=Me[Ht.id])==null?void 0:dt.previewUrl,thumbnailSrc:(Qt=Me[Ht.id])==null?void 0:Qt.thumbnailUrl,onOpen:()=>et(Ht),onDelete:()=>{S(Ht),D(!0)},onRename:()=>{S(Ht),Oe(Ht.title||""),ge(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Ht.contact_id}`),onGetEmbedCode:()=>{S(Ht),$(!0)},onCopyEmailHtml:()=>Ft(Ht),onEmbedToCrm:()=>Ie(Ht),onShareWithTemplate:()=>{S(Ht),ae(!0)},onSendViaGmail:()=>{S(Ht),me(!0)},isGmailConnected:c,getContactName:Ee,getShareUrl:$t,copyToClipboard:nt,formatDuration:$e},Ht.id)})}),e.jsx(vs,{open:T,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(bs,{children:(N==null?void 0:N.title)||"Video Preview"}),e.jsx(Fr,{children:(N==null?void 0:N.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"}),Ee(N.contact_id)]})})]}),N&&e.jsxs("div",{className:"space-y-4",children:[N.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(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(G,{variant:"outline",size:"sm",onClick:()=>{A(!1),n()},children:[e.jsx(Di,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:N.playback_url?(()=>{let Ht=N.playback_url;return Ht.includes("iframe.mediadelivery.net/play/")&&(Ht=Ht.replace("/play/","/embed/"),Ht+=(Ht.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Ht.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Ht,title:N.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:N.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:N.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ue.error("Video preview failed to load")},N.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(sn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>lt(N),children:[e.jsx(bi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(G,{variant:"outline",onClick:()=>it(N),children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(G,{variant:"outline",onClick:()=>nt($t(N),"Share link"),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(G,{variant:"outline",onClick:()=>Ft(N),children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(G,{variant:"outline",onClick:()=>at(N),children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),Ie(N)},children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),ae(!0)},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(N==null?void 0:N.share_token)&&e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),me(!0)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(G,{variant:"destructive",onClick:()=>{A(!1),D(!0)},children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(vs,{open:P,onOpenChange:D,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Delete Video"}),e.jsx(Fr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:Dt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(zmt,{open:B,onOpenChange:z}),e.jsx(vs,{open:F,onOpenChange:$,children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Embed Video"}),e.jsx(Fr,{children:"Copy this code to embed the video on your website."})]}),N&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Embed Code"}),e.jsx(ur,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(G,{className:"flex-1",onClick:()=>{const Ht=``;nt(Ht,"Embed code")},children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),N&&e.jsx(mxt,{open:ce,onOpenChange:ae,video:N,contactName:Ee(N.contact_id)}),N&&e.jsx(sIs,{open:ie,onOpenChange:me,video:N,gmailEmail:d,signedThumbnailUrl:(cs=Me[N.id])==null?void 0:cs.thumbnailUrl}),e.jsx(vs,{open:oe,onOpenChange:ge,children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Rename Video"}),e.jsx(Fr,{children:"Enter a new title for this video."})]}),e.jsx(ke,{value:be,onChange:Ht=>Oe(Ht.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Ht=>{Ht.key==="Enter"&&be.trim()&&o.mutate({id:N.id,title:be.trim()},{onSuccess:()=>{ue.success("Video renamed"),ge(!1)}})}}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>ge(!1),children:"Cancel"}),e.jsx(G,{disabled:!be.trim()||o.isPending,onClick:()=>{o.mutate({id:N.id,title:be.trim()},{onSuccess:()=>{ue.success("Video renamed"),ge(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(vs,{open:X,onOpenChange:K,children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Fr,{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."})]}),ne?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(he,{children:"CRM Email HTML"}),e.jsx(ur,{readOnly:!0,rows:12,value:Q,className:"font-mono text-xs"})]}),e.jsxs(G,{className:"w-full",onClick:()=>{nt(Q,"CRM embed code")},children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy CRM Embed Code"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this into your CRM's email HTML editor. The recipient will see the video thumbnail and can click to watch. Works with Follow Up Boss, KvCORE, BoomTown, Sierra, and more."})]}):null]})})]})]})})}function dIs({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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{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(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No 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(vn,{className:"h-7 w-7",children:[e.jsx(ga,{src:c.avatar||""}),e.jsx(bn,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Ge,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:h=>{h.target.style.display="none"}}):e.jsx(sn,{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(De,{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(Bi,{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(jn,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Ss(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const uIs=()=>{const{user:s}=As();return gt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.rpc("get_team_deals",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},OVe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function hIs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=uIs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=k.useMemo(()=>{if(!r)return new Map;const v=new Map;let j=0;return r.forEach(b=>{v.has(b.owner_user_id)||(v.set(b.owner_user_id,{name:b.owner_name||"Unknown",avatar:b.owner_avatar_url,color:OVe[j%OVe.length]}),j++)}),v},[r]),d=k.useMemo(()=>Array.from(c.entries()).map(([v,j])=>({id:v,...j})),[c]),h=k.useMemo(()=>{if(!r)return[];let v=r;if(l!=="all"&&(v=v.filter(j=>j.owner_user_id===l)),a.trim()){const j=a.toLowerCase();v=v.filter(b=>{var N,S,T,A;return b.deal_name.toLowerCase().includes(j)||((N=b.contact_name)==null?void 0:N.toLowerCase().includes(j))||((S=b.property_address)==null?void 0:S.toLowerCase().includes(j))||((T=b.city)==null?void 0:T.toLowerCase().includes(j))||((A=b.owner_name)==null?void 0:A.toLowerCase().includes(j))})}return v},[r,a,l]),m=k.useMemo(()=>{const v=new Map;return h.forEach(j=>{const b=j.stage_name||"Unknown";v.has(b)||v.set(b,{name:b,color:j.stage_color,icon:j.stage_icon,deals:[],totalValue:0});const N=v.get(b);N.deals.push(j),N.totalValue+=j.sale_price||0}),Array.from(v.values())},[h]),x=v=>v>=1e6?`$${(v/1e6).toFixed(1)}M`:v>=1e3?`$${(v/1e3).toFixed(0)}K`:`$${v.toFixed(0)}`,g=v=>v?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(v):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(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(fr,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search deals...",value:a,onChange:v=>i(v.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{placeholder:"All Members"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Members"}),d.map(v=>e.jsx(mt,{value:v.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:v.color}}),v.name]})},v.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(v=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:v.color}}),v.name.split(" ")[0]]},v.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:n?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(v=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(Vs,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Vs,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Vs,{className:"h-24 w-full rounded-lg"})]},v))}):m.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(fr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:m.map(v=>{const j=v.icon&&Vfe[v.icon]||Bd;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:v.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:v.color?`${v.color}20`:void 0},children:e.jsx(j,{className:"h-3.5 w-3.5",style:{color:v.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:v.name})]}),e.jsx(Ge,{variant:"secondary",className:"text-xs px-2",children:v.deals.length})]}),v.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:x(v.totalValue)})]}),e.jsx(ti,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:v.deals.map(b=>{const N=c.get(b.owner_user_id);return e.jsx(mIs,{deal:b,ownerColor:(N==null?void 0:N.color)||"#888",ownerName:(N==null?void 0:N.name)||"Unknown",ownerAvatar:(N==null?void 0:N.avatar)||null,formatPrice:g},b.id)})})})]},v.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[h.length," deal",h.length!==1?"s":""," across ",m.length," stage",m.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function mIs({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(vn,{className:"h-4 w-4",children:[e.jsx(ga,{src:n||""}),e.jsx(bn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:r.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:r})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(Ge,{variant:"outline",className:Bt("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(Cn,{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(_l,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function fIs({members:s,enabledMembers:t,onToggleMember:r,isOpen:n,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Bt("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",n?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(fr,{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(Vo,{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(ti,{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:Bt("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(vn,{className:"h-7 w-7",children:[e.jsx(ga,{src:l.avatar_url||""}),e.jsx(bn,{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:Bt("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(br,{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(vn,{className:Bt("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(ga,{src:l.avatar_url||""}),e.jsx(bn,{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 FVe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function pIs(){const s=na(),{data:t}=Xg(),r=(t==null?void 0:t.role)==="team_leader",n=t==null?void 0:t.teamId,a=gt({queryKey:["team-pipeline-members",n,s],queryFn:async()=>{const{data:i,error:l}=await H.from("team_members").select("user_id, role").eq("team_id",n).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(h=>h.user_id),{data:c,error:d}=await H.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((h,m)=>({id:h.id,name:h.name||"Unknown",avatar_url:h.avatar_url,color:FVe[m%FVe.length]}))},enabled:!!n&&!!s&&r,staleTime:5*60*1e3});return{isTeamLeader:r,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function xIs(s){return gt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:r}=await H.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 gIs(){const s=na();return gt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:r}=await H.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 fxt({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(lu,{open:a,onOpenChange:i,children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:n,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(ya,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Vd,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&Vfe[c.icon]||Bd,h=c.id===t;return e.jsxs(Da,{onClick:()=>o(c),className:Bt("flex items-center gap-2 cursor-pointer",h&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),h&&e.jsx(Hn,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const yIs={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"}},vIs={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 pxt({deal:s,onClick:t,isDragging:r,stages:n,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var S,T;const c=tL(),d=yIs[s.deal_type],h=vIs[s.priority],m=k.useMemo(()=>s.target_close_date?Kg(Ul(s.target_close_date),new Date):null,[s.target_close_date]),x=m!==null&&m<0,g=m!==null&&m<=7&&m>=0,v=k.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!A)return null;const P=s.contract_date?Ul(s.contract_date):new Date;return Kg(P,Ul(A))},[s]),j=l&&!s.scorecard_transaction_id,b=!!s.scorecard_transaction_id,N=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(Ne,{className:Bt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",r&&"opacity-50 rotate-2 shadow-xl",x&&"border-red-200 bg-red-50/30",j&&"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(De,{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(vn,{className:"h-4 w-4",children:[e.jsx(ga,{src:o.avatar_url||""}),e.jsx(bn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:o.color},children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:o.color},children:o.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(Ge,{variant:"outline",className:Bt("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(vn,{className:"h-5 w-5",children:e.jsxs(bn,{className:"text-[10px] bg-primary/10 text-primary",children:[(S=s.contact.first_name)==null?void 0:S[0],(T=s.contact.last_name)==null?void 0:T[0]]})}),e.jsxs("span",{className:"truncate",children:[s.contact.first_name," ",s.contact.last_name]})]}),s.listing&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(rl,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),j&&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(Zi,{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(Mn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),v!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Bv,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Bt("font-medium",v>90?"text-red-600":v>60?"text-amber-600":"text-muted-foreground"),children:[v," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Cn,{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(_l,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:N(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",N(s.expected_commission)," GCI"]}),(()=>{const A=Pg(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",N(A)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Bt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",h.color),children:[e.jsx("div",{className:Bt("w-1.5 h-1.5 rounded-full",h.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&n&&a?e.jsx(fxt,{stages:n,currentStageId:s.stage_id||"",onStageSelect:(A,P)=>a(s.id,A,P)}):s.target_close_date?e.jsxs("div",{className:Bt("flex items-center gap-1 text-[10px]",x&&"text-red-600",g&&!x&&"text-amber-600",!x&&!g&&"text-muted-foreground"),children:[x?e.jsx(Hi,{className:"h-3 w-3"}):e.jsx(rn,{className:"h-3 w-3"}),e.jsx("span",{children:x?`${Math.abs(m)}d overdue`:g?`${m}d left`:Ss(Ul(s.target_close_date),"MMM d")})]}):null]})]})})}function bIs({stage:s,deals:t,onDealClick:r,onAddDeal:n,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const h=k.useRef(null),m=t.reduce((b,N)=>b+(N.expected_price||0),0),x=t.reduce((b,N)=>b+(N.expected_commission||0),0),g=t.reduce((b,N)=>b+(Pg(N)||0),0),v=b=>b>=1e6?`$${(b/1e6).toFixed(1)}M`:b>=1e3?`$${(b/1e3).toFixed(0)}K`:`$${b.toFixed(0)}`,j=s.icon&&Vfe[s.icon]||Bd;return e.jsxs("div",{ref:h,className:Bt("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(j,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsx(Ge,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),m>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:v(m)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[v(x)," GCI"]}),g>0&&g!==x&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[v(g)," Net"]})]})]})]}),e.jsx(ti,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(b=>e.jsx("div",{draggable:!0,onDragStart:N=>{N.dataTransfer.effectAllowed="move",a(b.id,s.id)},children:e.jsx(pxt,{deal:b,onClick:()=>r(b),isWonStage:c,ownerInfo:(d==null?void 0:d(b))||null})},b.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>n(s.id),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function _Is({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:zd,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:r((s==null?void 0:s.weightedGCI)||0),icon:CO,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:zO,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:XR,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:_o,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(Ne,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(A_,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:n.map(a=>{const i=e.jsx(Ne,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Bt("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Bt("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(hc,{children:[e.jsx(mc,{asChild:!0,children:i}),e.jsx(Wl,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function wIs({formData:s,onChange:t,isEditing:r}){const{isAdmin:n}=As(),[a,i]=k.useState(s.portal_enabled);if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Coming Soon"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Give your clients a premium, real-time view of their transaction — coming soon!"})]});const l=o=>{t({...s,...o})};return e.jsx(bx,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(_x,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Ge,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(so,{className:Bt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(wx,{children:e.jsxs("div",{className:"px-4 pb-4 space-y-5 border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Enable Client Portal"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Create a beautiful portal your client can track their deal from"})]}),e.jsx(br,{checked:s.portal_enabled,onCheckedChange:o=>l({portal_enabled:o})})]}),s.portal_enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(Vb,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Bt("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(Qd,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Private"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Link-only access"})]})]}),e.jsxs("label",{className:Bt("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(Qd,{value:"public"}),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:"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(Ei,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ei,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(he,{htmlFor:"allow_spouse",className:"text-sm cursor-pointer",children:"Allow client to add spouse/partner during onboarding"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-sm font-medium",children:"Client Invite Details"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(ke,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(ke,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(ke,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(zs,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"email",children:"Email"}),e.jsxs(mt,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const jIs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],NIs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function kIs({open:s,onOpenChange:t,deal:r,defaultStageId:n}){const{data:a}=Mge(),{data:i}=$m(),{data:l}=Xnt(),o=exe(),c=lft(),d=cft(),h=dAe(),[m,x]=k.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[g,v]=k.useState(""),[j,b]=k.useState(!1),[N,S]=k.useState(!1),[T,A]=k.useState({first_name:"",last_name:"",email:"",phone:""}),P=(l==null?void 0:l.filter(Q=>((r==null?void 0:r.listing_id)===Q.id,!0)))||[],[D,B]=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,Y,ne,de,ce,ae,ie,me;s&&(r?(B({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:((Y=r.commission_percentage)==null?void 0:Y.toString())||"3",brokerage_split_pct:((ne=r.brokerage_split_pct)==null?void 0:ne.toString())||"",team_split_pct:((de=r.team_split_pct)==null?void 0:de.toString())||"",referral_fee_pct:((ce=r.referral_fee_pct)==null?void 0:ce.toString())||"",franchise_fee_pct:((ae=r.franchise_fee_pct)==null?void 0:ae.toString())||"",transaction_fee:((ie=r.transaction_fee)==null?void 0:ie.toString())||"",commission_calc_method:r.commission_calc_method||"standard",target_close_date:r.target_close_date?Ul(r.target_close_date):void 0,contract_date:r.contract_date?Ul(r.contract_date):void 0,listing_date:r.listing_date?Ul(r.listing_date):void 0,priority:r.priority,probability:r.probability.toString(),notes:r.notes||""}),r.contact&&v(`${r.contact.first_name} ${r.contact.last_name}`)):(B({deal_name:"",deal_type:"buyer",stage_id:n||((me=a==null?void 0:a[0])==null?void 0:me.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""}),v(""),x({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,r,n,a]);const z=i==null?void 0:i.filter(Q=>{var ge,be,Oe,Me,Pe;const Y=g.toLowerCase().trim();if(!Y)return!0;const ne=((ge=Q.first_name)==null?void 0:ge.toLowerCase())||"",de=((be=Q.last_name)==null?void 0:be.toLowerCase())||"",ce=((Oe=Q.email)==null?void 0:Oe.toLowerCase())||"",ae=((Pe=(Me=Q.phone)==null?void 0:Me.toLowerCase)==null?void 0:Pe.call(Me))||"",ie=`${ne} ${de}`.trim(),me=`${de} ${ne}`.trim();if(ie.includes(Y)||me.includes(Y)||ne.includes(Y)||de.includes(Y)||ce.includes(Y)||ae.includes(Y))return!0;const oe=Y.split(/\s+/).filter(Boolean);return oe.length>1?oe.every(Ee=>ne.includes(Ee)||de.includes(Ee)||ce.includes(Ee)||ae.includes(Ee)):!1}).slice(0,8),F=()=>{const Q=parseFloat(D.expected_price)||0,Y=parseFloat(D.commission_percentage)||0;return Q*(Y/100)},$=()=>{const Q=F();if(!Q)return null;const Y=parseFloat(D.brokerage_split_pct)||0,ne=parseFloat(D.team_split_pct)||0,de=parseFloat(D.referral_fee_pct)||0,ce=parseFloat(D.franchise_fee_pct)||0,ae=parseFloat(D.transaction_fee)||0;if(D.commission_calc_method==="referral_first"){let me=Q;de&&(me-=Q*de/100);let oe=me;return Y&&(oe-=me*Y/100),ne&&(oe-=Q*ne/100),ce&&(oe-=Q*ce/100),ae&&(oe-=ae),Math.max(0,oe)}let ie=Q;return Y&&(ie=ie*((100-Y)/100)),ne&&(ie=ie*((100-ne)/100)),de&&(ie=ie-Q*de/100),ce&&(ie=ie-Q*ce/100),ae&&(ie=ie-ae),Math.max(0,ie)},X=async Q=>{var Y,ne,de;if(Q.preventDefault(),!D.deal_name.trim()){ue.error("Please enter a deal name");return}try{const ce={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:F()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,commission_calc_method:D.commission_calc_method,target_close_date:((Y=D.target_close_date)==null?void 0:Y.toISOString().split("T")[0])||null,contract_date:((ne=D.contract_date)==null?void 0:ne.toISOString().split("T")[0])||null,listing_date:((de=D.listing_date)==null?void 0:de.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,...ce}),ue.success("Deal updated successfully");else{const ae=await c.mutateAsync(ce);if(ue.success("Deal created successfully"),m.portal_enabled&&(ae!=null&&ae.id))try{await h.mutateAsync({deal_id:ae.id,visibility:m.visibility,require_onboarding:m.require_onboarding,allow_spouse:m.allow_spouse,client_name:m.client_name||null,client_email:m.client_email||null,client_phone:m.client_phone||null,invite_method:m.invite_method}),ue.success("Client portal created!")}catch{ue.error("Deal created, but portal setup failed")}}t(!1)}catch{ue.error("Failed to save deal")}},K=c.isPending||d.isPending;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(bs,{children:r?"Edit Deal":"Add New Deal"}),e.jsx(Fr,{children:r?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:X,className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(he,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(ke,{id:"deal_name",value:D.deal_name,onChange:Q=>B(Y=>({...Y,deal_name:Q.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Deal Type"}),e.jsxs(zs,{value:D.deal_type,onValueChange:Q=>B(Y=>({...Y,deal_type:Q})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:jIs.map(Q=>e.jsx(mt,{value:Q.value,children:Q.label},Q.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Stage"}),e.jsxs(zs,{value:D.stage_id||"none",onValueChange:Q=>B(Y=>({...Y,stage_id:Q==="none"?"":Q})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select stage"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Q=>e.jsx(mt,{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(he,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:g,onChange:Q=>{v(Q.target.value),b(!0),S(!1),Q.target.value||B(Y=>({...Y,contact_id:""}))},onFocus:()=>b(!0),placeholder:"Search contacts...",className:"pl-9"}),j&&g&&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:[z&&z.length>0?z.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:()=>{B(Y=>({...Y,contact_id:Q.id})),v(`${Q.first_name} ${Q.last_name}`),b(!1)},children:[e.jsx(Bi,{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=g.trim().split(/\s+/);A({first_name:Q[0]||"",last_name:Q.slice(1).join(" ")||"",email:"",phone:""}),S(!0),b(!1)},children:[e.jsx(nl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',g.trim(),'"']})]})]})]}),N&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>S(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ke,{placeholder:"First name *",value:T.first_name,onChange:Q=>A(Y=>({...Y,first_name:Q.target.value})),className:"h-8 text-sm"}),e.jsx(ke,{placeholder:"Last name",value:T.last_name,onChange:Q=>A(Y=>({...Y,last_name:Q.target.value})),className:"h-8 text-sm"}),e.jsx(ke,{placeholder:"Email",type:"email",value:T.email,onChange:Q=>A(Y=>({...Y,email:Q.target.value})),className:"h-8 text-sm"}),e.jsx(ke,{placeholder:"Phone",type:"tel",value:T.phone,onChange:Q=>A(Y=>({...Y,phone:Q.target.value})),className:"h-8 text-sm"})]}),e.jsx(G,{type:"button",size:"sm",className:"w-full h-8",disabled:!T.first_name.trim()||o.isPending,onClick:async()=>{try{const Q=await o.mutateAsync({first_name:T.first_name.trim(),last_name:T.last_name.trim()||null,email:T.email.trim()||null,phone:T.phone.trim()||null});Q&&(B(Y=>({...Y,contact_id:Q.id})),v(`${Q.first_name} ${Q.last_name||""}`.trim()),S(!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(nl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),P.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(rl,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(zs,{value:D.listing_id||"none",onValueChange:Q=>{const Y=Q==="none"?"":Q,ne=P.find(de=>de.id===Y);B(ne?de=>{var ce;return{...de,listing_id:Y,deal_type:"seller",property_address:ne.property_address||de.property_address,city:ne.city||de.city,state:ne.state||de.state,expected_price:((ce=ne.price)==null?void 0:ce.toString())||de.expected_price}}:de=>({...de,listing_id:Y}))},children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a listing to sync status..."})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"None"}),P.map(Q=>e.jsx(mt,{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(he,{htmlFor:"property_address",children:"Address"}),e.jsx(ke,{id:"property_address",value:D.property_address,onChange:Q=>B(Y=>({...Y,property_address:Q.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(ke,{id:"city",value:D.city,onChange:Q=>B(Y=>({...Y,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(he,{htmlFor:"state",children:"State"}),e.jsx(ke,{id:"state",value:D.state,onChange:Q=>B(Y=>({...Y,state:Q.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(ke,{id:"zip_code",value:D.zip_code,onChange:Q=>B(Y=>({...Y,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(he,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ke,{id:"expected_price",type:"number",value:D.expected_price,onChange:Q=>B(Y=>({...Y,expected_price:Q.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:Q=>B(Y=>({...Y,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(he,{children:"Expected GCI"}),e.jsx(ke,{value:F()?`$${F().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(he,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(zs,{value:D.commission_calc_method,onValueChange:Q=>B(Y=>({...Y,commission_calc_method:Q})),children:[e.jsx(Os,{className:"h-7 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(mt,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:Q=>B(Y=>({...Y,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(he,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:Q=>B(Y=>({...Y,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(he,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:Q=>B(Y=>({...Y,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(he,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:Q=>B(Y=>({...Y,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(he,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(ke,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:Q=>B(Y=>({...Y,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(he,{className:"text-xs",children:"Net to Agent"}),e.jsx(ke,{value:$()?`$${Math.round($()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Target Close Date"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!D.target_close_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),D.target_close_date?Ss(D.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:D.target_close_date,onSelect:Q=>B(Y=>({...Y,target_close_date:Q})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Contract Date"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!D.contract_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),D.contract_date?Ss(D.contract_date,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:D.contract_date,onSelect:Q=>B(Y=>({...Y,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(he,{children:"Listing Date (for Days on Market)"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!D.listing_date&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),D.listing_date?Ss(D.listing_date,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:D.listing_date,onSelect:Q=>B(Y=>({...Y,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(he,{children:"Priority"}),e.jsxs(zs,{value:D.priority,onValueChange:Q=>B(Y=>({...Y,priority:Q})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:NIs.map(Q=>e.jsx(mt,{value:Q.value,children:Q.label},Q.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{type:"number",min:"0",max:"100",value:D.probability,onChange:Q=>B(Y=>({...Y,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(he,{htmlFor:"notes",children:"Notes"}),e.jsx(ur,{id:"notes",value:D.notes,onChange:Q=>B(Y=>({...Y,notes:Q.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!r&&e.jsx(wIs,{formData:m,onChange:x}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:K,children:[K&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Update Deal":"Create Deal"]})]})]})]})})}function SIs({dealId:s}){const t=na(),r=es(),[n,a]=k.useState(""),[i,l]=k.useState(!1),{data:o=[]}=gt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:v,error:j}=await H.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(j)throw j;return v},enabled:!!s}),{data:c=[]}=gt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:v,error:j}=await H.from("deal_tags").select("tag").eq("owner_user_id",t);if(j)throw j;return[...new Set(v.map(N=>N.tag))].sort()},enabled:!!t}),d=Lt({mutationFn:async v=>{if(!t)throw new Error("Not authenticated");const{error:j}=await H.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:v.trim()});if(j)throw j},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]}),r.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),h=Lt({mutationFn:async v=>{const{error:j}=await H.from("deal_tags").delete().eq("id",v);if(j)throw j},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]})}}),m=()=>{const v=n.trim();v&&(o.some(j=>j.tag.toLowerCase()===v.toLowerCase())||d.mutate(v))},x=o.map(v=>v.tag.toLowerCase()),g=c.filter(v=>v.toLowerCase().includes(n.toLowerCase())&&!x.includes(v.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(v=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 text-xs",children:[v.tag,e.jsx("button",{type:"button",onClick:()=>h.mutate(v.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(_r,{className:"h-3 w-3"})})]},v.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(Ws,{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(ke,{value:n,onChange:v=>a(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),m()),v.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:m,disabled:!n.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),n&&g.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:g.map(v=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:j=>{j.preventDefault(),d.mutate(v)},children:v},v))})]})]})}function CIs(s){return gt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:r}=await H.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function TIs(){const s=na(),t=es();return Lt({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 H.storage.from("deal-files").upload(i,n);if(l)throw l;const{data:o,error:c}=await H.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 EIs(){const s=es();return Lt({mutationFn:async({fileId:t,storagePath:r,dealId:n})=>{await H.storage.from("deal-files").remove([r]);const{error:a}=await H.from("deal_files").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function AIs(){const s=es();return Lt({mutationFn:async({fileId:t,visible:r,dealId:n})=>{const{error:a}=await H.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 MIs(s){const{data:t,error:r}=await H.storage.from("deal-files").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const BVe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function xxt({open:s,onOpenChange:t}){const{data:r,isLoading:n}=TTs(),a=ETs(),i=ATs(),l=MTs(),[o,c]=k.useState(!1),[d,h]=k.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[m,x]=k.useState(""),g=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((r==null?void 0:r.length)||0)+1}),h({question_text:"",field_type:"text",options:[],is_required:!1}),x(""),c(!1),ue.success("Question added")}catch{ue.error("Failed to add question")}},v=async S=>{try{await l.mutateAsync(S),ue.success("Question removed")}catch{ue.error("Failed to remove question")}},j=async(S,T)=>{try{await i.mutateAsync({id:S,is_required:T})}catch{ue.error("Failed to update question")}},b=()=>{m.trim()&&(h(S=>({...S,options:[...S.options,m.trim()]})),x(""))},N=S=>{h(T=>({...T,options:T.options.filter((A,P)=>P!==S)}))};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(js,{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(ti,{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(S=>{var T;return e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:S.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs",children:BVe[S.field_type]||S.field_type}),S.is_required&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Required"})]}),S.field_type==="dropdown"&&((T=S.options)==null?void 0:T.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",S.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(br,{checked:S.is_required,onCheckedChange:A=>j(S.id,A),className:"scale-75"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})},S.id)}),!n&&(r==null?void 0:r.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Question"}),e.jsx(ke,{value:d.question_text,onChange:S=>h(T=>({...T,question_text:S.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(BVe).map(([S,T])=>e.jsx("button",{type:"button",onClick:()=>h(A=>({...A,field_type:S,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===S?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:T},S))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((S,T)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:S}),e.jsx("button",{onClick:()=>N(T),className:"text-muted-foreground hover:text-destructive",children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]},T)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:m,onChange:S=>x(S.target.value),onKeyDown:S=>S.key==="Enter"&&(S.preventDefault(),b()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(G,{variant:"outline",size:"sm",onClick:b,disabled:!m.trim(),className:"h-8",children:e.jsx(Ws,{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(br,{checked:d.is_required,onCheckedChange:S=>h(T=>({...T,is_required:S}))}),e.jsx(he,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(G,{size:"sm",onClick:g,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(G,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function IIs({override:s,onChange:t}){const r=na(),{data:n}=_rt(),[a,i]=k.useState(null),l=d=>t({...s,...d}),o=async(d,h)=>{if(r){if(d.size>5*1024*1024){ue.error("Image must be under 5MB");return}i(h);try{const m=await wrt(r,d,`${h}`);l(h==="logo"?{logo_url:m}:{cover_photo_url:m})}catch(m){ue.error(`Upload failed: ${m.message||m}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(jr,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(zVe,{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(zVe,{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($Ve,{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($Ve,{label:"Accent Color",value:s.accent_color??null,globalValue:(n==null?void 0:n.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(ke,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(n==null?void 0:n.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(yr,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function zVe({label:s,value:t,globalValue:r,uploading:n,onUpload:a,onClear:i,aspect:l}){const o=t||r,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(he,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):r?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Bt("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(fl,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var m;const h=(m=d.target.files)==null?void 0:m[0];h&&a(h),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[n?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(oa,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})}function $Ve({label:s,value:t,globalValue:r,onChange:n}){const a=t||r||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:s}),i&&e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"})]}),e.jsxs("div",{className:Bt("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(ke,{value:t||"",onChange:l=>n(l.target.value||null),placeholder:r||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3 w-3"})})]})]})}function PIs({portalId:s,ownerId:t,clientEmail:r,linkedPortalId:n,onLink:a}){const[i,l]=k.useState(""),[o,c]=k.useState(!1),{data:d,isLoading:h}=gt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:v,error:j}=await H.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(j)throw j;return v},enabled:o||!!n}),m=k.useMemo(()=>!n||!d?null:d.find(v=>v.id===n),[n,d]),x=k.useMemo(()=>!d||!r?[]:d.filter(v=>{var j;return((j=v.client_email)==null?void 0:j.toLowerCase())===r.toLowerCase()&&v.id!==s}),[d,r,s]),g=k.useMemo(()=>{if(!d||!i.trim())return[];const v=i.toLowerCase();return d.filter(j=>{var N,S,T,A;const b=j.deal_pipeline;return((N=j.client_name)==null?void 0:N.toLowerCase().includes(v))||((S=j.client_email)==null?void 0:S.toLowerCase().includes(v))||((T=b==null?void 0:b.deal_name)==null?void 0:T.toLowerCase().includes(v))||((A=b==null?void 0:b.property_address)==null?void 0:A.toLowerCase().includes(v))})},[d,i]);if(n){const v=m==null?void 0:m.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Linked Portal"}),e.jsxs("div",{className:"flex items-center gap-2 bg-primary/5 border border-primary/20 rounded-lg p-3",children:[e.jsx(rl,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(m==null?void 0:m.client_name)||(v==null?void 0:v.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(v==null?void 0:v.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(v==null?void 0:v.property_address)||"No address"]})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(W3,{className:"h-3 w-3 mr-1"}),"Unlink"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Client will see both transactions in a tabbed view on one portal link."})]})}return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(rl,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&x.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),x.map(v=>{const j=v.deal_pipeline;return e.jsxs("button",{onClick:()=>a(v.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(j==null?void 0:j.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:(j==null?void 0:j.deal_name)||v.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:j==null?void 0:j.property_address})]}),e.jsx(rl,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},v.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{value:i,onChange:v=>l(v.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),h&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),g.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:g.map(v=>{const j=v.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(v.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:(j==null?void 0:j.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:(j==null?void 0:j.deal_name)||v.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:v.client_email})]})]},v.id)})}),i&&g.length===0&&!h&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function dMe({contactId:s,onVideoReady:t}){const[r,n]=k.useState(!1),[a,i]=k.useState("record"),[l,o]=k.useState(0),[c,d]=k.useState(0),h=O_(),m=()=>{i("record"),o(0),d(0)},x=v=>{!v&&(a==="uploading"||a==="processing")||(n(v),v||m())},g=k.useCallback(async(v,j)=>{i("uploading");try{const b="Card Video",{videoId:N,libraryId:S}=await sT(b),{uploadUrl:T,apiKey:A}=await rT(N),P=new XMLHttpRequest;P.upload.onprogress=K=>{K.lengthComputable&&o(K.loaded/K.total*100)},await new Promise((K,Q)=>{P.onload=()=>P.status>=200&&P.status<300?K():Q(new Error("Upload failed")),P.onerror=()=>Q(new Error("Upload failed")),P.open("PUT",T),P.setRequestHeader("AccessKey",A),P.send(v)}),i("processing");let D=0;const B=Date.now(),z=9e4,F=`https://iframe.mediadelivery.net/embed/${S}/${N}`;for(;D<4;){if(await new Promise(Q=>setTimeout(Q,3e3)),Date.now()-B>z){const Q=v.size/1048576;await h.mutateAsync({bunny_video_id:N,playback_url:`https://iframe.mediadelivery.net/play/${S}/${N}`,file_size_mb:Q,title:b,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(F),ue.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{n(!1),m()},1500);return}const K=await u1(N);if(D=K.status,d(K.encodeProgress||0),D===5||D===6)throw new Error("Video processing failed")}const $=await u1(N),X=($.storageSize||v.size)/(1024*1024);await h.mutateAsync({bunny_video_id:N,contact_id:s||void 0,playback_url:$.directPlayUrl||F,thumbnail_url:$.thumbnailUrl,preview_url:$.previewUrl||null,duration_seconds:$.length||j,file_size_mb:X,title:b,status:"ready",touch_type:"video"}),t(F),ue.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{n(!1),m()},1500)}catch(b){console.error("Recording upload error:",b),ue.error("Failed to process video. Please try again."),i("record")}},[s,t,h]);return e.jsxs(vs,{open:r,onOpenChange:x,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(sn,{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(js,{children:e.jsx(bs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(xL,{maxDurationSeconds:600,onRecordingComplete:g,onError:v=>ue.error(v)}),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(ri,{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(ri,{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(mi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const LIs=s=>`portal-settings-draft:${s}`;function uMe({open:s,onOpenChange:t,portal:r,dealOwnerId:n}){const a=rL(),[i,l]=k.useState(!1),o=k.useMemo(()=>LIs(r.id),[r.id]),[c,d]=k.useState(!1),[h,m]=k.useState(r.next_step_text||""),[x,g]=k.useState(r.next_step_video_url||""),[v,j]=k.useState(r.inspection_date||""),[b,N]=k.useState(r.appraisal_date||""),[S,T]=k.useState(r.welcome_message||""),[A,P]=k.useState(r.review_url||""),[D,B]=k.useState(r.show_post_close_tips),[z,F]=k.useState(r.notify_client),[$,X]=k.useState(r.require_onboarding),[K,Q]=k.useState(r.allow_spouse),[Y,ne]=k.useState(r.visibility),[de,ce]=k.useState(r.stage_mapping||[]),[ae,ie]=k.useState(null),[me,oe]=k.useState(r.linked_portal_id||null),[ge,be]=k.useState(r.referral_enabled??!0),[Oe,Me]=k.useState(r.referral_reward_text||""),[Pe,Ee]=k.useState(r.referral_cta_headline||""),[$e,Se]=k.useState(r.homeowner_hub_video_url||""),[ze,Te]=k.useState(r.branding_override||{}),ye=()=>{m(r.next_step_text||""),g(r.next_step_video_url||""),j(r.inspection_date||""),N(r.appraisal_date||""),T(r.welcome_message||""),P(r.review_url||""),B(r.show_post_close_tips),F(r.notify_client),X(r.require_onboarding),Q(r.allow_spouse),ne(r.visibility),ce(r.stage_mapping||[]),oe(r.linked_portal_id||null),be(r.referral_enabled??!0),Me(r.referral_reward_text||""),Ee(r.referral_cta_headline||""),Se(r.homeowner_hub_video_url||""),Te(r.branding_override||{})};k.useEffect(()=>{d(!1);const Ce=localStorage.getItem(o);if(Ce)try{const nt=JSON.parse(Ce);m(nt.nextStepText||""),g(nt.nextStepVideo||""),j(nt.inspectionDate||""),N(nt.appraisalDate||""),T(nt.welcomeMessage||""),P(nt.reviewUrl||""),B(!!nt.showPostClose),F(!!nt.notifyClient),X(!!nt.requireOnboarding),Q(!!nt.allowSpouse),ne(nt.visibility||r.visibility),ce(nt.stageMapping||[]),oe(nt.linkedPortalId??null),be(nt.referralEnabled??!0),Me(nt.referralRewardText||""),Ee(nt.referralCtaHeadline||""),Se(nt.homeownerHubVideoUrl||""),Te(nt.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ye(),d(!0)},[o,r]),k.useEffect(()=>{if(!c)return;const Ce={nextStepText:h,nextStepVideo:x,inspectionDate:v,appraisalDate:b,welcomeMessage:S,reviewUrl:A,showPostClose:D,notifyClient:z,requireOnboarding:$,allowSpouse:K,visibility:Y,stageMapping:de,linkedPortalId:me,referralEnabled:ge,referralRewardText:Oe,referralCtaHeadline:Pe,homeownerHubVideoUrl:$e,brandingOverride:ze};h!==(r.next_step_text||"")||x!==(r.next_step_video_url||"")||v!==(r.inspection_date||"")||b!==(r.appraisal_date||"")||S!==(r.welcome_message||"")||A!==(r.review_url||"")||D!==r.show_post_close_tips||z!==r.notify_client||$!==r.require_onboarding||K!==r.allow_spouse||Y!==r.visibility||JSON.stringify(de)!==JSON.stringify(r.stage_mapping||[])||me!==(r.linked_portal_id||null)||ge!==(r.referral_enabled??!0)||Oe!==(r.referral_reward_text||"")||Pe!==(r.referral_cta_headline||"")||$e!==(r.homeowner_hub_video_url||"")||JSON.stringify(ze)!==JSON.stringify(r.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ce)):localStorage.removeItem(o)},[h,x,v,b,S,A,D,z,$,K,Y,de,me,ge,Oe,Pe,$e,ze,o,c,r]);const ct=()=>{localStorage.removeItem(o),ye()},ve=async()=>{try{await a.mutateAsync({id:r.id,next_step_text:h||null,next_step_video_url:x||null,inspection_date:v||null,appraisal_date:b||null,welcome_message:S||null,review_url:A||null,show_post_close_tips:D,notify_client:z,require_onboarding:$,allow_spouse:K,visibility:Y,stage_mapping:de.length>0?de:null,linked_portal_id:me,referral_enabled:ge,referral_reward_text:Oe||null,referral_cta_headline:Pe||null,homeowner_hub_video_url:$e||null,branding_override:Object.values(ze).some(nt=>nt!=null&&nt!=="")?ze:null});const Ce=r.linked_portal_id;me&&me!==Ce&&await H.from("client_portals").update({linked_portal_id:r.id}).eq("id",me),!me&&Ce&&await H.from("client_portals").update({linked_portal_id:null}).eq("id",Ce),localStorage.removeItem(o),ue.success("Portal settings saved"),t(!1)}catch{ue.error("Failed to save settings")}},rt=()=>{ce([...de,{label:""}])},Re=Ce=>{ce(de.filter((nt,$t)=>$t!==Ce)),ae===Ce&&ie(null)},Qe=(Ce,nt,$t)=>{const lt=[...de];lt[Ce]={...lt[Ce],[nt]:$t},ce(lt)},Ke=()=>{const nt=Bpe(null).map($t=>({label:$t.label,description:$t.description,stageId:void 0}));ce(nt)};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(js,{children:e.jsx(bs,{children:"Portal Settings"})}),e.jsxs(Rn,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Dn,{className:"grid grid-cols-4 shrink-0",children:[e.jsx(Xt,{value:"general",children:"General"}),e.jsx(Xt,{value:"timeline",children:"Timeline"}),e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(as,{value:"general",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public portals appear without restrictions"})]}),e.jsx("div",{className:"flex gap-1",children:["private","public"].map(Ce=>e.jsx("button",{onClick:()=>ne(Ce),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${Y===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(he,{className:"text-sm font-medium",children:"Require Onboarding"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clients must fill out intake form"})]}),e.jsx(br,{checked:$,onCheckedChange:X})]}),$&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Allow Spouse/Partner"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show spouse fields on onboarding"})]}),e.jsx(br,{checked:K,onCheckedChange:Q})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Post-Close Celebration"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show congrats card when deal closes"})]}),e.jsx(br,{checked:D,onCheckedChange:B})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Notify Client on Updates"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email client when you post portal updates"})]}),e.jsx(br,{checked:z,onCheckedChange:F})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(PIs,{portalId:r.id,ownerId:n,clientEmail:r.client_email,linkedPortalId:me,onLink:oe})}),e.jsx("div",{children:e.jsx(ke,{type:"date",value:v,onChange:Ce=>j(Ce.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(ke,{type:"date",value:b,onChange:Ce=>N(Ce.target.value),className:"mt-1"})]})]}),e.jsx(as,{value:"timeline",className:"space-y-4 mt-0 px-1",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:Ke,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.'}),de.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(G,{variant:"outline",size:"sm",onClick:Ke,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:de.map((Ce,nt)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(ke,{value:Ce.label,onChange:$t=>Qe(nt,"label",$t.target.value),placeholder:`Stage ${nt+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ie(ae===nt?null:nt),children:ae===nt?"Less":"More"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Re(nt),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),ae===nt&&e.jsxs("div",{className:"ml-6 space-y-2 pl-2 border-l-2 border-primary/15 pb-2",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ce.description||"",onChange:$t=>Qe(nt,"description",$t.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Video"}),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(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Qe(nt,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(dMe,{onVideoReady:$t=>Qe(nt,"video_url",$t)}),e.jsx(sL,{userId:n,onSelect:$t=>Qe(nt,"video_url",$t),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const $t=prompt("Paste a YouTube or Loom URL:");$t&&Qe(nt,"video_url",$t)},children:[e.jsx(xo,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},nt))}),de.length>0&&e.jsxs(G,{variant:"outline",size:"sm",onClick:rt,className:"mt-2 text-xs w-full",children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(as,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:S,onChange:Ce=>T(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(he,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:h,onChange: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(he,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(ke,{value:x,onChange:Ce=>g(Ce.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(ke,{value:A,onChange:Ce=>P(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(he,{className:"text-sm font-semibold",children:"Homeowner Hub & Referrals"})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:'Shown automatically when the deal is in a "won" stage.'}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Show Referral Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Big CTA asking client to refer friends"})]}),e.jsx(br,{checked:ge,onCheckedChange:be})]}),ge&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Headline"}),e.jsx(ke,{value:Pe,onChange:Ce=>Ee(Ce.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(ke,{value:Oe,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(he,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(ke,{value:$e,onChange:Ce=>Se(Ce.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(as,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(IIs,{override:ze,onChange:Te})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(G,{variant:"ghost",onClick:ct,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(G,{onClick:ve,disabled:a.isPending,children:[a.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(xxt,{open:i,onOpenChange:l})]})}const DIs=s=>`portal-update-draft:${s}`;function hMe({open:s,onOpenChange:t,portalId:r,portalSlug:n,notifyClient:a}){const i=k.useMemo(()=>DIs(r),[r]),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,g]=k.useState(!1),[v,j]=k.useState(a??!1),[b,N]=k.useState(!1),S=Wmt();k.useEffect(()=>{N(!1);const P=localStorage.getItem(i);if(P)try{const D=JSON.parse(P);o(D.title||""),d(D.content||""),m(D.videoUrl||""),g(!!D.isStageChange),j(typeof D.sendNotification=="boolean"?D.sendNotification:a??!1),N(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),m(""),g(!1),j(a??!1),N(!0)},[i,a]),k.useEffect(()=>{if(!b)return;const P={title:l,content:c,videoUrl:h,isStageChange:x,sendNotification:v};l.trim()||c.trim()||h.trim()||x||v!==(a??!1)?localStorage.setItem(i,JSON.stringify(P)):localStorage.removeItem(i)},[l,c,h,x,v,b,i,a]);const T=()=>{localStorage.removeItem(i),o(""),d(""),m(""),g(!1),j(a??!1)},A=async()=>{if(l.trim())try{if(await S.mutateAsync({portal_id:r,title:l.trim(),content:c.trim()||void 0,video_url:h.trim()||void 0,is_stage_change:x}),v&&n)try{const P=s1(n);await H.functions.invoke("send-portal-notification",{body:{portal_id:r,update_title:l.trim(),update_content:c.trim()||null,portal_url:P}}),ue.success("Update posted & client notified")}catch(P){console.error("Notification failed:",P),ue.success("Update posted (notification failed to send)")}else ue.success("Update posted to portal");T(),t(!1)}catch{ue.error("Failed to post update")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Title *"}),e.jsx(ke,{value:l,onChange:P=>o(P.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:P=>d(P.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Everything looked great during the inspection..."})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ke,{value:h,onChange:P=>m(P.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(sn,{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:()=>g(!x),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${x?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>j(!v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${v?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[v?e.jsx(Rm,{className:"h-3 w-3"}):e.jsx(Fv,{className:"h-3 w-3"}),v?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(G,{variant:"ghost",onClick:T,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(G,{onClick:A,disabled:!l.trim()||S.isPending,children:[S.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function mMe({open:s,onOpenChange:t,portal:r,dealName:n}){const a=rL(),{isGmailConnected:i,gmailEmail:l}=Oh(),[o,c]=k.useState(r.client_name||""),[d,h]=k.useState(r.client_email||""),[m,x]=k.useState(!1),[g,v]=k.useState(!1),j=s1(r.slug),b=o.split(" ")[0]||"there",N=`Your Transaction Portal – ${n}`,S=`Hi ${b}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${j} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,T=()=>{navigator.clipboard.writeText(j),v(!0),setTimeout(()=>v(!1),2e3),ue.success("Portal link copied!")},A=async()=>{if(!d.trim()){ue.error("Please enter the client email");return}x(!0);try{await a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:D}=await H.functions.invoke("gmail-send",{body:{to:d,subject:N,body:S.replace(/\n/g,"
")}});if(D){let B="";try{const z=D==null?void 0:D.context;if(z&&typeof z.json=="function"){const F=await z.json();B=(F==null?void 0:F.message)||(F==null?void 0:F.error)||""}}catch{}throw new Error(B||D.message||"Failed to send invite")}ue.success(`Invite sent to ${d}`),t(!1)}catch(D){ue.error(D.message||"Failed to send invite")}finally{x(!1)}},P=()=>{const D=encodeURIComponent(N),B=encodeURIComponent(S);window.open(`mailto:${d}?subject=${D}&body=${B}`,"_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(js,{children:e.jsx(bs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(ke,{value:o,onChange:D=>c(D.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(ke,{type:"email",value:d,onChange:D=>h(D.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Portal Link"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted/50 rounded-md px-3 py-2",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:j})}),e.jsx(G,{variant:"outline",size:"icon",onClick:T,className:"shrink-0",children:g?e.jsx(Hn,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ra,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(G,{onClick:A,disabled:m||!d.trim(),className:"w-full",children:[m?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(G,{onClick:P,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(G,{variant:"ghost",onClick:T,className:"w-full text-muted-foreground",children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function RIs({deal:s}){const{isAdmin:t,user:r}=As(),{data:n,isLoading:a}=STs(s.id),i=dAe(),l=rL(),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState(!1),j=`portal-management-ui:${s.id}`;if(k.useEffect(()=>{const D=sessionStorage.getItem(j);if(D)try{const B=JSON.parse(D);h(!!B.settingsOpen),x(!!B.composerOpen),v(!!B.inviteOpen)}catch{sessionStorage.removeItem(j)}},[j]),k.useEffect(()=>{d||m||g?sessionStorage.setItem(j,JSON.stringify({settingsOpen:d,composerOpen:m,inviteOpen:g})):sessionStorage.removeItem(j)},[d,m,g,j]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ls,{className:"h-3 w-3 animate-spin ml-auto"})]})});const b=async()=>{var D,B;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:((B=s.contact)==null?void 0:B.phone)||void 0}),ue.success("Client portal enabled!")}catch{ue.error("Failed to create portal")}finally{c(!1)}},N=async D=>{if(n)try{await l.mutateAsync({id:n.id,is_enabled:D}),ue.success(D?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update portal")}},S=()=>{if(!n)return;const D=s1(n.slug);navigator.clipboard.writeText(D),ue.success("Portal link copied!")},T=()=>{if(!n)return;const D=s1(n.slug);window.open(D,"_blank")};if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(G,{onClick:b,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=s1(n.slug),P=(r==null?void 0:r.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ge,{variant:"outline",className:n.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"})]}),e.jsx(br,{checked:n.is_enabled,onCheckedChange:N})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:n.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:n.require_onboarding?"Required":"Disabled"})]}),n.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:n.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:A})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:S,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ra,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:T,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>v(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Invite"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 w-full",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>x(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Tv,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>h(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(lo,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Kn,{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(li,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(uMe,{open:d,onOpenChange:h,portal:n,dealOwnerId:P}),e.jsx(hMe,{open:m,onOpenChange:x,portalId:n.id,portalSlug:n.slug,notifyClient:n.notify_client}),e.jsx(mMe,{open:g,onOpenChange:v,portal:n,dealName:s.deal_name})]})}const OIs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function FIs(s){return gt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:r}=await H.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 BIs(){const s=es();return Lt({mutationFn:async({dealId:t,contactId:r,role:n})=>{const{data:a,error:i}=await H.from("deal_contacts").insert({deal_id:t,contact_id:r,role:n}).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),ue.success("Contact linked to deal")},onError:t=>{var r;(r=t.message)!=null&&r.includes("duplicate")?ue.error("This contact is already linked to this deal"):ue.error("Failed to link contact")}})}function zIs(){const s=es();return Lt({mutationFn:async({id:t,dealId:r})=>{const{error:n}=await H.from("deal_contacts").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),ue.success("Contact removed from deal")},onError:()=>{ue.error("Failed to remove contact")}})}function $Is({dealId:s,primaryContactId:t}){const r=vr(),{data:n,isLoading:a}=FIs(s),{data:i}=$m(),l=BIs(),o=zIs(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,g]=k.useState("Client"),v=new Set((n==null?void 0:n.map(T=>T.contact_id))||[]);t&&v.add(t);const j=i==null?void 0:i.filter(T=>{var P,D,B;if(v.has(T.id))return!1;if(!h.trim())return!0;const A=h.toLowerCase();return((P=T.first_name)==null?void 0:P.toLowerCase().includes(A))||((D=T.last_name)==null?void 0:D.toLowerCase().includes(A))||((B=T.email)==null?void 0:B.toLowerCase().includes(A))}).slice(0,8),b=T=>{l.mutate({dealId:s,contactId:T,role:x}),d(!1),m("")},N=T=>{o.mutate({id:T,dealId:s})},S={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(n!=null&&n.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Ao,{open:c,onOpenChange:d,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(wo,{className:"w-80 p-3",align:"start",children:e.jsx(UVe,{search:h,setSearch:m,selectedRole:x,setSelectedRole:g,filteredContacts:j,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(fr,{className:"h-4 w-4"}),"Linked Contacts",n&&n.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5",children:n.length})]}),e.jsxs(Ao,{open:c,onOpenChange:d,children:[e.jsx(Mo,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Ws,{className:"h-3.5 w-3.5"})})}),e.jsx(wo,{className:"w-80 p-3",align:"end",children:e.jsx(UVe,{search:h,setSearch:m,selectedRole:x,setSelectedRole:g,filteredContacts:j,onAdd:b})})]})]}),e.jsx("div",{className:"space-y-1.5",children:n==null?void 0:n.map(T=>{var A,P,D,B,z,F,$,X;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(vn,{className:"h-7 w-7",children:e.jsxs(bn,{className:"text-[10px] bg-primary/10 text-primary",children:[(P=(A=T.contact)==null?void 0:A.first_name)==null?void 0:P[0],(B=(D=T.contact)==null?void 0:D.last_name)==null?void 0:B[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>r(`/mission-control/contacts/${T.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(z=T.contact)==null?void 0:z.first_name," ",(F=T.contact)==null?void 0:F.last_name]})}),e.jsx(Ge,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${S[T.role]||S.Other}`,children:T.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[(($=T.contact)==null?void 0:$.phone)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${T.contact.phone}`,children:e.jsx(Nn,{className:"h-3 w-3"})})}),((X=T.contact)==null?void 0:X.email)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${T.contact.email}`,children:e.jsx(Qs,{className:"h-3 w-3"})})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>N(T.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]},T.id)})})]})}function UVe({search:s,setSearch:t,selectedRole:r,setSelectedRole:n,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(zs,{value:r,onValueChange:n,children:[e.jsx(Os,{className:"h-8 text-sm",children:e.jsx(Us,{placeholder:"Role"})}),e.jsx(Fs,{children:OIs.map(l=>e.jsx(mt,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(ti,{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 UIs={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"}},qIs={note:bi,call:Nn,email:Qs,meeting:rn,stage_change:Yr,task_completed:Mn,document:Cn,system:cn};function VIs({deal:s,open:t,onOpenChange:r,onEdit:n,onAddToScorecard:a,isWonStage:i}){var Ee,$e;const{data:l,isLoading:o}=FEs((s==null?void 0:s.id)||""),{data:c,isLoading:d}=zEs((s==null?void 0:s.id)||""),h=BEs(),m=UEs(),x=$Es(),g=OEs(),{data:v,isLoading:j}=CIs((s==null?void 0:s.id)||""),b=TIs(),N=EIs(),S=AIs(),T=k.useRef(null),[A,P]=k.useState(""),[D,B]=k.useState(""),[z,F]=k.useState(!1),[$,X]=k.useState(!1);if(!s)return null;const K=UIs[s.deal_type],Q=(()=>{var Te;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Se=((Te=s.listing)==null?void 0:Te.created_at)||s.listing_date;if(!Se)return null;const ze=s.contract_date?Ul(s.contract_date):new Date;return Kg(ze,Ul(Se))})(),Y=Se=>Se?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Se):"-",ne=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),P(""),ue.success("Note added")}catch{ue.error("Failed to add note")}},de=async()=>{if(D.trim())try{await m.mutateAsync({deal_id:s.id,title:D,sort_order:((c==null?void 0:c.length)||0)+1}),B(""),ue.success("Task added")}catch{ue.error("Failed to add task")}},ce=async(Se,ze)=>{try{await x.mutateAsync({id:Se,is_completed:ze,deal_id:s.id})}catch{ue.error("Failed to update task")}},ae=async()=>{try{await g.mutateAsync(s.id),ue.success("Deal deleted"),r(!1)}catch{ue.error("Failed to delete deal")}},ie=(c==null?void 0:c.filter(Se=>Se.is_completed).length)||0,me=(c==null?void 0:c.length)||0,oe=(v==null?void 0:v.length)||0,ge=Se=>Se<1024?`${Se} B`:Se<1024*1024?`${(Se/1024).toFixed(1)} KB`:`${(Se/(1024*1024)).toFixed(1)} MB`,be=Se=>Se?Se.startsWith("image/")?fl:Se.includes("pdf")?ln:sM:sM,Oe=async Se=>{const ze=Se.target.files;if(!(!ze||!s)){X(!0);try{for(const Te of Array.from(ze)){if(Te.size>20*1024*1024){ue.error(`${Te.name} exceeds 20MB limit`);continue}await b.mutateAsync({dealId:s.id,file:Te})}ue.success("File(s) uploaded")}catch{ue.error("Failed to upload file")}finally{X(!1),T.current&&(T.current.value="")}}},Me=async(Se,ze)=>{if(s)try{await N.mutateAsync({fileId:Se,storagePath:ze,dealId:s.id}),ue.success("File deleted")}catch{ue.error("Failed to delete file")}},Pe=async(Se,ze)=>{try{const Te=await MIs(Se),ye=document.createElement("a");ye.href=Te,ye.download=ze,ye.target="_blank",document.body.appendChild(ye),ye.click(),document.body.removeChild(ye)}catch{ue.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(G2,{open:t,onOpenChange:r,children:e.jsxs(I_,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(W2,{className:"p-6 pb-4 border-b shrink-0",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ge,{variant:"outline",className:Bt("text-xs",K.color),children:K.label}),e.jsxs(Ge,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(K2,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(SIs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>n(s),children:e.jsx(nd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>F(!0),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})}),e.jsx(ti,{className:"flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:!w-full",children:e.jsxs("div",{className:"p-6 space-y-6 min-w-0",children:[s.contact&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(vn,{className:"h-10 w-10",children:e.jsxs(bn,{className:"bg-primary/10 text-primary",children:[(Ee=s.contact.first_name)==null?void 0:Ee[0],($e=s.contact.last_name)==null?void 0:$e[0]]})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-medium",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.contact.email})]}),e.jsxs("div",{className:"flex gap-2",children:[s.contact.phone&&e.jsx(G,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Nn,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(G,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(Qs,{className:"h-4 w-4"})})})]})]}),e.jsx($Is,{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(Cn,{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:Y(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:Y(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?` (${Y(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:Y(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:Y(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(G,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(Zi,{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(Mn,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Q!==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:Bt("text-lg font-bold",Q>90?"text-red-600":Q>60?"text-amber-600":"text-foreground"),children:[Q," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Ss(Ul(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(_l,{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(RIs,{deal:s}),e.jsxs(Rn,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Dn,{className:"w-full grid grid-cols-3",children:[e.jsxs(Xt,{value:"tasks",className:"gap-1",children:[e.jsx(Mn,{className:"h-4 w-4"}),"Tasks ",me>0&&`(${ie}/${me})`]}),e.jsxs(Xt,{value:"files",className:"gap-1",children:[e.jsx(Xj,{className:"h-4 w-4"}),"Files ",oe>0&&`(${oe})`]}),e.jsxs(Xt,{value:"activity",className:"gap-1",children:[e.jsx(cn,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(as,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Add a new task...",value:D,onChange:Se=>B(Se.target.value),onKeyDown:Se=>Se.key==="Enter"&&de()}),e.jsx(G,{onClick:de,disabled:!D.trim(),children:e.jsx(Ws,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[c==null?void 0:c.map(Se=>e.jsxs("div",{className:Bt("flex items-center gap-3 p-3 rounded-lg border transition-colors",Se.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(Ei,{checked:Se.is_completed,onCheckedChange:ze=>ce(Se.id,!!ze)}),e.jsx("span",{className:Bt("flex-1 text-sm",Se.is_completed&&"line-through text-muted-foreground"),children:Se.title}),Se.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(Se.due_date),"MMM d")})]},Se.id)),(c==null?void 0:c.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(as,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:T,className:"hidden",multiple:!0,onChange:Oe,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(G,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Se;return(Se=T.current)==null?void 0:Se.click()},disabled:$,children:[$?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-2"}),$?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[v==null?void 0:v.map(Se=>{const ze=be(Se.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(ze,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Se.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge(Se.file_size)," · ",Ss(new Date(Se.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(A_,{children:e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Se.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>S.mutate({fileId:Se.id,visible:!Se.visible_on_portal,dealId:s.id}),children:Se.visible_on_portal?e.jsx(jn,{className:"h-4 w-4"}):e.jsx(am,{className:"h-4 w-4"})})}),e.jsx(Wl,{side:"top",children:Se.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Pe(Se.storage_path,Se.file_name),children:e.jsx(Xa,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Me(Se.id,Se.storage_path),children:e.jsx(_r,{className:"h-4 w-4"})})]})]},Se.id)}),(v==null?void 0:v.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No files yet. Upload contracts, disclosures, or other documents."})]})]}),e.jsxs(as,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ur,{placeholder:"Add a note...",value:A,onChange:Se=>P(Se.target.value),rows:2}),e.jsxs(G,{onClick:ne,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[l==null?void 0:l.map(Se=>{const ze=qIs[Se.activity_type]||cn;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(ze,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:Se.title}),Se.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Se.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:al(new Date(Se.created_at),{addSuffix:!0})})]})]},Se.id)}),(l==null?void 0:l.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(Yo,{open:z,onOpenChange:F,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Deal?"}),e.jsxs(Uo,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:ae,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function HIs({open:s,onOpenChange:t,deal:r,onComplete:n}){const a=sxe(),i=cft(),{data:l}=IP(),{data:o}=qx(),[c,d]=k.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Ss(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});k.useEffect(()=>{if(r&&s){const x=r.deal_type==="seller"?"seller":"buyer",g=r.expected_price||0,v=r.commission_percentage||3,j=r.expected_commission||g*v/100;d({property_address:r.property_address||r.deal_name||"",city:r.city||"",state:r.state||"",zip:r.zip_code||"",transaction_type:x,close_date:r.actual_close_date||r.target_close_date||Ss(new Date,"yyyy-MM-dd"),sale_price:g,commission_amount:j,lead_source_id:"",client_type_id:"",notes:r.notes||""})}},[r,s]);const h=async x=>{if(x.preventDefault(),!!r)try{const g=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:g.id,actual_close_date:c.close_date}),ue.success("Deal added to Scorecard! 🎉"),t(!1),n==null||n()}catch(g){console.error("Error syncing to scorecard:",g),ue.error("Failed to add to scorecard")}},m=x=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(x);return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{className:"space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20",children:e.jsx(Zi,{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(Fr,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(ke,{id:"property_address",value:c.property_address,onChange:x=>d(g=>({...g,property_address:x.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(ke,{id:"city",value:c.city,onChange:x=>d(g=>({...g,city:x.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(ke,{id:"state",value:c.state,onChange:x=>d(g=>({...g,state:x.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zip",children:"Zip"}),e.jsx(ke,{id:"zip",value:c.zip,onChange:x=>d(g=>({...g,zip:x.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Transaction Type *"}),e.jsxs(zs,{value:c.transaction_type,onValueChange:x=>d(g=>({...g,transaction_type:x})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"buyer",children:"Buyer"}),e.jsx(mt,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(ke,{id:"close_date",type:"date",value:c.close_date,onChange:x=>d(g=>({...g,close_date:x.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(_l,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(ke,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:x=>d(g=>({...g,sale_price:Number(x.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(F3,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(ke,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:x=>d(g=>({...g,commission_amount:Number(x.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Lead Source"}),e.jsxs(zs,{value:c.lead_source_id,onValueChange:x=>d(g=>({...g,lead_source_id:x})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select source"})}),e.jsx(Fs,{children:l==null?void 0:l.map(x=>e.jsx(mt,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Client Type"}),e.jsxs(zs,{value:c.client_type_id,onValueChange:x=>d(g=>({...g,client_type_id:x})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select type"})}),e.jsx(Fs,{children:o==null?void 0:o.map(x=>e.jsx(mt,{value:x.id,children:x.name},x.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(ur,{id:"notes",value:c.notes,onChange:x=>d(g=>({...g,notes:x.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(on,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(G,{type:"submit",disabled:a.isPending||i.isPending,className:"bg-green-600 hover:bg-green-700",children:a.isPending?"Adding...":e.jsxs(e.Fragment,{children:["Add to Scorecard",e.jsx(Ga,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const GIs={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"}},qVe={urgent:0,high:1,medium:2,low:3};function WIs({deals:s,stages:t,onDealClick:r,onStageChange:n}){const[a,i]=k.useState("target_close_date"),[l,o]=k.useState("asc"),c=g=>{a===g?o(v=>v==="asc"?"desc":"asc"):(i(g),o("asc"))},d=k.useMemo(()=>[...s].sort((g,v)=>{var b,N;let j=0;switch(a){case"deal_name":j=g.deal_name.localeCompare(v.deal_name);break;case"stage":{const S=((b=t.find(A=>A.id===g.stage_id))==null?void 0:b.sort_order)||0,T=((N=t.find(A=>A.id===v.stage_id))==null?void 0:N.sort_order)||0;j=S-T;break}case"expected_price":j=(g.expected_price||0)-(v.expected_price||0);break;case"expected_commission":j=(g.expected_commission||0)-(v.expected_commission||0);break;case"target_close_date":{const S=g.target_close_date?Ul(g.target_close_date).getTime():1/0,T=v.target_close_date?Ul(v.target_close_date).getTime():1/0;j=S-T;break}case"priority":j=qVe[g.priority]-qVe[v.priority];break}return l==="asc"?j:-j}),[s,t,a,l]),h=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):"—",m=g=>g?t.find(v=>v.id===g):null,x=({field:g,children:v})=>e.jsxs(G,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(g),children:[v,a===g?l==="asc"?e.jsx(Fd,{className:"ml-2 h-4 w-4"}):e.jsx(Ku,{className:"ml-2 h-4 w-4"}):e.jsx(Rd,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[250px]",children:e.jsx(x,{field:"deal_name",children:"Deal Name"})}),e.jsx(Tt,{className:"w-[150px]",children:e.jsx(x,{field:"stage",children:"Stage"})}),e.jsx(Tt,{className:"w-[100px]",children:"Type"}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(x,{field:"expected_price",children:"Price"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(x,{field:"expected_commission",children:"GCI"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(x,{field:"target_close_date",children:"Close Date"})}),e.jsx(Tt,{className:"w-[100px]",children:e.jsx(x,{field:"priority",children:"Priority"})})]})}),e.jsx(Bn,{children:d.map(g=>{m(g.stage_id);const v=GIs[g.deal_type],j=g.target_close_date?Kg(Ul(g.target_close_date),new Date):null,b=j!==null&&j<0,N=j!==null&&j<=7&&j>=0;return e.jsxs(qs,{className:Bt("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>r(g),children:[e.jsx(ft,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:g.deal_name}),g.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[g.contact.first_name," ",g.contact.last_name]})]})}),e.jsx(ft,{onClick:S=>S.stopPropagation(),children:e.jsx(fxt,{stages:t,currentStageId:g.stage_id||"",onStageSelect:(S,T)=>n(g.id,S,T)})}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",className:Bt("text-xs",v.color),children:v.label})}),e.jsx(ft,{children:e.jsx("span",{className:"font-medium",children:h(g.expected_price)})}),e.jsx(ft,{children:e.jsx("span",{className:"text-emerald-600",children:h(g.expected_commission)})}),e.jsx(ft,{children:g.target_close_date?e.jsxs("div",{className:Bt("flex items-center gap-1 text-sm",b&&"text-red-600",N&&!b&&"text-amber-600"),children:[b&&e.jsx(Hi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Ss(Ul(g.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",className:Bt("text-xs capitalize",g.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",g.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",g.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",g.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:g.priority})})]},g.id)})})]})})}function KIs(){const s=na();return gt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 YIs(s){const t=na();return gt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:r,error:n}=await H.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 ZIs(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 XIs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("deal_tasks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function QIs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("deal_tasks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function fMe(){const s=es();return Lt({mutationFn:async({id:t,status:r})=>{const{data:n,error:a}=await H.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function JIs(){const s=es();return Lt({mutationFn:async t=>{if(t.length===0)return;const{error:r}=await H.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 ePs(s){const t=na();return gt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let r=H.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 tPs(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 sPs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("deal_task_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function rPs(){const s=na(),t=es();return Lt({mutationFn:async({dealId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await H.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 H.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),o=new Set((l||[]).map(m=>m.title)),c=a.filter(m=>!o.has(m.title)).map((m,x)=>({owner_user_id:s,deal_id:r,stage_id:n,title:m.title,description:m.description,priority:m.priority,due_date:m.default_due_offset_days?new Date(Date.now()+m.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:x,status:"todo"}));if(c.length===0)return[];const{data:d,error:h}=await H.from("deal_tasks").insert(c).select();if(h)throw h;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const nPs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function aPs({open:s,onOpenChange:t,dealId:r,dealName:n,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=YIs(s?r:void 0),h=JIs(),m=rPs(),[x,g]=k.useState(new Set),[v,j]=k.useState(!1),b=(c||[]).filter(A=>A.status!=="done");k.useEffect(()=>{b.length>0&&g(new Set(b.map(A=>A.id)))},[c]);const N=A=>{g(P=>{const D=new Set(P);return D.has(A)?D.delete(A):D.add(A),D})},S=async()=>{j(!0);try{const A=Array.from(x);A.length>0&&await h.mutateAsync(A),await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ue.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{j(!1)}},T=async()=>{j(!0);try{await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ue.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{j(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[480px]",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Move Deal"}),e.jsxs(Fr,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:n})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Ge,{variant:"outline",className:"text-sm",children:a}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ge,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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(ti,{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(Ei,{checked:x.has(A.id),onCheckedChange:()=>N(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[nPs[A.priority]," ",A.title]}),A.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:A.stage.color+"20",color:A.stage.color},children:A.stage.name})]},A.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{x.size===b.length?g(new Set):g(new Set(b.map(A=>A.id)))},children:x.size===b.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:T,disabled:v,children:"Skip"}),e.jsxs(G,{size:"sm",onClick:S,disabled:v,children:[v&&e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),x.size>0?`Complete ${x.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Mn,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:S,disabled:v,children:[v&&e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const iPs=[{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 gxt({open:s,onOpenChange:t}){const r=na(),{data:n,isLoading:a}=_rt(),i=ABt(),[l,o]=k.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=k.useState(null);k.useEffect(()=>{s&&o({logo_url:(n==null?void 0:n.logo_url)??null,cover_photo_url:(n==null?void 0:n.cover_photo_url)??null,brand_color:(n==null?void 0:n.brand_color)??null,accent_color:(n==null?void 0:n.accent_color)??null,tagline:(n==null?void 0:n.tagline)??null,welcome_message:(n==null?void 0:n.welcome_message)??null})},[s,n]);const h=g=>o(v=>({...v,...g})),m=async(g,v)=>{if(r){if(g.size>5*1024*1024){ue.error("Image must be under 5MB");return}d(v);try{const j=await wrt(r,g,v);h(v==="logo"?{logo_url:j}:{cover_photo_url:j})}catch(j){ue.error(`Upload failed: ${j.message||j}`)}finally{d(null)}}},x=async()=>{try{await i.mutateAsync(l),ue.success("Portal branding saved"),t(!1)}catch{ue.error("Failed to save branding")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Fr,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(ti,{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(oPs,{draft:l}),e.jsx(VVe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:g=>m(g,"logo"),onClear:()=>h({logo_url:null}),aspect:"square"}),e.jsx(VVe,{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:g=>m(g,"cover"),onClear:()=>h({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Brand Colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for the header background and primary buttons."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:iPs.map(g=>{const v=l.brand_color===g.brand&&l.accent_color===g.accent;return e.jsxs("button",{type:"button",onClick:()=>h({brand_color:g.brand,accent_color:g.accent}),className:Bt("group relative rounded-lg border-2 p-2 text-left transition-all",v?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:g.brand}}),e.jsx("div",{className:"flex-1",style:{background:g.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:g.name})]},g.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(HVe,{label:"Brand",value:l.brand_color,onChange:g=>h({brand_color:g})}),e.jsx(HVe,{label:"Accent",value:l.accent_color,onChange:g=>h({accent_color:g})})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(ke,{value:l.tagline||"",onChange:g=>h({tagline:g.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:g=>h({welcome_message:g.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function oPs({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 VVe({label:s,hint:t,value:r,uploading:n,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:s}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:t}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Bt("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(fl,{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(oa,{className:"h-3.5 w-3.5"}),r?"Replace":"Upload"]})]}),r&&e.jsx(G,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})}function HVe({label:s,value:t,onChange:r}){const n=t||"#000000";return e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:n,onChange:a=>r(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(ke,{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 lPs(){const s=na();return gt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("client_portals").select("*").eq("owner_user_id",s);if(r)throw r;return t||[]},enabled:!!s})}function cPs({dealId:s,dealName:t,contactName:r,portal:n,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=dAe(),d=rL(),h=Vmt(),m=Hmt(),[x,g]=k.useState(!1),v=!!(n!=null&&n.archived_at),j=async()=>{g(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ue.success("Portal enabled!")}catch{ue.error("Failed to create portal")}finally{g(!1)}},b=async P=>{if(n)try{await d.mutateAsync({id:n.id,is_enabled:P}),ue.success(P?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update portal")}},N=()=>{n&&(navigator.clipboard.writeText(s1(n.slug)),ue.success("Link copied!"))},S=()=>{n&&window.open(s1(n.slug),"_blank")},T=async()=>{if(n)try{await h.mutateAsync(n.id),ue.success("Portal archived")}catch{ue.error("Failed to archive portal")}},A=async()=>{if(n)try{await m.mutateAsync(n.id),ue.success("Portal restored")}catch{ue.error("Failed to restore portal")}};return n?v?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Kn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(Ge,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(ZA,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>o(n),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(Kn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(Ge,{variant:"outline",className:n.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"}),e.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N,title:"Copy link",children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:S,title:"Preview",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(n,t),title:"Invite client",children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(n),title:"Post update",children:e.jsx(Tv,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(n),title:"Settings",children:e.jsx(lo,{className:"h-3.5 w-3.5"})}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ix,{className:"h-3.5 w-3.5"})})}),e.jsx(Vd,{align:"end",children:e.jsxs(Da,{onClick:T,children:[e.jsx(Uj,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(br,{checked:n.is_enabled,onCheckedChange:b,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r||"No contact"})]}),e.jsxs(G,{size:"sm",onClick:j,disabled:x,className:"shrink-0 ml-4",children:[x?e.jsx(ls,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function yxt(){const{data:s,isLoading:t}=Ige(),{data:r,isLoading:n}=lPs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=Gmt(),[d,h]=k.useState(null),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(null),[N,S]=k.useState(!1),T=na(),A=t||n,P=new Map;r==null||r.forEach(K=>P.set(K.deal_id,K));const B=[...(s||[]).filter(K=>{var ce,ae,ie,me,oe;const Q=P.get(K.id),Y=a.toLowerCase(),ne=!Y||K.deal_name.toLowerCase().includes(Y)||((ae=(ce=K.contact)==null?void 0:ce.first_name)==null?void 0:ae.toLowerCase().includes(Y))||((me=(ie=K.contact)==null?void 0:ie.last_name)==null?void 0:me.toLowerCase().includes(Y))||((oe=Q==null?void 0:Q.client_name)==null?void 0:oe.toLowerCase().includes(Y));let de=!0;return l==="active"?de=!!(Q!=null&&Q.is_enabled)&&!(Q!=null&&Q.archived_at):l==="disabled"?de=!!Q&&!Q.is_enabled&&!Q.archived_at:l==="archived"?de=!!(Q!=null&&Q.archived_at):l==="none"?de=!Q:l==="all"&&(de=!(Q!=null&&Q.archived_at)||!Q),ne&&de})].sort((K,Q)=>{const Y=P.get(K.id),ne=P.get(Q.id);if(Y!=null&&Y.archived_at&&!(ne!=null&&ne.archived_at))return 1;if(!(Y!=null&&Y.archived_at)&&(ne!=null&&ne.archived_at)||Y&&!ne)return-1;if(!Y&&ne)return 1;if(Y&&ne){if(Y.is_enabled&&!ne.is_enabled)return-1;if(!Y.is_enabled&&ne.is_enabled)return 1}return 0}),z=(r==null?void 0:r.filter(K=>!K.archived_at).length)||0,F=(r==null?void 0:r.filter(K=>K.is_enabled&&!K.archived_at).length)||0,$=(r==null?void 0:r.filter(K=>K.archived_at).length)||0,X=async()=>{if(j)try{await c.mutateAsync({id:j.id,dealId:j.deal_id}),ue.success("Portal permanently deleted"),b(null)}catch{ue.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(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(jr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[z," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[F," active · ",z-F," disabled",$>0&&` · ${$} archived`]})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>S(!0),className:"gap-1.5",children:[e.jsx(pl,{className:"h-3.5 w-3.5"}),"Portal Branding"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search deals or clients...",value:a,onChange:K=>i(K.target.value),className:"pl-9 pr-8"}),a&&e.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(_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(K=>e.jsx(G,{variant:l===K?"secondary":"ghost",size:"sm",onClick:()=>o(K),className:"text-xs px-3 capitalize",children:K==="none"?"No Portal":K},K))})]}),e.jsx(ti,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[B.map(K=>{const Q=P.get(K.id)||null,Y=K.contact?`${K.contact.first_name||""} ${K.contact.last_name||""}`.trim():"";return e.jsx(cPs,{dealId:K.id,dealName:K.deal_name,contactName:Y,portal:Q,onSettingsOpen:h,onComposerOpen:ne=>x(ne),onInviteOpen:(ne,de)=>v({portal:ne,dealName:de}),onDeleteConfirm:b},K.id)}),B.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(jr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(uMe,{open:!!d,onOpenChange:K=>!K&&h(null),portal:d,dealOwnerId:T||""}),m&&e.jsx(hMe,{open:!!m,onOpenChange:K=>!K&&x(null),portalId:m.id,portalSlug:m.slug,notifyClient:m.notify_client}),g&&e.jsx(mMe,{open:!!g,onOpenChange:K=>!K&&v(null),portal:g.portal,dealName:g.dealName}),e.jsx(gxt,{open:N,onOpenChange:S}),e.jsx(Yo,{open:!!j,onOpenChange:K=>!K&&b(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Permanently delete this portal?"}),e.jsx(Uo,{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(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:X,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class dPs 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(_s,{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 iR="deal-pipeline-detail-sheet";function uPs(){var Is;const s=tL(),{data:t,isLoading:r}=Mge(),{data:n,isLoading:a,refetch:i}=Ige(),{data:l,isLoading:o}=qEs(),c=oft(),d=REs(),[h,m]=k.useState("board"),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(null),[S,T]=k.useState(null),[A,P]=k.useState(null),[D,B]=k.useState(null),[z,F]=k.useState(!1),[$,X]=k.useState(null),[K,Q]=k.useState(""),[Y,ne]=k.useState("all"),[de,ce]=k.useState("all"),{data:ae}=gIs(),[ie,me]=k.useState(!1),[oe,ge]=k.useState(!1),[be,Oe]=k.useState(new Set),Me=k.useRef(!1),[Pe,Ee]=k.useState(null),{data:$e}=Xg(),{isTeamLeader:Se,teamMembers:ze}=pIs(),Te=k.useMemo(()=>Array.from(be),[be]),{data:ye}=xIs(Te),ct=k.useMemo(()=>{const fs=new Map;return ze.forEach(ar=>fs.set(ar.id,{name:ar.name,avatar_url:ar.avatar_url,color:ar.color})),fs},[ze]),ve=k.useCallback(fs=>fs.owner_user_id&&ct.get(fs.owner_user_id)||null,[ct]),rt=k.useCallback(fs=>{Oe(ar=>{const Er=new Set(ar);return Er.has(fs)?Er.delete(fs):Er.add(fs),Er})},[]);k.useEffect(()=>{!r&&t&&t.length===0&&c.mutate()},[r,t]);const[Re,Qe]=Lc(),Ke=k.useRef(!1);k.useEffect(()=>{const fs=Re.get("deal");if(fs&&n&&n.length>0&&!Ke.current){const ar=n.find(Er=>Er.id===fs);ar&&(Ke.current=!0,N(ar),j(!0),Re.delete("deal"),Qe(Re,{replace:!0}))}},[n,Re]);const Ce=k.useMemo(()=>{if(!ye||!t)return[];const fs=new Map(t.map(ar=>[ar.name,ar.id]));return ye.map(ar=>{const Er=ar._stage_name&&fs.get(ar._stage_name)||null;return{...ar,stage_id:Er||ar.stage_id}})},[ye,t]),nt=k.useMemo(()=>[...n||[],...Ce],[n,Ce]);k.useEffect(()=>{if(Me.current||nt.length===0)return;Me.current=!0;const fs=sessionStorage.getItem(iR);if(fs)try{const ar=JSON.parse(fs);if(!ar.open||!ar.dealId)return;const Er=nt.find(Tr=>Tr.id===ar.dealId);Er&&(N(Er),j(!0))}catch{sessionStorage.removeItem(iR)}},[nt]),k.useEffect(()=>{v&&(b!=null&&b.id)?sessionStorage.setItem(iR,JSON.stringify({dealId:b.id,open:!0})):sessionStorage.removeItem(iR)},[v,b==null?void 0:b.id]);const $t=(ae==null?void 0:ae.byDeal)||{},lt=(ae==null?void 0:ae.unique)||[],it=nt.filter(fs=>{var kr,Sr,hn,zn,Xs,Ur;const ar=K.toLowerCase(),Er=$t[fs.id]||[],Tr=!ar||fs.deal_name.toLowerCase().includes(ar)||((Sr=(kr=fs.contact)==null?void 0:kr.first_name)==null?void 0:Sr.toLowerCase().includes(ar))||((zn=(hn=fs.contact)==null?void 0:hn.last_name)==null?void 0:zn.toLowerCase().includes(ar))||((Xs=fs.property_address)==null?void 0:Xs.toLowerCase().includes(ar))||((Ur=fs.city)==null?void 0:Ur.toLowerCase().includes(ar))||Er.some(xn=>xn.toLowerCase().includes(ar)),Lr=Y==="all"||fs.deal_type===Y,$r=de==="all"||Er.includes(de);return Tr&&Lr&&$r}),Nt=k.useMemo(()=>{if(!t)return l||null;const fs=new Set(t.filter(kr=>kr.is_won_stage).map(kr=>kr.id)),ar=new Set(t.filter(kr=>kr.is_lost_stage).map(kr=>kr.id)),Er=nt.filter(kr=>kr.stage_id&&!fs.has(kr.stage_id)&&!ar.has(kr.stage_id)),Tr=nt.filter(kr=>kr.stage_id&&fs.has(kr.stage_id)),Lr=new Date().getFullYear(),$r=Tr.filter(kr=>kr.actual_close_date?new Date(kr.actual_close_date).getFullYear()===Lr:!0);return{totalDeals:nt.length,activeDeals:Er.length,wonDeals:Tr.length,pipelineValue:Er.reduce((kr,Sr)=>kr+(Sr.expected_price||0),0),expectedCommission:Er.reduce((kr,Sr)=>kr+(Sr.expected_commission||0),0),expectedNetToAgent:Er.reduce((kr,Sr)=>kr+(Pg(Sr)||0),0),wonValue:Tr.reduce((kr,Sr)=>kr+(Sr.expected_price||0),0),weightedGCI:Er.reduce((kr,Sr)=>kr+(Sr.expected_commission||0)*((Sr.probability??50)/100),0),weightedNet:Er.reduce((kr,Sr)=>kr+(Pg(Sr)||0)*((Sr.probability??50)/100),0),ytdWonDeals:$r.length,ytdWonGCI:$r.reduce((kr,Sr)=>kr+(Sr.expected_commission||0),0),ytdWonNet:$r.reduce((kr,Sr)=>kr+(Pg(Sr)||0),0),projectedAnnualNet:$r.reduce((kr,Sr)=>kr+(Pg(Sr)||0),0)+Er.reduce((kr,Sr)=>kr+(Pg(Sr)||0)*((Sr.probability??50)/100),0)}},[nt,t,l]),Ft=fs=>{N(fs),j(!0)},at=fs=>{T(fs||null),N(null),g(!0)},Ie=fs=>{N(fs),j(!1),g(!0)},et=fs=>{j(fs),fs||sessionStorage.removeItem(iR)},Dt=(fs,ar)=>{P(fs)},Jt=(fs,ar)=>{fs.preventDefault(),fs.dataTransfer.dropEffect="move",B(ar)},cs=async(fs,ar)=>{if(fs.preventDefault(),B(null),!A)return;const Er=n==null?void 0:n.find($r=>$r.id===A),Tr=t==null?void 0:t.find($r=>$r.id===ar),Lr=t==null?void 0:t.find($r=>$r.id===(Er==null?void 0:Er.stage_id));if(!Er||!Tr||Er.stage_id===ar){P(null);return}Ee({dealId:A,dealName:Er.deal_name,fromStageName:(Lr==null?void 0:Lr.name)||"Unknown",toStageName:Tr.name,toStageId:ar,isWonStage:Tr.is_won_stage,deal:Er}),P(null)},Ht=async()=>{if(!Pe)return;const{dealId:fs,toStageId:ar,toStageName:Er,isWonStage:Tr,deal:Lr}=Pe;if(await d.mutateAsync({dealId:fs,stageId:ar,stageName:Er}),ue.success(`Moved to ${Er}`),Tr&&!Lr.scorecard_transaction_id){const $r={...Lr,stage_id:ar};X($r),F(!0)}},dt=k.useCallback(async(fs,ar,Er)=>{const Tr=n==null?void 0:n.find(kr=>kr.id===fs),Lr=t==null?void 0:t.find(kr=>kr.id===ar),$r=t==null?void 0:t.find(kr=>kr.id===(Tr==null?void 0:Tr.stage_id));!Tr||!Lr||Tr.stage_id===ar||Ee({dealId:fs,dealName:Tr.deal_name,fromStageName:($r==null?void 0:$r.name)||"Unknown",toStageName:Er,toStageId:ar,isWonStage:Lr.is_won_stage,deal:Tr})},[n,t]),Qt=fs=>it.filter(ar=>ar.stage_id===fs),yt=r||a,ss=s?"list":h;return e.jsxs(_s,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(Di,{className:"h-4 w-4"})}),!s&&e.jsx(A_,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:h==="board"?"secondary":"ghost",size:"sm",onClick:()=>m("board"),className:"px-3 gap-1.5",children:[e.jsx(Sf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(Wl,{children:"Kanban board view"})]}),e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:h==="list"?"secondary":"ghost",size:"sm",onClick:()=>m("list"),className:"px-3 gap-1.5",children:[e.jsx(lm,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(Wl,{children:"Grouped list view"})]}),e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:h==="table"?"secondary":"ghost",size:"sm",onClick:()=>m("table"),className:"px-3 gap-1.5",children:[e.jsx(fM,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(Wl,{children:"Sortable table view"})]}),e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsxs(G,{variant:h==="portals"?"secondary":"ghost",size:"sm",onClick:()=>m("portals"),className:"px-3 gap-1.5",children:[e.jsx(jr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(Wl,{children:"Client portal management"})]})]})}),$e&&!Se&&e.jsxs(G,{variant:"outline",onClick:()=>me(!0),children:[e.jsx(fr,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(G,{onClick:()=>at(),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),ss!=="portals"&&e.jsx(_Is,{stats:Nt,isLoading:o}),ss!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search deals, contacts, addresses, tags...",value:K,onChange:fs=>Q(fs.target.value),className:"pl-9 pr-8"}),K&&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(zs,{value:Y,onValueChange:ne,children:[e.jsx(Os,{className:"w-[140px]",children:e.jsx(Us,{placeholder:"All Types"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Types"}),e.jsx(mt,{value:"buyer",children:"Buyer"}),e.jsx(mt,{value:"seller",children:"Seller"}),e.jsx(mt,{value:"dual",children:"Dual"}),e.jsx(mt,{value:"referral",children:"Referral"}),e.jsx(mt,{value:"lease",children:"Lease"})]})]}),e.jsxs(zs,{value:de,onValueChange:ce,children:[e.jsxs(Os,{className:"w-[160px]",children:[e.jsx(Ah,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(Us,{placeholder:"All Tags"})]}),e.jsxs(Fs,{className:"max-h-[300px]",children:[e.jsx(mt,{value:"all",children:"All Tags"}),lt.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),lt.map(fs=>e.jsx(mt,{value:fs,children:fs},fs))]})]}),de!=="all"&&e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Ah,{className:"h-3 w-3"}),de,e.jsx("button",{onClick:()=>ce("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(_r,{className:"h-3 w-3"})})]}),(K||Y!=="all"||de!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[it.length," of ",(n==null?void 0:n.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Se&&!s&&ze.length>0&&e.jsx(fIs,{members:ze,enabledMembers:be,onToggleMember:rt,isOpen:oe,onToggleOpen:()=>ge(fs=>!fs)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:yt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(fs=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Vs,{className:"h-full rounded-xl"})},fs))}):ss==="board"?e.jsxs(ti,{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(fs=>e.jsx(bIs,{stage:fs,deals:Qt(fs.id),onDealClick:Ft,onAddDeal:at,onDragStart:Dt,onDragOver:Jt,onDrop:cs,isDragOver:D===fs.id,isWonStage:fs.is_won_stage,getOwnerInfo:ve},fs.id))}),e.jsx(Ppe,{orientation:"horizontal"})]}):ss==="table"?e.jsx(ti,{className:"h-full",children:e.jsx(WIs,{deals:it,stages:t||[],onDealClick:Ft,onStageChange:dt})}):ss==="portals"?e.jsx(yxt,{}):e.jsx(ti,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(fs=>{const ar=Qt(fs.id);return ar.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:fs.color}}),e.jsx("h3",{className:"font-semibold",children:fs.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",ar.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:ar.map(Er=>e.jsx(pxt,{deal:Er,onClick:()=>Ft(Er),stages:t,onStageChange:dt,showStagePicker:!0,isWonStage:fs.is_won_stage,ownerInfo:ve(Er)},Er.id))})]},fs.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(Sf,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs(G,{onClick:()=>at(),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((n==null?void 0:n.length)||0)>0&&it.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(fn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(G,{variant:"outline",onClick:()=>{Q(""),ne("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(kIs,{open:x,onOpenChange:g,deal:b,defaultStageId:S}),e.jsx(VIs,{deal:b,open:v,onOpenChange:et,onEdit:Ie,isWonStage:b?(Is=t==null?void 0:t.find(fs=>fs.id===b.stage_id))==null?void 0:Is.is_won_stage:!1,onAddToScorecard:fs=>{X(fs),F(!0),j(!1)}}),e.jsx(HIs,{open:z,onOpenChange:F,deal:$,onComplete:()=>{i(),X(null)}}),Pe&&e.jsx(aPs,{open:!!Pe,onOpenChange:fs=>{fs||Ee(null)},dealId:Pe.dealId,dealName:Pe.dealName,fromStageName:Pe.fromStageName,toStageName:Pe.toStageName,toStageId:Pe.toStageId,onConfirm:Ht}),e.jsx(hIs,{open:ie,onOpenChange:me})]})}function hPs(){return e.jsx(dPs,{children:e.jsx(uPs,{})})}function vxt({open:s,onOpenChange:t,editTask:r,defaultDealId:n,defaultStageId:a}){var Q;const i=ZIs(),l=XIs(),{data:o}=Ige(),c=na(),{data:d}=gt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:Y,error:ne}=await H.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(ne)throw ne;return Y},enabled:!!c&&s}),[h,m]=k.useState(""),[x,g]=k.useState(""),[v,j]=k.useState("none"),[b,N]=k.useState("none"),[S,T]=k.useState("medium"),[A,P]=k.useState("todo"),[D,B]=k.useState(),[z,F]=k.useState(!1),[$,X]=k.useState(!1);k.useEffect(()=>{r?(m(r.title),g(r.description||""),j(r.deal_id||"none"),N(r.contact_id||"none"),T(r.priority),P(r.status),B(r.due_date?ff(r.due_date):void 0)):(m(""),g(""),j(n||"none"),N("none"),T("medium"),P("todo"),B(void 0))},[r,s,n]);const K=async()=>{if(!h.trim()){ue.error("Task title is required");return}try{const Y={title:h.trim(),description:x.trim()||null,deal_id:v==="none"?null:v,contact_id:b==="none"?null:b,stage_id:a||null,priority:S,status:A,due_date:D?Ss(D,"yyyy-MM-dd"):null};r?(await l.mutateAsync({id:r.id,...Y}),ue.success("Task updated")):(await i.mutateAsync(Y),ue.success("Task created")),t(!1)}catch{ue.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(js,{children:e.jsx(bs,{children:r?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title *"}),e.jsx(ke,{value:h,onChange:Y=>m(Y.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:x,onChange:Y=>g(Y.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Priority"}),e.jsxs(zs,{value:S,onValueChange:Y=>T(Y),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"low",children:"🟢 Low"}),e.jsx(mt,{value:"medium",children:"🟡 Medium"}),e.jsx(mt,{value:"high",children:"🟠 High"}),e.jsx(mt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Status"}),e.jsxs(zs,{value:A,onValueChange:Y=>P(Y),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"todo",children:"To Do"}),e.jsx(mt,{value:"in_progress",children:"In Progress"}),e.jsx(mt,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Due Date"}),e.jsxs(Ao,{children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:Bt("w-full justify-start text-left font-normal",!D&&"text-muted-foreground"),children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),D?Ss(D,"PPP"):"Pick a date"]})}),e.jsx(wo,{className:"w-auto p-0",align:"start",children:e.jsx(Nx,{mode:"single",selected:D,onSelect:B,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Link to Deal"}),e.jsxs(Ao,{open:z,onOpenChange:F,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?((Q=o==null?void 0:o.find(Y=>Y.id===v))==null?void 0:Q.deal_name)||"Select deal":"No Deal"]}),e.jsx(xx,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search deals..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:"No deals found."}),e.jsxs(Rx,{children:[e.jsxs(vf,{value:"no-deal",onSelect:()=>{j("none"),F(!1)},children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(Y=>e.jsxs(vf,{value:Y.deal_name,onSelect:()=>{j(Y.id),F(!1)},children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",v===Y.id?"opacity-100":"opacity-0")}),Y.deal_name]},Y.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Link to Contact"}),e.jsxs(Ao,{open:$,onOpenChange:X,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Bi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),b!=="none"?(()=>{const Y=d==null?void 0:d.find(ne=>ne.id===b);return Y?`${Y.first_name} ${Y.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(xx,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search contacts..."}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:"No contacts found."}),e.jsxs(Rx,{children:[e.jsxs(vf,{value:"no-contact",onSelect:()=>{N("none"),X(!1)},children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",b==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(Y=>e.jsxs(vf,{value:`${Y.first_name} ${Y.last_name}`,onSelect:()=>{N(Y.id),X(!1)},children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",b===Y.id?"opacity-100":"opacity-0")}),Y.first_name," ",Y.last_name]},Y.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:i.isPending||l.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const mPs={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 fPs({tasks:s}){const t=fMe(),r=QIs(),n=vr(),[a,i]=k.useState(null),l=async h=>{const m=h.status==="done"?"todo":"done";try{await t.mutateAsync({id:h.id,status:m})}catch{ue.error("Failed to update task")}},o=async h=>{try{await r.mutateAsync(h),ue.success("Task deleted")}catch{ue.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(Mn,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),e.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const c=new Map,d=[];return s.forEach(h=>{if(h.deal){const m=c.get(h.deal.id)||{dealName:h.deal.deal_name,tasks:[]};m.tasks.push(h),c.set(h.deal.id,m)}else d.push(h)}),e.jsxs("div",{className:"space-y-4",children:[d.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:e.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),d.map(h=>e.jsx(GVe,{task:h,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:m=>n(`/mission-control/pipeline?deal=${m}`)},h.id))]}),Array.from(c.entries()).map(([h,m])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${h}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:m.dealName}),e.jsxs(Ge,{variant:"secondary",className:"ml-auto text-xs",children:[m.tasks.filter(x=>x.status==="done").length,"/",m.tasks.length]}),e.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),m.tasks.map(x=>e.jsx(GVe,{task:x,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:g=>n(`/mission-control/pipeline?deal=${g}`)},x.id))]},h)),a&&e.jsx(vxt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function GVe({task:s,onToggle:t,onDelete:r,onEdit:n,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&Xv(ff(s.due_date))&&!qu(ff(s.due_date)),o=!i&&s.due_date&&qu(ff(s.due_date)),c=mPs[s.priority];return e.jsxs("div",{className:Bt("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(Mn,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Bd,{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:Bt("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(Bi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Ge,{variant:"outline",className:Bt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Bt("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(cn,{className:"h-3 w-3"}),Ss(ff(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(nd,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>r(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const pPs=[{status:"todo",label:"To Do",icon:Bd,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:mf,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Mn,color:"border-t-emerald-500"}],xPs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function gPs({tasks:s}){const t=fMe(),r=k.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),n=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{ue.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:pPs.map(i=>e.jsxs("div",{className:Bt("border rounded-lg border-t-4 bg-muted/20",i.color),onDragOver:l=>l.preventDefault(),onDrop:l=>a(l,i.status),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[e.jsx(i.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm",children:i.label}),e.jsx(Ge,{variant:"secondary",className:"ml-auto text-xs",children:r[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[i.status].map(l=>e.jsx(yPs,{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 yPs({task:s,onDragStart:t}){const r=s.status==="done",n=!r&&s.due_date&&Xv(ff(s.due_date))&&!qu(ff(s.due_date)),a=!r&&s.due_date&&qu(ff(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Bt("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:xPs[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Bt("text-sm font-medium",r&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Sa,{className:"h-2.5 w-2.5"}),s.deal.deal_name]}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Bi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Bt("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(cn,{className:"h-2.5 w-2.5"}),n?"Overdue — ":a?"Due today — ":"",Ss(ff(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 WVe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function vPs({tasks:s}){const[t,r]=k.useState(new Date),n=fMe(),a=Hc(t),i=jg(t),l=Fm(a),o=Cpe(i),c=UIt({start:l,end:o}),d=k.useMemo(()=>{const x=new Map;return s.forEach(g=>{if(!g.due_date)return;const v=g.due_date,j=x.get(v)||[];j.push(g),x.set(v,j)}),x},[s]),h=k.useMemo(()=>s.filter(x=>!x.due_date),[s]),m=async x=>{const g=x.status==="done"?"todo":"done";try{await n.mutateAsync({id:x.id,status:g})}catch{ue.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>r(q4(t,1)),children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Ss(t,"MMMM yyyy")}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>r(Cf(t,1)),children:e.jsx(ya,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(x=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:x},x))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(x=>{const g=Ss(x,"yyyy-MM-dd"),v=d.get(g)||[],j=Epe(x,t),b=qu(x);return e.jsxs("div",{className:Bt("border-r border-b min-h-[100px] p-1",!j&&"bg-muted/30",b&&"bg-primary/5"),children:[e.jsx("div",{className:Bt("text-xs font-medium mb-1 text-right px-1",!j&&"text-muted-foreground/40",b&&"text-primary font-bold"),children:Ss(x,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[v.slice(0,3).map(N=>e.jsxs("button",{onClick:()=>m(N),className:Bt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",N.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[N.status==="done"?e.jsx(Mn,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Bd,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[WVe[N.priority]," ",N.title]})]},N.id)),v.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",v.length-3," more"]})]})]},g)})}),h.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",h.length,")"]}),e.jsx("div",{className:"space-y-1",children:h.map(x=>e.jsxs("button",{onClick:()=>m(x),className:Bt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",x.status==="done"&&"opacity-50 line-through"),children:[x.status==="done"?e.jsx(Mn,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Bd,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[WVe[x.priority]," ",x.title]}),x.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",x.deal.deal_name]})]},x.id))})]})]})}const bPs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function _Ps({open:s,onOpenChange:t,stages:r}){var N;const[n,a]=k.useState(((N=r[0])==null?void 0:N.id)||""),{data:i,isLoading:l}=ePs(n||void 0),o=tPs(),c=sPs(),[d,h]=k.useState(""),[m,x]=k.useState("medium"),[g,v]=k.useState(""),j=async()=>{if(!(!d.trim()||!n))try{await o.mutateAsync({stage_id:n,title:d.trim(),priority:m,default_due_offset_days:g?parseInt(g):null,sort_order:((i==null?void 0:i.length)||0)+1}),h(""),v(""),ue.success("Template added")}catch{ue.error("Failed to add template")}},b=async S=>{try{await c.mutateAsync(S),ue.success("Template deleted")}catch{ue.error("Failed to delete template")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[560px]",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(nO,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),e.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),e.jsxs("div",{children:[e.jsx(he,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(S=>!S.is_won_stage&&!S.is_lost_stage).map(S=>e.jsx("button",{onClick:()=>a(S.id),className:Bt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===S.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:S.name},S.id))})]}),e.jsx(ti,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((S,T)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[e.jsx("span",{className:"text-xs",children:bPs[S.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:S.title}),S.default_due_offset_days&&e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:["+",S.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>b(S.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},S.id)),(i==null?void 0:i.length)===0&&n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Task title...",value:d,onChange:S=>h(S.target.value),className:"flex-1",onKeyDown:S=>S.key==="Enter"&&j()}),e.jsxs(zs,{value:m,onValueChange:S=>x(S),children:[e.jsx(Os,{className:"w-[100px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"low",children:"🟢 Low"}),e.jsx(mt,{value:"medium",children:"🟡 Med"}),e.jsx(mt,{value:"high",children:"🟠 High"}),e.jsx(mt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(ke,{type:"number",placeholder:"e.g., 7",value:g,onChange:S=>v(S.target.value)})]}),e.jsxs(G,{onClick:j,disabled:!d.trim()||o.isPending,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function wPs(){const{data:s,isLoading:t}=KIs(),{data:r}=Mge(),[n,a]=k.useState("list"),[i,l]=k.useState(""),[o,c]=k.useState("active"),[d,h]=k.useState("all"),[m,x]=k.useState("all"),[g,v]=k.useState(!1),[j,b]=k.useState(!1),N=k.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(P=>{P.deal&&A.set(P.deal.id,P.deal.deal_name)}),Array.from(A,([P,D])=>({id:P,name:D}))},[s]),S=k.useMemo(()=>s?s.filter(A=>{var $,X,K,Q;const P=i.toLowerCase(),D=!P||A.title.toLowerCase().includes(P)||((X=($=A.deal)==null?void 0:$.deal_name)==null?void 0:X.toLowerCase().includes(P))||`${((K=A.contact)==null?void 0:K.first_name)||""} ${((Q=A.contact)==null?void 0:Q.last_name)||""}`.toLowerCase().includes(P),B=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&&Xv(ff(A.due_date))&&!qu(ff(A.due_date)),z=d==="all"||A.priority===d,F=m==="all"||m==="no_deal"&&!A.deal_id||A.deal_id===m;return D&&B&&z&&F}):[],[s,i,o,d,m]),T=k.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(P=>P.status!=="done");return{total:A.length,overdue:A.filter(P=>P.due_date&&Xv(ff(P.due_date))&&!qu(ff(P.due_date))).length,dueToday:A.filter(P=>P.due_date&&qu(ff(P.due_date))).length,dueThisWeek:A.filter(P=>P.due_date&&FLt(ff(P.due_date))).length,completed:s.filter(P=>P.status==="done").length}},[s]);return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>b(!0),children:[e.jsx(s0,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(G,{size:"sm",onClick:()=>v(!0),children:[e.jsx(Ws,{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(lm,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.total})]}),e.jsxs("button",{onClick:()=>c("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${o==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[e.jsx(od,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:T.overdue})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[e.jsx(cn,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.dueToday})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[e.jsx(pd,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.dueThisWeek})]}),e.jsxs("button",{onClick:()=>c("done"),className:`p-3 rounded-lg border text-left transition-colors ${o==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.completed})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:d,onValueChange:h,children:[e.jsx(Os,{className:"w-[130px]",children:e.jsx(Us,{placeholder:"Priority"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Priorities"}),e.jsx(mt,{value:"urgent",children:"🔴 Urgent"}),e.jsx(mt,{value:"high",children:"🟠 High"}),e.jsx(mt,{value:"medium",children:"🟡 Medium"}),e.jsx(mt,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{className:"w-[160px]",children:e.jsx(Us,{placeholder:"Deal"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Deals"}),e.jsx(mt,{value:"no_deal",children:"No Deal"}),N.map(A=>e.jsx(mt,{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(lm,{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(Uv,{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(pd,{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(fPs,{tasks:S}),n==="kanban"&&e.jsx(gPs,{tasks:S}),n==="calendar"&&e.jsx(vPs,{tasks:S})]}),e.jsx(vxt,{open:g,onOpenChange:v}),e.jsx(_Ps,{open:j,onOpenChange:b,stages:r||[]})]})})}function bxt(){const s=na();return gt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 jPs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("portal_referrals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function NPs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("portal_referrals").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const kPs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),T_e=[{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"}],SPs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function _xt(){const{data:s=[],isLoading:t}=bxt(),r=jPs(),n=NPs(),[a,i]=k.useState("all"),[l,o]=k.useState({}),c=k.useMemo(()=>a==="all"?s:s.filter(g=>g.status===a),[s,a]),d=k.useMemo(()=>({total:s.length,new:s.filter(g=>g.status==="new").length,converted:s.filter(g=>g.status==="converted").length}),[s]),h=(g,v)=>{r.mutate({id:g.id,status:v}),ue.success("Status updated")},m=g=>{const v=l[g.id];r.mutate({id:g.id,agent_notes:v}),o(j=>{const{[g.id]:b,...N}=j;return N}),ue.success("Notes saved")},x=g=>{confirm(`Delete referral for ${g.friend_name}?`)&&n.mutate(g.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(il,{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(li,{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"},...T_e.map(g=>({v:g.value,l:g.label}))].map(g=>e.jsx("button",{onClick:()=>i(g.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===g.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:g.l},g.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(Ne,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(li,{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(g=>{var N,S;const v=T_e.find(T=>T.value===g.status),j=(N=g.client_portals)==null?void 0:N.slug,b=g.referrer_name||((S=g.client_portals)==null?void 0:S.client_name)||"Anonymous client";return e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:g.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(rn,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:b})," ·"," ",kPs(g.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"outline",className:v==null?void 0:v.className,children:(v==null?void 0:v.label)||g.status}),e.jsxs(zs,{value:g.status,onValueChange:T=>h(g,T),children:[e.jsx(Os,{className:"h-8 w-[130px] text-xs",children:e.jsx(Us,{})}),e.jsx(Fs,{children:T_e.map(T=>e.jsx(mt,{value:T.value,className:"text-xs",children:T.label},T.value))})]})]})]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.friend_interest&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:SPs[g.friend_interest]||g.friend_interest}),g.friend_email&&e.jsxs("a",{href:`mailto:${g.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Qs,{className:"h-3 w-3"}),g.friend_email]}),g.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${g.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Nn,{className:"h-3 w-3"}),g.friend_phone]}),e.jsxs("a",{href:`sms:${g.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(tc,{className:"h-3 w-3"}),"Text"]})]})]}),g.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:['"',g.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[g.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ur,{value:l[g.id],onChange:T=>o(A=>({...A,[g.id]:T.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",onClick:()=>m(g),children:"Save"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>o(T=>{const{[g.id]:A,...P}=T;return P}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(T=>({...T,[g.id]:g.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:g.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:[j&&e.jsxs("a",{href:`/portal/${j}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>x(g),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]},g.id)})})]})}function wxt({vendor:s,onEdit:t,onDelete:r,onToggleVisible:n,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=XB.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(Ne,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Kc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Qn,{className:"w-3.5 h-3.5 text-amber-500 fill-amber-500","aria-label":"Featured"})]}),s.company&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.company}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Ge,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:[l," clicks"]})]})]})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[s.phone&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{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(gc,{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(rn,{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(ja,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[n&&e.jsxs(G,{size:"sm",variant:a?"default":"outline",onClick:()=>n(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(jn,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(am,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(G,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(nd,{className:"w-3.5 h-3.5"})}),r&&e.jsx(G,{size:"sm",variant:"ghost",onClick:r,className:"text-destructive",children:e.jsx(yr,{className:"w-3.5 h-3.5"})})]})]})}function jxt({open:s,onOpenChange:t,vendor:r,ownerType:n,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=fBt(),[c,d]=k.useState({}),[h,m]=k.useState(!1),x=k.useRef(null),g=async b=>{if(!b.type.startsWith("image/")){ue.error("Please select an image");return}if(b.size>5*1024*1024){ue.error("Image must be under 5MB");return}m(!0);try{const N=b.name.split(".").pop()||"png",S=`${n}/${a||i||"misc"}/${Date.now()}.${N}`,{error:T}=await H.storage.from("vendor-logos").upload(S,b,{upsert:!0,contentType:b.type});if(T)throw T;const{data:A}=H.storage.from("vendor-logos").getPublicUrl(S);d(P=>({...P,logo_url:A.publicUrl})),ue.success("Logo uploaded")}catch(N){ue.error(N.message||"Upload failed")}finally{m(!1)}};k.useEffect(()=>{s&&d(r||{owner_type:n,owner_brokerage_id:n==="brokerage"&&a||null,owner_user_id:n==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,r,n,a,i]);const v=(b,N)=>d(S=>({...S,[b]:N})),j=async()=>{var b;if(!((b=c.name)!=null&&b.trim())){ue.error("Name is required");return}try{await o.mutateAsync(c),ue.success(r?"Vendor updated":"Vendor added"),t(!1)}catch(N){ue.error(N.message||"Failed to save vendor")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{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(he,{children:"Contact Name *"}),e.jsx(ke,{value:c.name||"",onChange:b=>v("name",b.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Company"}),e.jsx(ke,{value:c.company||"",onChange:b=>v("company",b.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Category"}),e.jsxs(zs,{value:c.category,onValueChange:b=>v("category",b),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:XB.map(b=>e.jsx(mt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(ke,{value:c.phone||"",onChange:b=>v("phone",b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(ke,{type:"email",value:c.email||"",onChange:b=>v("email",b.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Website"}),e.jsx(ke,{value:c.website||"",onChange:b=>v("website",b.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Logo"}),e.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];N&&g(N),b.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>v("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(_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(oa,{className:"h-5 w-5"})}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=x.current)==null?void 0:b.click()},disabled:h,children:[h?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Address"}),e.jsx(ke,{value:c.address||"",onChange:b=>v("address",b.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{rows:3,value:c.description||"",onChange:b=>v("description",b.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Primary Action"}),e.jsxs(zs,{value:c.action_type,onValueChange:b=>v("action_type",b),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:uBt.map(b=>e.jsx(mt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Booking URL (Calendly etc.)"}),e.jsx(ke,{value:c.booking_url||"",onChange:b=>v("booking_url",b.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Compliance Disclosure (optional)"}),e.jsx(ur,{rows:2,value:c.disclosure_text||"",onChange:b=>v("disclosure_text",b.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(br,{checked:!!c.is_active,onCheckedChange:b=>v("is_active",b)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(br,{checked:!!c.is_featured,onCheckedChange:b=>v("is_featured",b)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(br,{checked:!!c.is_required,onCheckedChange:b=>v("is_required",b)})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:j,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function Nxt({embedded:s=!1}={}){const t=na(),{brokerageId:r}=As(),{data:n,isLoading:a}=mBt(),{data:i={}}=grt("agent",t),l=xrt(),o=pBt(),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,g]=k.useState(""),[v,j]=k.useState("all"),b=(n==null?void 0:n.vendors)||[],N=(n==null?void 0:n.selections)||[],S=k.useMemo(()=>{const $=new Map;return N.forEach(X=>$.set(X.vendor_id,X.is_visible)),$},[N]),T=k.useMemo(()=>b.filter($=>!(v!=="all"&&$.category!==v||x&&!`${$.name} ${$.company||""}`.toLowerCase().includes(x.toLowerCase()))),[b,x,v]),A=T.filter($=>$.owner_type==="agent"),P=T.filter($=>$.owner_type==="brokerage"),D=async $=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync($),ue.success("Vendor deleted")}catch(X){ue.error(X.message)}},B=async($,X)=>{try{await o.mutateAsync({vendorId:$,isVisible:X})}catch(K){ue.error(K.message)}},z=$=>$.is_required?!0:S.get($.id)??$.owner_type==="agent",F=e.jsxs("div",{className:s?"space-y-6":"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Yu,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ws,{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(fn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ke,{className:"pl-9",placeholder:"Search vendors...",value:x,onChange:$=>g($.target.value)})]}),e.jsxs("select",{value:v,onChange:$=>j($.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),XB.map($=>e.jsx("option",{value:$.value,children:$.label},$.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(Rn,{defaultValue:r?"all":"personal",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"all",children:["All (",T.length,")"]}),r&&e.jsxs(Xt,{value:"brokerage",children:["From Brokerage (",P.length,")"]}),e.jsxs(Xt,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(as,{value:"all",className:"mt-4",children:e.jsx(E_e,{vendors:T,isVisibleInPortals:z,onToggle:B,onEdit:$=>{d($),m(!0)},onDelete:D,userId:t,clicks:i})}),r&&e.jsx(as,{value:"brokerage",className:"mt-4",children:P.length===0?e.jsx(KVe,{icon:e.jsx(jr,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(E_e,{vendors:P,isVisibleInPortals:z,onToggle:B,userId:t,clicks:i})}),e.jsx(as,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(KVe,{icon:e.jsx(Yu,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ws,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(E_e,{vendors:A,isVisibleInPortals:z,onToggle:B,onEdit:$=>{d($),m(!0)},onDelete:D,userId:t,clicks:i})})]}),e.jsx(jxt,{open:h,onOpenChange:m,vendor:c,ownerType:"agent",agentUserId:t})]});return s?F:e.jsx(_s,{children:F})}function E_e({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(wxt,{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 KVe({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 CPs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:r,loading:n}=As(),{data:a=[],isLoading:i}=hBt(s),{data:l={}}=grt("brokerage",s),o=xrt(),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,g]=k.useState(""),[v,j]=k.useState("all");if(n)return e.jsx(_s,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!r)return e.jsx(_s,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const b=a.filter(S=>!(v!=="all"&&S.category!==v||x&&!`${S.name} ${S.company||""}`.toLowerCase().includes(x.toLowerCase()))),N=async S=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(S),ue.success("Vendor deleted")}catch(T){ue.error(T.message)}};return e.jsx(_s,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Sa,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ws,{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(fn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ke,{className:"pl-9",placeholder:"Search vendors...",value:x,onChange:S=>g(S.target.value)})]}),e.jsxs("select",{value:v,onChange:S=>j(S.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),XB.map(S=>e.jsx("option",{value:S.value,children:S.label},S.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):b.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Sa,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ws,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(S=>e.jsx(wxt,{vendor:S,onEdit:()=>{d(S),m(!0)},onDelete:()=>N(S.id),clickCount:l[S.id]},S.id))}),e.jsx(jxt,{open:h,onOpenChange:m,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const TPs=[{value:"overview",label:"Portals",icon:Sf},{value:"vendors",label:"Vendors",icon:Gj},{value:"referrals",label:"Referrals",icon:li},{value:"branding",label:"Branding",icon:pl},{value:"questions",label:"Onboarding",icon:t_}];function EPs(){const[s,t]=Lc(),r=s.get("tab")||"overview",[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return k.useEffect(()=>{t(d=>{const h=new URLSearchParams(d);return h.set("tab",n),h},{replace:!0})},[n,t]),e.jsxs(_s,{children:[e.jsx(il,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(jr,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx($O,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx(G,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Kn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(Rn,{value:n,onValueChange:a,className:"w-full",children:[e.jsx(Dn,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:TPs.map(d=>e.jsxs(Xt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(as,{value:"overview",className:"mt-6",children:e.jsx(yxt,{})}),e.jsx(as,{value:"vendors",className:"mt-6",children:e.jsx(APs,{})}),e.jsx(as,{value:"referrals",className:"mt-6",children:e.jsx(MPs,{})}),e.jsx(as,{value:"branding",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Portal Branding Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Set the default logo, colors, cover photo and welcome message that appear at the top of every client portal you create. You can still override per-portal in any deal's settings."}),e.jsxs(G,{onClick:()=>l(!0),children:[e.jsx(lo,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(as,{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(t_,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Custom Onboarding Questions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Questions you want every new client to answer when they first open their portal — preferred contact times, kids/pets, must-have features, and anything else that helps you serve them better."}),e.jsxs(G,{onClick:()=>c(!0),children:[e.jsx(lo,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(gxt,{open:i,onOpenChange:l}),e.jsx(xxt,{open:o,onOpenChange:c})]})}function APs(){return e.jsx(Nxt,{embedded:!0})}function MPs(){return e.jsx(_xt,{})}const XE=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function IPs(s){return gt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 H.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 H.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 PPs(){const{portalId:s}=Xi(),t=vr(),r=na(),{data:n,isLoading:a}=IPs(s),{data:i=[]}=CTs(s),{data:l=[]}=bxt(),o=rL(),c=Vmt(),d=Hmt(),h=Gmt(),[m,x]=k.useState(!1),[g,v]=k.useState(!1),[j,b]=k.useState(!1),[N,S]=k.useState(!1),T=(n==null?void 0:n.portal)??null,A=(n==null?void 0:n.deal)??null,P=k.useMemo(()=>T?l.filter(de=>de.portal_id===T.id):[],[l,T==null?void 0:T.id]);if(a)return e.jsx(_s,{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(!T)return e.jsx(_s,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(G,{asChild:!0,variant:"outline",children:e.jsxs(Kn,{to:"/mission-control/client-portals",children:[e.jsx(wa,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const D=s1(T.slug),B=(A==null?void 0:A.deal_name)||"Untitled deal",z=A==null?void 0:A.contact,F=z?`${z.first_name||""} ${z.last_name||""}`.trim():"",$=!!T.archived_at,X=()=>{navigator.clipboard.writeText(D),ue.success("Portal link copied!")},K=async de=>{try{await o.mutateAsync({id:T.id,is_enabled:de}),ue.success(de?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update")}},Q=async()=>{try{await c.mutateAsync(T.id),ue.success("Portal archived")}catch{ue.error("Failed to archive")}},Y=async()=>{try{await d.mutateAsync(T.id),ue.success("Portal restored")}catch{ue.error("Failed to restore")}},ne=async()=>{try{await h.mutateAsync({id:T.id,dealId:T.deal_id}),ue.success("Portal deleted"),t("/mission-control/client-portals")}catch{ue.error("Failed to delete")}};return e.jsxs(_s,{children:[e.jsx(il,{children:e.jsxs("title",{children:[B," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(G,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Kn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(wa,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(jr,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:B}),e.jsx(Ge,{variant:"outline",className:$?"bg-muted text-muted-foreground":T.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:$?"Archived":T.is_enabled?"Active":"Disabled"}),e.jsx(Ge,{variant:"outline",className:"capitalize text-xs",children:T.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Bi,{className:"w-3.5 h-3.5"}),T.client_name||F||"No client name set",(z==null?void 0:z.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Qs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:z.email})]}),(z==null?void 0:z.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Nn,{className:"w-3.5 h-3.5"}),z.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})})]}),!$&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(br,{checked:T.is_enabled,onCheckedChange:K})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(G,{onClick:X,variant:"outline",size:"sm",children:[e.jsx(Ra,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(G,{onClick:()=>window.open(D,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Yr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(G,{onClick:()=>b(!0),size:"sm",children:[e.jsx(Zr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(G,{onClick:()=>v(!0),variant:"outline",size:"sm",children:[e.jsx(Tv,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(G,{onClick:()=>x(!0),variant:"outline",size:"sm",children:[e.jsx(lo,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[$?e.jsxs(G,{onClick:Y,variant:"outline",size:"sm",children:[e.jsx(ZA,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(G,{onClick:Q,variant:"ghost",size:"sm",children:[e.jsx(Uj,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(G,{onClick:()=>S(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(sq,{icon:Tv,label:"Updates Posted",value:i.length}),e.jsx(sq,{icon:li,label:"Referrals",value:P.length}),e.jsx(sq,{icon:rn,label:"Inspection",value:T.inspection_date?XE(T.inspection_date):"—"}),e.jsx(sq,{icon:rn,label:"Appraisal",value:T.appraisal_date?XE(T.appraisal_date):"—"})]}),e.jsxs(Rn,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Xt,{value:"referrals",children:["Referrals (",P.length,")"]}),e.jsx(Xt,{value:"branding",children:"Branding"}),e.jsx(Xt,{value:"details",children:"Details"})]}),e.jsx(as,{value:"updates",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(G,{size:"sm",onClick:()=>v(!0),children:[e.jsx(Tv,{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(Tv,{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(de=>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:de.title}),de.is_stage_change&&e.jsx(Ge,{variant:"outline",className:"text-[10px] bg-emerald-500/10 text-emerald-700 border-emerald-200",children:"Stage Change"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:XE(de.created_at)}),de.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:de.content}),de.video_url&&e.jsxs("a",{href:de.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(sn,{className:"w-3 h-3"})," View video"]})]})})},de.id))})]})})}),e.jsx(as,{value:"referrals",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),P.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(li,{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:P.map(de=>e.jsx(Kn,{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:de.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[de.friend_email||de.friend_phone||"No contact info"," · ",XE(de.created_at)]})]}),e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:de.status})]})},de.id))})]})})}),e.jsx(as,{value:"branding",className:"mt-4",children:e.jsx(Ne,{children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold mb-1",children:"Portal Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-xl",children:"Override your default branding for this specific portal — custom logo, colors, cover photo, and welcome message just for this client."}),e.jsxs(G,{onClick:()=>x(!0),children:[e.jsx(lo,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(as,{value:"details",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsx(Fw,{label:"Visibility",value:T.visibility}),e.jsx(Fw,{label:"Onboarding Required",value:T.require_onboarding?"Yes":"No"}),e.jsx(Fw,{label:"Allow Spouse",value:T.allow_spouse?"Yes":"No"}),e.jsx(Fw,{label:"Notify Client on Updates",value:T.notify_client?"Yes":"No"}),e.jsx(Fw,{label:"Show Post-Close Tips",value:T.show_post_close_tips?"Yes":"No"}),e.jsx(Fw,{label:"Slug",value:T.slug,mono:!0}),e.jsx(Fw,{label:"Created",value:XE(T.created_at)}),e.jsx(Fw,{label:"Last Updated",value:XE(T.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(G,{variant:"outline",onClick:()=>x(!0),children:[e.jsx(lo,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(uMe,{open:m,onOpenChange:x,portal:T,dealOwnerId:r||""}),e.jsx(hMe,{open:g,onOpenChange:v,portalId:T.id,portalSlug:T.slug,notifyClient:T.notify_client}),e.jsx(mMe,{open:j,onOpenChange:b,portal:T,dealName:B}),e.jsx(Yo,{open:N,onOpenChange:S,children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Permanently delete this portal?"}),e.jsx(Uo,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:ne,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function sq({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 Fw({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 zSe=[{value:"video_intro",label:"Video Intro",icon:sn,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:yO,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Ah,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:rl,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Pc,description:"Links to your social profiles"}],LPs=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],DPs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function kxt({cardId:s}){const{data:t,isLoading:r}=CMt(s),n=TMt(),a=EMt(),i=AMt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(null);if(r)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Vs,{className:"h-16 w-full"}),e.jsx(Vs,{className:"h-16 w-full"})]});const x=()=>{c&&n.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:DPs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},g=S=>{a.mutate({id:S.id,is_visible:!S.is_visible})},v=(S,T)=>{if(!t)return;const A=t.findIndex(B=>B.id===S.id),P=T==="up"?A-1:A+1;if(P<0||P>=t.length)return;const D=t[P];a.mutate({id:S.id,sort_order:D.sort_order}),a.mutate({id:D.id,sort_order:S.sort_order})},j=S=>{confirm("Remove this block from this card?")&&i.mutate(S.id)},b=(S,T)=>{a.mutate({id:S.id,config:T},{onSuccess:()=>m(null)})},N=S=>zSe.find(T=>T.value===S);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(G,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((S,T)=>{const A=N(S.block_type),P=(A==null?void 0:A.icon)||Ah;return e.jsx(Ne,{className:S.is_visible?"":"opacity-50",children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(P,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(A==null?void 0:A.label)||S.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:RPs(S)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>v(S,"up"),disabled:T===0,children:e.jsx(Fd,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>v(S,"down"),disabled:T===t.length-1,children:e.jsx(Ku,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(S),children:S.is_visible?e.jsx(jn,{className:"h-3 w-3"}):e.jsx(am,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>m(S),children:"Edit"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>j(S),children:e.jsx(yr,{className:"h-3 w-3"})})]})]})})},S.id)}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:zSe.map(S=>{const T=S.icon;return e.jsxs("button",{onClick:()=>d(S.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===S.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(T,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:S.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.description})]})]},S.value)})}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{onClick:x,disabled:!c||n.isPending,children:"Add Block"})]})]})}),h&&e.jsx(OPs,{block:h,onSave:S=>b(h,S),onClose:()=>m(null)})]})}function RPs(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 OPs({block:s,onSave:t,onClose:r}){const[n,a]=k.useState(s.config),i=zSe.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(js,{children:e.jsxs(bs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(FPs,{config:n,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(BPs,{config:n,onChange:a}),s.block_type==="specialties"&&e.jsx(zPs,{config:n,onChange:a}),s.block_type==="custom_links"&&e.jsx($Ps,{config:n,onChange:a}),s.block_type==="social_media"&&e.jsx(UPs,{config:n,onChange:a}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(G,{onClick:()=>t(n),children:"Save"})]})]})})}function FPs({config:s,onChange:t,cardId:r}){var g,v;const[n,a]=k.useState(""),[i,l]=k.useState((g=s.video_url)!=null&&g.includes("youtube")||(v=s.video_url)!=null&&v.includes("youtu.be")?"youtube":"library"),{data:o}=gt({queryKey:["card-owner",r],queryFn:async()=>{const{data:j}=await H.from("agent_cards").select("user_id").eq("id",r).single();return j==null?void 0:j.user_id},enabled:!!r}),{data:c,isLoading:d}=gt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:j,error:b}=await H.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 j||[]},enabled:!!o}),h=(c==null?void 0:c.filter(j=>!n||(j.title||"").toLowerCase().includes(n.toLowerCase())))||[],m=s.bunny_video_id,x=j=>{var T;const b=(T=j.playback_url)==null?void 0:T.match(/\/(?:play|embed)\/(\d+)\//),S=`https://iframe.mediadelivery.net/embed/${b?b[1]:"570924"}/${j.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:S,bunny_video_id:j.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Rn,{value:i,onValueChange:l,children:[e.jsxs(Dn,{className:"w-full",children:[e.jsx(Xt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Xt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(as,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search videos...",value:n,onChange:j=>a(j.target.value),className:"pl-9"})]}),e.jsx(ti,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Vs,{className:"h-14 w-full"}),e.jsx(Vs,{className:"h-14 w-full"})]}):h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:h.map(j=>e.jsxs("button",{onClick:()=>x(j),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${m===j.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[j.thumbnail_url?e.jsx("img",{src:j.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:b=>{var N;b.currentTarget.style.display="none",(N=b.currentTarget.nextElementSibling)==null||N.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${j.thumbnail_url?"hidden":""}`,children:e.jsx(sn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:j.title||"Untitled Video"}),m===j.bunny_video_id&&e.jsx(Hn,{className:"h-4 w-4 text-primary flex-shrink-0"})]},j.id))})})]}),e.jsx(as,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(he,{children:"YouTube URL"}),e.jsx(ke,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:j=>t({...s,video_url:j.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 BPs({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(Ne,{children:e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),r.length>1&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(yr,{className:"h-3 w-3"})})]}),e.jsx(ke,{placeholder:"Client name",value:l.name,onChange:c=>n(o,"name",c.target.value)}),e.jsx(ke,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>n(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>n(o,"quote",c.target.value)})]})},o)),e.jsxs(G,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function zPs({config:s,onChange:t}){const r=s.tags||[],[n,a]=k.useState(""),i=o=>{t({...s,tags:r.includes(o)?r.filter(c=>c!==o):[...r,o]})},l=()=>{n.trim()&&!r.includes(n.trim())&&(t({...s,tags:[...r,n.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:LPs.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${r.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Add your own...",value:n,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(G,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function $Ps({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(ke,{placeholder:"Button label",value:l.label,onChange:c=>n(o,"label",c.target.value)}),e.jsx(ke,{placeholder:"https://...",value:l.url,onChange:c=>n(o,"url",c.target.value)})]}),r.length>1&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(yr,{className:"h-3 w-3"})})]},o)),e.jsxs(G,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const YVe=[{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 UPs({config:s,onChange:t}){const r=s.platforms||[],n=c=>{r.find(d=>d.platform===c)||t({...s,platforms:[...r,{platform:c,url:""}]})},a=(c,d)=>{const h=[...r];h[c]={...h[c],url:d},t({...s,platforms:h})},i=c=>{t({...s,platforms:r.filter((d,h)=>h!==c)})},l=YVe.filter(c=>!r.find(d=>d.platform===c.value)),o=c=>{const d=n2e[c],h=YVe.find(m=>m.value===c);return{label:(h==null?void 0:h.label)||c,color:(d==null?void 0:d.color)||"#666",iconPath:d==null?void 0:d.icon}};return e.jsxs("div",{className:"space-y-4",children:[r.length>0&&e.jsx("div",{className:"space-y-3",children:r.map((c,d)=>{const h=o(c.platform);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 border",style:{borderColor:h.color+"30",backgroundColor:h.color+"10"},children:h.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:h.color,children:e.jsx("path",{d:h.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(ke,{placeholder:`Your ${h.label} profile URL`,value:c.url,onChange:m=>a(d,m.target.value)})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground mb-2 block",children:"Add a platform"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(c=>{const d=n2e[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 qPs=Object.defineProperty,ufe=Object.getOwnPropertySymbols,Sxt=Object.prototype.hasOwnProperty,Cxt=Object.prototype.propertyIsEnumerable,ZVe=(s,t,r)=>t in s?qPs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,$Se=(s,t)=>{for(var r in t||(t={}))Sxt.call(t,r)&&ZVe(s,r,t[r]);if(ufe)for(var r of ufe(t))Cxt.call(t,r)&&ZVe(s,r,t[r]);return s},USe=(s,t)=>{var r={};for(var n in s)Sxt.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&ufe)for(var n of ufe(s))t.indexOf(n)<0&&Cxt.call(s,n)&&(r[n]=s[n]);return r};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var z5;(s=>{const t=class mo{constructor(c,d,h,m){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cmo.MAX_VERSION)throw new RangeError("Version value out of range");if(m<-1||m>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let x=[];for(let v=0;v7)throw new RangeError("Invalid value");let v,j;for(v=h;;v++){const T=mo.getNumDataCodewords(v,d)*8,A=l.getTotalBits(c,v);if(A<=T){j=A;break}if(v>=m)throw new RangeError("Data too long")}for(const T of[mo.Ecc.MEDIUM,mo.Ecc.QUARTILE,mo.Ecc.HIGH])g&&j<=mo.getNumDataCodewords(v,T)*8&&(d=T);let b=[];for(const T of c){r(T.mode.modeBits,4,b),r(T.numChars,T.mode.numCharCountBits(v),b);for(const A of T.getData())b.push(A)}a(b.length==j);const N=mo.getNumDataCodewords(v,d)*8;a(b.length<=N),r(0,Math.min(4,N-b.length),b),r(0,(8-b.length%8)%8,b),a(b.length%8==0);for(let T=236;b.lengthS[A>>>3]|=T<<7-(A&7)),new mo(v,d,S,x)}getModule(c,d){return 0<=c&&c>>9)*1335;const m=(d<<10|h)^21522;a(m>>>15==0);for(let x=0;x<=5;x++)this.setFunctionModule(8,x,n(m,x));this.setFunctionModule(8,7,n(m,6)),this.setFunctionModule(8,8,n(m,7)),this.setFunctionModule(7,8,n(m,8));for(let x=9;x<15;x++)this.setFunctionModule(14-x,8,n(m,x));for(let x=0;x<8;x++)this.setFunctionModule(this.size-1-x,8,n(m,x));for(let x=8;x<15;x++)this.setFunctionModule(8,this.size-15+x,n(m,x));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let h=0;h<12;h++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let h=0;h<18;h++){const m=n(d,h),x=this.size-11+h%3,g=Math.floor(h/3);this.setFunctionModule(x,g,m),this.setFunctionModule(g,x,m)}}drawFinderPattern(c,d){for(let h=-4;h<=4;h++)for(let m=-4;m<=4;m++){const x=Math.max(Math.abs(m),Math.abs(h)),g=c+m,v=d+h;0<=g&&g{(T!=j-x||P>=v)&&S.push(A[T])});return a(S.length==g),S}drawCodewords(c){if(c.length!=Math.floor(mo.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let h=this.size-1;h>=1;h-=2){h==6&&(h=5);for(let m=0;m>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(v,j),g||(c+=this.finderPenaltyCountPatterns(j)*mo.PENALTY_N3),g=this.modules[x][b],v=1);c+=this.finderPenaltyTerminateAndCount(g,v,j)*mo.PENALTY_N3}for(let x=0;x5&&c++):(this.finderPenaltyAddHistory(v,j),g||(c+=this.finderPenaltyCountPatterns(j)*mo.PENALTY_N3),g=this.modules[b][x],v=1);c+=this.finderPenaltyTerminateAndCount(g,v,j)*mo.PENALTY_N3}for(let x=0;xg+(v?1:0),d);const h=this.size*this.size,m=Math.ceil(Math.abs(d*20-h*10)/h)-1;return a(0<=m&&m<=9),c+=m*mo.PENALTY_N4,a(0<=c&&c<=2568888),c}getAlignmentPatternPositions(){if(this.version==1)return[];{const c=Math.floor(this.version/7)+2,d=this.version==32?26:Math.ceil((this.version*4+4)/(c*2-2))*2;let h=[6];for(let m=this.size-7;h.lengthmo.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const h=Math.floor(c/7)+2;d-=(25*h-10)*h-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(mo.getNumRawDataModules(c)/8)-mo.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*mo.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let m=0;m0);for(const m of c){const x=m^h.shift();h.push(0),d.forEach((g,v)=>h[v]^=mo.reedSolomonMultiply(g,x))}return h}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let h=0;for(let m=7;m>=0;m--)h=h<<1^(h>>>7)*285,h^=(d>>>m&1)*c;return a(h>>>8==0),h}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const h=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(h&&c[0]>=d*4&&c[6]>=d?1:0)+(h&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,h){return c&&(this.finderPenaltyAddHistory(d,h),d=0),d+=this.size,this.finderPenaltyAddHistory(d,h),this.finderPenaltyCountPatterns(h)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function r(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let h=c-1;h>=0;h--)d.push(o>>>h&1)}function n(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class Nd{constructor(c,d,h){if(this.mode=c,this.numChars=d,this.bitData=h,d<0)throw new RangeError("Invalid argument");this.bitData=h.slice()}static makeBytes(c){let d=[];for(const h of c)r(h,8,d);return new Nd(Nd.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Nd.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let h=0;h=1<{(t=>{const r=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(s.QrCode||(s.QrCode={}))})(z5||(z5={}));(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={}))})(z5||(z5={}));var $A=z5;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var VPs={L:$A.QrCode.Ecc.LOW,M:$A.QrCode.Ecc.MEDIUM,Q:$A.QrCode.Ecc.QUARTILE,H:$A.QrCode.Ecc.HIGH},Txt=128,Ext="L",Axt="#FFFFFF",Mxt="#000000",Ixt=!1,Pxt=1,HPs=4,GPs=0,WPs=.1;function Lxt(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 Dxt(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 KPs(s,t,r,n){if(n==null)return null;const a=s.length+r*2,i=Math.floor(t*WPs),l=a/t,o=(n.width||i)*l,c=(n.height||i)*l,d=n.x==null?s.length/2-o/2:n.x*l,h=n.y==null?s.length/2-c/2:n.y*l,m=n.opacity==null?1:n.opacity;let x=null;if(n.excavate){let v=Math.floor(d),j=Math.floor(h),b=Math.ceil(o+d-v),N=Math.ceil(c+h-j);x={x:v,y:j,w:b,h:N}}const g=n.crossOrigin;return{x:d,y:h,h:c,w:o,excavation:x,opacity:m,crossOrigin:g}}function YPs(s,t){return t!=null?Math.max(Math.floor(t),0):s?HPs:GPs}function Rxt({value:s,level:t,minVersion:r,includeMargin:n,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=wt.useMemo(()=>{const v=(Array.isArray(s)?s:[s]).reduce((j,b)=>(j.push(...$A.QrSegment.makeSegments(b)),j),[]);return $A.QrCode.encodeSegments(v,VPs[t],r,void 0,void 0,o)},[s,t,r,o]);const{cells:d,margin:h,numCells:m,calculatedImageSettings:x}=wt.useMemo(()=>{let g=c.getModules();const v=YPs(n,a),j=g.length+v*2,b=KPs(g,l,v,i);return{cells:g,margin:v,numCells:j,calculatedImageSettings:b}},[c,l,i,n,a]);return{qrcode:c,margin:h,cells:d,numCells:m,calculatedImageSettings:x}}var ZPs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),XPs=wt.forwardRef(function(t,r){const n=t,{value:a,size:i=Txt,level:l=Ext,bgColor:o=Axt,fgColor:c=Mxt,includeMargin:d=Ixt,minVersion:h=Pxt,boostLevel:m,marginSize:x,imageSettings:g}=n,j=USe(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:b}=j,N=USe(j,["style"]),S=g==null?void 0:g.src,T=wt.useRef(null),A=wt.useRef(null),P=wt.useCallback(Y=>{T.current=Y,typeof r=="function"?r(Y):r&&(r.current=Y)},[r]),[D,B]=wt.useState(!1),{margin:z,cells:F,numCells:$,calculatedImageSettings:X}=Rxt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:x,imageSettings:g,size:i});wt.useEffect(()=>{if(T.current!=null){const Y=T.current,ne=Y.getContext("2d");if(!ne)return;let de=F;const ce=A.current,ae=X!=null&&ce!==null&&ce.complete&&ce.naturalHeight!==0&&ce.naturalWidth!==0;ae&&X.excavation!=null&&(de=Dxt(F,X.excavation));const ie=window.devicePixelRatio||1;Y.height=Y.width=i*ie;const me=i/$*ie;ne.scale(me,me),ne.fillStyle=o,ne.fillRect(0,0,$,$),ne.fillStyle=c,ZPs?ne.fill(new Path2D(Lxt(de,z))):F.forEach(function(oe,ge){oe.forEach(function(be,Oe){be&&ne.fillRect(Oe+z,ge+z,1,1)})}),X&&(ne.globalAlpha=X.opacity),ae&&ne.drawImage(ce,X.x+z,X.y+z,X.w,X.h)}}),wt.useEffect(()=>{B(!1)},[S]);const K=$Se({height:i,width:i},b);let Q=null;return S!=null&&(Q=wt.createElement("img",{src:S,key:S,style:{display:"none"},onLoad:()=>{B(!0)},ref:A,crossOrigin:X==null?void 0:X.crossOrigin})),wt.createElement(wt.Fragment,null,wt.createElement("canvas",$Se({style:K,height:i,width:i,ref:P,role:"img"},N)),Q)});XPs.displayName="QRCodeCanvas";var Bz=wt.forwardRef(function(t,r){const n=t,{value:a,size:i=Txt,level:l=Ext,bgColor:o=Axt,fgColor:c=Mxt,includeMargin:d=Ixt,minVersion:h=Pxt,boostLevel:m,title:x,marginSize:g,imageSettings:v}=n,j=USe(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:b,cells:N,numCells:S,calculatedImageSettings:T}=Rxt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:g,imageSettings:v,size:i});let A=N,P=null;v!=null&&T!=null&&(T.excavation!=null&&(A=Dxt(N,T.excavation)),P=wt.createElement("image",{href:v.src,height:T.h,width:T.w,x:T.x+b,y:T.y+b,preserveAspectRatio:"none",opacity:T.opacity,crossOrigin:T.crossOrigin}));const D=Lxt(A,b);return wt.createElement("svg",$Se({height:i,width:i,viewBox:`0 0 ${S} ${S}`,ref:r,role:"img"},j),!!x&&wt.createElement("title",null,x),wt.createElement("path",{fill:o,d:`M0,0 h${S}v${S}H0z`,shapeRendering:"crispEdges"}),wt.createElement("path",{fill:c,d:D,shapeRendering:"crispEdges"}),P)});Bz.displayName="QRCodeSVG";function QPs({slug:s,agentName:t}){const r=k.useRef(null),n=`https://cards.relevelup.com/${s}`,a=k.useCallback(()=>{var m;const i=(m=r.current)==null?void 0:m.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),h=new Image;h.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(h,0,0,o,o);const x=document.createElement("a");x.download=`${s}-qr-code.png`,x.href=l.toDataURL("image/png"),x.click(),ue.success("QR code downloaded!")},h.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:r,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(Bz,{value:n,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs(G,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(Xa,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function A_e(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 JPs(){const{user:s}=As(),{data:t,isLoading:r}=NMt(s==null?void 0:s.id),n=tL(),[a,i]=k.useState(null),l=k.useMemo(()=>a||(t?A_e(t):null),[a,t]);if(r)return e.jsx(_s,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Vs,{className:"h-8 w-48"}),e.jsx(Vs,{className:"h-32 w-full"}),e.jsx(Vs,{className:"h-32 w-full"})]})});if(!t)return e.jsx(_s,{children:e.jsx(tLs,{userId:s==null?void 0:s.id})});const o=l||A_e(t),c=d=>{i(h=>{const m=h||A_e(t);return typeof d=="function"?d(m):d})};return e.jsx(_s,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${n?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(sLs,{card:t}),e.jsx(iLs,{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(Zj,{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(eLs,{card:t,form:o})})]})})]})})}function eLs({card:s,form:t}){const{data:r}=gt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await H.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 H.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=H.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(h3e,{card:n})})}function tLs({userId:s}){var c;const[t,r]=k.useState(""),n=ket(),{data:a}=gt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await H.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ue.error("Please enter a URL slug for your card");return}n.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ue.success("Your digital card has been created!")})},o=[{icon:gc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:Xu,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Zu,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:pl,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(Ne,{className:"shadow-lg border-2",children:[e.jsxs(Ot,{className:"text-center pb-2",children:[e.jsx(zt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Nr,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(De,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ke,{value:t||i,onChange:d=>r(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(G,{onClick:l,disabled:n.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),n.isPending?"Creating...":"Create My Card"]})]})]})]})}function sLs({card:s}){const r=`https://cards.relevelup.com/${s.slug}`,n=()=>{navigator.clipboard.writeText(r),ue.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(Ge,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(gc,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[e.jsx(Ra,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(G,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function rLs({userId:s}){const t=es(),r=k.useRef(null),[n,a]=k.useState(!1),[i,l]=k.useState(""),{data:o,isLoading:c}=gt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:X}=await H.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let K=(X==null?void 0:X.avatar_url)||null;if(!K){const{data:Q}=await H.storage.from("avatars").list(`${s}`);if(Q&&Q.length>0){const{data:Y}=H.storage.from("avatars").getPublicUrl(`${s}/${Q[0].name}`);K=`${Y.publicUrl}?t=${Date.now()}`,await H.from("profiles").update({avatar_url:K}).eq("id",s)}}return{...X,avatar_url:K}}}),[d,h]=k.useState(null),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(!1),N=d??(o==null?void 0:o.name)??"",S=m??(o==null?void 0:o.phone)??"",T=g??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,P=((o==null?void 0:o.name)||"A").split(" ").map(X=>X[0]).join("").toUpperCase().slice(0,2),D=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),B=Lt({mutationFn:async X=>{const{error:K}=await H.from("profiles").update(X).eq("id",s);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ue.success("Profile updated!")},onError:()=>ue.error("Failed to update profile")}),z=()=>{const X={};if(d!==null&&d!==(o==null?void 0:o.name)&&(X.name=d),m!==null&&m!==(o==null?void 0:o.phone)&&(X.phone=m||null),g!==null&&g!==(o==null?void 0:o.email)&&(X.email=g),Object.keys(X).length===0){ue.info("No changes to save");return}B.mutate(X)},F=X=>{var Y;const K=(Y=X.target.files)==null?void 0:Y[0];if(!K)return;if(!K.type.startsWith("image/")){ue.error("Please select an image file");return}const Q=new FileReader;Q.onloadend=()=>{l(Q.result),a(!0)},Q.readAsDataURL(K),X.target.value=""},$=async X=>{b(!0);try{const{data:K}=await H.storage.from("avatars").list(`${s}`);K&&K.length>0&&await H.storage.from("avatars").remove(K.map(ce=>`${s}/${ce.name}`));const Q=`${s}/avatar.jpg`,{error:Y}=await H.storage.from("avatars").upload(Q,X,{upsert:!0,contentType:"image/jpeg"});if(Y)throw Y;const{data:ne}=H.storage.from("avatars").getPublicUrl(Q),de=ne.publicUrl+"?t="+Date.now();await H.from("profiles").update({avatar_url:de}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ue.success("Photo updated!")}catch{ue.error("Failed to upload photo")}finally{b(!1)}};return c?e.jsx(Vs,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:D?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(De,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(he,{className:"text-sm font-semibold",children:"Profile Info"}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Hi,{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 X;return(X=r.current)==null?void 0:X.click()},children:[e.jsxs(vn,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ga,{src:A||void 0,alt:N}),e.jsx(bn,{className:"text-lg font-semibold bg-primary/10 text-primary",children:P})]}),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(pp,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:F})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:j?"Uploading...":A?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(ke,{value:N,onChange:X=>h(X.target.value),placeholder:"Your full name",className:"h-10"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(ke,{value:S,onChange:X=>x(X.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(ke,{value:T,onChange:X=>v(X.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:z,disabled:B.isPending,className:"w-full",children:B.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(TTe,{open:n,onClose:()=>a(!1),imageSrc:i,onCropComplete:$,aspectRatio:1})]})}function nLs({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=g=>{l(g),t(g==="name"?v=>({...v,brokerage_logo_url:""}):v=>({...v,brokerage_display_name:""}))},h=g=>{c(g),t(g==="name"?v=>({...v,team_logo_url:""}):v=>({...v,team_name:""}))},m=async(g,v)=>{var b;const j=(b=g.target.files)==null?void 0:b[0];if(j){if(!j.type.startsWith("image/")){ue.error("Please select an image file");return}a(v);try{const N=j.name.split(".").pop()||"png",T=`${r}/${v==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${N}`,{error:A}=await H.storage.from("card-logos").upload(T,j,{upsert:!0});if(A)throw A;const{data:P}=H.storage.from("card-logos").getPublicUrl(T),D=P.publicUrl+"?t="+Date.now();t(v==="brokerage_logo_url"?B=>({...B,[v]:D,brokerage_display_name:""}):B=>({...B,[v]:D,team_name:""})),ue.success("Logo uploaded!")}catch{ue.error("Failed to upload logo")}finally{a(null),g.target.value=""}}},x=g=>{t(v=>({...v,[g]:""}))};return e.jsx(Ne,{children:e.jsxs(De,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-semibold",children:"Brokerage & Team Branding"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Choose either a name or a logo for each — not both."})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(G,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(ke,{value:s.brokerage_display_name,onChange:g=>t(v=>({...v,brokerage_display_name:g.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>x("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(pp,{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:g=>m(g,"brokerage_logo_url"),disabled:n!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.brokerage_logo_size||56,"px"]})]}),e.jsx(Xy,{value:[s.brokerage_logo_size||56],onValueChange:([g])=>t(v=>({...v,brokerage_logo_size:g})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("name"),children:"Use Name"}),e.jsx(G,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(ke,{value:s.team_name,onChange:g=>t(v=>({...v,team_name:g.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>x("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(pp,{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:g=>m(g,"team_logo_url"),disabled:n!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.team_logo_size||56,"px"]})]}),e.jsx(Xy,{value:[s.team_logo_size||56],onValueChange:([g])=>t(v=>({...v,team_logo_size:g})),min:24,max:120,step:4})]})]})]})]})})}function aLs({form:s,setForm:t}){const r={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},n=s.bold_theme_colors||r,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...r,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(he,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(pl,{className:"h-4 w-4"})," Brand Colors"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize colors to match your brand"})]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:n[o],onChange:h=>a(o,h.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:n[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(ke,{value:n[o],onChange:h=>{const m=h.target.value;/^#[0-9a-fA-F]{0,6}$/.test(m)&&a(o,m)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.button}})]})]})]})}function iLs({card:s,form:t,setForm:r}){var j;const n=Cet(),a=es(),{data:i}=Tet(s.id),[l,o]=k.useState(s.slug),[c,d]=k.useState(!1),[h,m]=k.useState("idle"),x=k.useRef(JSON.stringify(t)),g=k.useRef(null);k.useEffect(()=>{const b=JSON.stringify(t);if(b!==x.current)return g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{m("saving"),n.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{x.current=b,m("saved"),setTimeout(()=>m("idle"),2e3)},onError:()=>m("idle")})},1500),()=>{g.current&&clearTimeout(g.current)}},[t]);const v=async()=>{const b=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!b){ue.error("Please enter a valid URL");return}if(b===s.slug){ue.info("No changes to save");return}d(!0);try{const{data:N}=await H.from("agent_cards").select("id").eq("slug",b).neq("id",s.id).maybeSingle();if(N){ue.error("This URL is already taken. Try another one.");return}const{error:S}=await H.from("agent_cards").update({slug:b}).eq("id",s.id);if(S)throw S;o(b),a.invalidateQueries({queryKey:["agent-card"]}),ue.success("Card address updated!")}catch{ue.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Rn,{defaultValue:"content",children:[e.jsxs(Dn,{className:"w-full h-11 p-1",children:[e.jsxs(Xt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(gx,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Xt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(jn,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Xt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Xu,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Xt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Hv,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Xt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Dd,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(as,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(rLs,{userId:s.user_id}),e.jsx(nLs,{form:t,setForm:r,userId:s.user_id}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-semibold",children:"Card Status"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Toggle your card on or off"})]}),e.jsx(br,{checked:t.is_published,onCheckedChange:b=>r(N=>({...N,is_published:b}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ke,{value:l,onChange:b=>o(b.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:v,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(ke,{value:t.display_email,onChange:b=>r(N=>({...N,display_email:b.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(zs,{value:t.theme,onValueChange:b=>r(N=>({...N,theme:b})),children:[e.jsx(Os,{className:"h-11",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(mt,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(mt,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(mt,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(aLs,{form:t,setForm:r}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(ke,{value:t.title,onChange:b=>r(N=>({...N,title:b.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(ke,{value:t.positioning_statement,onChange:b=>r(N=>({...N,positioning_statement:b.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Bio"}),e.jsx(ur,{value:t.bio,onChange:b=>r(N=>({...N,bio:b.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(ke,{value:t.review_snippet,onChange:b=>r(N=>({...N,review_snippet:b.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(ke,{value:t.review_source_url,onChange:b=>r(N=>({...N,review_source_url:b.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(ke,{value:t.booking_url,onChange:b=>r(N=>({...N,booking_url:b.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(ke,{value:t.custom_cta_label,onChange:b=>r(N=>({...N,custom_cta_label:b.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(as,{value:"sections",className:"mt-4",children:e.jsx(Ne,{children:e.jsx(De,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:b,label:N,desc:S})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(he,{className:"text-sm font-medium",children:N}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S})]}),e.jsx(br,{checked:t[b],onCheckedChange:T=>r(A=>({...A,[b]:T}))})]},b))})})}),e.jsx(as,{value:"blocks",className:"mt-4",children:e.jsx(kxt,{cardId:s.id})}),e.jsx(as,{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:jn,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:Dd,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((j=i==null?void 0:i.leads)==null?void 0:j.length)??0,icon:nl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(b=>e.jsx(Ne,{className:"overflow-hidden",children:e.jsxs(De,{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(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-base",children:"Recent Leads"})}),e.jsx(De,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(b=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:b.name}),b.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:b.phone})]}),b.intent&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:b.intent})]},b.id))})]}),(!i||i.leads.length===0)&&e.jsx(Ne,{children:e.jsxs(De,{className:"p-8 text-center",children:[e.jsx(Dd,{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(as,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(Ne,{children:e.jsx(De,{className:"p-6",children:e.jsx(QPs,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[h==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),h==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),h==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function oLs(){const s=es(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState(null),[j,b]=k.useState(null),[N,S]=k.useState(0),[T,A]=k.useState(""),[P,D]=k.useState(!1),{data:B,isLoading:z}=gt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ie,error:me}=await H.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(me)throw me;return ie}}),F=Lt({mutationFn:async ie=>{const{data:me,error:oe}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ie}});if(oe)throw oe;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),r(""),ue.success("BoldTrail connected successfully!")},onError:ie=>{ue.error(ie.message||"Failed to connect BoldTrail")}}),$=Lt({mutationFn:async()=>{const{data:ie,error:me}=await H.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(me)throw me;return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("BoldTrail disconnected")},onError:()=>ue.error("Failed to disconnect")}),X=Lt({mutationFn:async ie=>{const{data:me,error:oe}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ie}});if(oe)throw oe;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("Sync direction saved")},onError:ie=>{ue.error(ie.message||"Failed to save sync direction")}}),K=Lt({mutationFn:async()=>{const{data:ie,error:me}=await H.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(me)throw me;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.kvcore_user_id){const me=ie.detected_name||ie.detected_email||`ID ${ie.kvcore_user_id}`;ue.success(`Detected your BoldTrail account: ${me}`)}else if(ie.candidates&&ie.candidates.length>0){const me=ie.candidates.slice(0,5).map(oe=>`${oe.id} (${oe.count} contacts)`).join(", ");ue.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${me}. Pick yours and enter it below.`,{duration:12e3}),D(!0)}else ue.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),D(!0)},onError:ie=>ue.error(ie.message||"Detection failed")}),Q=Lt({mutationFn:async ie=>{const{data:me,error:oe}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ie}});if(oe)throw oe;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("Settings saved"),D(!1)},onError:ie=>ue.error(ie.message||"Failed to save settings")}),Y=Lt({mutationFn:async()=>{const{data:ie,error:me}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(me)throw me;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{v(null),c(ie),a(!0)},onError:ie=>{ue.error(ie.message||"Failed to generate sync preview")}}),ne=Lt({mutationFn:async()=>{b("Initializing sync..."),S(5);const{data:ie,error:me}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ae}});if(me)throw me;if(ie!=null&&ie.error)throw new Error(ie.error);const oe=ie;let ge=oe.sync_log_id,be=oe.next_phase,Oe=oe.next_offset,Me=oe.push_total||0,Pe=oe.pull_total||0,Ee=0,$e=0;for(;be!=="finalize";){const Te=Me+Pe;be==="fetch_bt"?b("Fetching BoldTrail contacts..."):be==="analyze"?(b("Analyzing contacts..."),S(15)):be==="push"?(b(`Pushing contacts to BoldTrail... (${Ee}/${Me})`),S(Te>0?Ee/Te*100:0)):be==="pull"&&(b(`Pulling contacts from BoldTrail... (${$e}/${Pe})`),S(Te>0?(Me+$e)/Te*100:0));const{data:ye,error:ct}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:be,offset:Oe,sync_log_id:ge,sync_direction:ae}});if(ct)throw ct;if(ye!=null&&ye.error)throw new Error(ye.error);const ve=ye;Ee+=ve.chunk_pushed||0,$e+=ve.chunk_pulled||0,ve.push_total!==void 0&&(Me=ve.push_total||0),ve.pull_total!==void 0&&(Pe=ve.pull_total||0),ve.progress&&b(ve.progress),be==="pull"&&Pe>0?S(Math.min(95,$e/Pe*100)):be==="push"&&Me>0&&S(Math.min(95,Ee/Me*100)),be=ve.next_phase,Oe=ve.next_offset}b("Finalizing sync..."),S(95);const{data:Se,error:ze}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ge,sync_direction:ae}});if(ze)throw ze;return S(100),Se},onSuccess:ie=>{b(null),S(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ue.success(`Sync complete! Pushed ${ie.contacts_pushed||0}, pulled ${ie.contacts_pulled||0}, skipped ${ie.contacts_skipped||0} duplicates.`)},onError:ie=>{b(null),S(0),ue.error(ie.message||"Sync failed")}}),de=B==null?void 0:B.connected,ce=(B==null?void 0:B.sync_direction)||"bidirectional",ae=g??ce;return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{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(Rd,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",de&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"}),e.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(mf,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Nr,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(De,{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(mi,{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(mi,{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(mi,{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"})]}),de?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"}),(B==null?void 0:B.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(B.last_sync_at).toLocaleString(),B.last_sync_status&&e.jsx(Ge,{variant:B.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:B.last_sync_status})]}),(B==null?void 0:B.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[B.boldtrail_contact_count," contacts in BoldTrail"]}),(B==null?void 0:B.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:B.last_sync_message})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect BoldTrail?"}),e.jsx(Uo,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>$.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(Yv,{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(br,{checked:!!(B!=null&&B.sync_only_owned),onCheckedChange:ie=>Q.mutate({sync_only_owned:ie}),disabled:Q.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Your BoldTrail Agent ID"}),P?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",placeholder:"e.g. 12345",value:T,onChange:ie=>A(ie.target.value),className:"h-8 text-sm"}),e.jsx(G,{size:"sm",onClick:()=>{const ie=T.trim()===""?null:Number(T);Q.mutate({kvcore_user_id:ie})},disabled:Q.isPending,children:"Save"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>D(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(B==null?void 0:B.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>K.mutate(),disabled:K.isPending,children:[K.isPending?e.jsx(Di,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{var ie;A(((ie=B==null?void 0:B.kvcore_user_id)==null?void 0:ie.toString())??""),D(!0)},children:"Edit"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your numeric BoldTrail (kvCORE) user ID. To find it: log into BoldTrail → click your avatar (top right) → ",e.jsx("strong",{children:"My Profile"}),". The ID appears in the page URL after ",e.jsx("code",{children:"/users/"})," (e.g. ",e.jsxs("code",{children:[".../users/",e.jsx("strong",{children:"12345"})]}),"). You can also open any contact you own in BoldTrail and look at the URL — your ID is shown as the assigned agent. Auto-detect tries to find it via your API token first."]})]})]}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsx(ySe,{value:ce,onChange:ie=>X.mutate(ie)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(G,{onClick:()=>Y.mutate(),disabled:Y.isPending||ne.isPending,variant:"outline",className:"gap-2",children:[Y.isPending?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(jn,{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(ke,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ie=>r(ie.target.value),className:"flex-1"}),e.jsxs(G,{onClick:()=>F.mutate(t),disabled:!t||t.length<10||F.isPending,children:[F.isPending?e.jsx(Di,{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:ie=>{ne.isPending||a(ie)},children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Rd,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Fr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ie=ae==="pull_only"?0:o.to_push,me=ae==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ySe,{value:ae,onChange:v,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(Yv,{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 ${ae==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ie}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ae==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:me}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ku,{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(fr,{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"]}),ne.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ri,{value:N||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:j||"Sync in progress..."})]}),ie>0&&e.jsxs(bx,{open:d,onOpenChange:h,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3 text-emerald-600"}),ie," contacts to push to BoldTrail"]}),e.jsx(so,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(wx,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((oe,ge)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:oe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:oe.email})]},ge)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),me>0&&e.jsxs(bx,{open:m,onOpenChange:x,children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ku,{className:"h-3 w-3 text-blue-600"}),me," contacts to pull from BoldTrail"]}),e.jsx(so,{className:`h-3 w-3 transition-transform ${m?"rotate-180":""}`})]})}),e.jsx(wx,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((oe,ge)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:oe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:oe.email})]},ge)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),ie===0&&me===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),disabled:ne.isPending,children:"Cancel"}),e.jsxs(G,{onClick:()=>ne.mutate(),disabled:ne.isPending||ie===0&&me===0,className:"gap-2",children:[ne.isPending?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Rd,{className:"h-4 w-4"}),ne.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(js,{className:"p-6 pb-0",children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Rd,{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 lLs(){const s=es(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:h}=gt({queryKey:["fub-status"],queryFn:async()=>{const{data:j,error:b}=await H.functions.invoke("followupboss-sync",{body:{action:"status"}});if(b)throw b;return j}}),m=Lt({mutationFn:async j=>{const{data:b,error:N}=await H.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:j}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{ue.success("Connected to Follow Up Boss"),r(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:j=>ue.error(j.message)}),x=Lt({mutationFn:async()=>{const{error:j}=await H.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(j)throw j},onSuccess:()=>{ue.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),g=Lt({mutationFn:async j=>{const{error:b}=await H.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:j}});if(b)throw b},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),v=async()=>{a(!0),l(0),c("Pulling from FUB…");let j=0,b=0,N=0,S=0;try{for(;;){const{data:D,error:B}=await H.functions.invoke("followupboss-sync",{body:{action:"sync",offset:j}});if(B)throw B;if(D!=null&&D.error)throw new Error(D.error);b+=D.chunk_created||0,N+=D.chunk_updated||0,S+=D.chunk_skipped||0,j=D.next_offset;const z=D.total?Math.min(100,Math.round(j/D.total*100)):100;if(l(z),c(`Pulling · ${j} / ${D.total||"?"}`),D.done)break;await new Promise(F=>setTimeout(F,400))}let T=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to FUB…");;){const{data:B,error:z}=await H.functions.invoke("followupboss-sync",{body:{action:"push",offset:D}});if(z)throw z;if(B!=null&&B.error)throw new Error(B.error);T+=B.chunk_pushed||0,A+=B.chunk_failed||0,D=B.next_offset;const F=B.total?Math.min(100,Math.round(D/B.total*100)):100;if(l(F),c(`Pushing · ${D} / ${B.total||"?"}`),B.done)break;await new Promise($=>setTimeout($,400))}}const P=T||A?` · pushed ${T}${A?`, ${A} failed`:""}`:"";ue.success(`Sync complete · ${b} new, ${N} updated${S?`, ${S} skipped`:""}${P}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(T){ue.error(T.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(B3,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Ge,{variant:"default",className:"ml-1",children:[e.jsx(mi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Nr,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(De,{className:"space-y-4",children:h?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"FUB contacts"}),e.jsx("p",{className:"font-medium",children:d.fub_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from FUB only. On = also push new Agent OS contacts to FUB."})]}),e.jsx(br,{checked:d.sync_direction==="bidirectional",onCheckedChange:j=>g.mutate(j?"bidirectional":"pull_only"),disabled:n||g.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ri,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{onClick:v,disabled:n,children:[e.jsx(Di,{className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),n?"Syncing…":"Sync Now"]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsxs(G,{variant:"outline",disabled:n,children:[e.jsx(yr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Follow Up Boss?"}),e.jsx(Uo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>x.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(ke,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:j=>r(j.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(Yr,{className:"h-3 w-3"})]})]})]}),e.jsx(G,{onClick:()=>m.mutate(t),disabled:!t.trim()||m.isPending,children:m.isPending?"Connecting…":"Connect"})]})})]})}function Oxt(){const s=vr(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState("Test from ReLevelUp"),[o,c]=k.useState(!1),{data:d,isLoading:h}=gt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:g}}=await H.auth.getSession();if(!g)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 ${g.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),m=async()=>{if(!t||!n){ue.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:g}}=await H.auth.getSession();if(!g)throw new Error("Not authenticated");const j=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g.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();j.success?ue.success(`Test email sent! Message ID: ${j.messageId}`):ue.error(j.error||"Failed to send test email")}catch(g){ue.error(g.message||"Failed to send test email")}finally{c(!1)}},x=(d==null?void 0:d.configured)===!0;return e.jsxs(Ne,{children:[e.jsx(Ot,{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(Qs,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Nr,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Ge,{variant:x?"default":"secondary",children:h?"Checking...":x?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mi,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hi,{className:"h-3 w-3"})," Not Configured"]})})]})}),x&&e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"From Email"}),e.jsx(ke,{placeholder:"notifications@mail.relevelup.com",value:n,onChange:g=>a(g.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"To Email"}),e.jsx(ke,{placeholder:"your@email.com",value:t,onChange:g=>r(g.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Subject"}),e.jsx(ke,{value:i,onChange:g=>l(g.target.value),className:"text-sm"})]})]}),e.jsxs(G,{onClick:m,disabled:o,size:"sm",children:[o?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(G,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(Cu,{className:"h-4 w-4 mr-2"})," Launch Campaign Composer"]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Region:"})," ",d==null?void 0:d.region]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Domain:"})," send.relevelup.com (verified)"]})]})]}),!x&&!h&&e.jsx(De,{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 M_e(s){const{data:{session:t}}=await H.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 cLs({status:s}){return s==="verified"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"})," Not started"]})}function Fxt({brokerageId:s,onVerifiedSelect:t}){const r=es(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),{data:g,isLoading:v}=gt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:S,error:T}=await H.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(T)throw T;return S||[]}}),j=Lt({mutationFn:async()=>M_e({action:"request_verification",brokerage_id:s,email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ue.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:S=>ue.error(S.message)}),b=async S=>{var T,A;h(S.id);try{const P=await M_e({action:"check_status",sender_id:S.id});r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((T=P.sender)==null?void 0:T.status)==="verified"?ue.success(`${S.email} is verified! 🎉`):ue.info(`Status: ${((A=P.sender)==null?void 0:A.status)||"unknown"}`)}catch(P){ue.error(P.message)}finally{h(null)}},N=Lt({mutationFn:async S=>M_e({action:"delete",sender_id:S}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ue.success("Sender removed"),x(null)},onError:S=>ue.error(S.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),v?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):g&&g.length>0?e.jsx("div",{className:"space-y-2",children:g.map(S=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:S.email}),e.jsx(cLs,{status:S.status})]}),S.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',S.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.status==="verified"&&t&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>t(S.email),children:"Use"}),S.status!=="verified"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>b(S),disabled:d===S.id,title:"Refresh status from AWS",children:d===S.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Di,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(S),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},S.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Email Address *"}),e.jsx(ke,{type:"email",value:n,onChange:S=>a(S.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ke,{value:i,onChange:S=>l(S.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",onClick:()=>j.mutate(),disabled:!n.trim()||j.isPending,children:[j.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Yo,{open:!!m,onOpenChange:S=>!S&&x(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Remove this sender?"}),e.jsxs(Uo,{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(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m&&N.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function I_e(s){const{data:{session:t}}=await H.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 dLs({status:s}){return s==="verified"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(Hi,{className:"h-3 w-3 mr-1"})," Not started"]})}function uLs({userId:s,onVerifiedSelect:t}){const r=es(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),{data:g,isLoading:v}=gt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:S,error:T}=await H.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(T)throw T;return S||[]}}),j=Lt({mutationFn:async()=>I_e({action:"request_verification",scope:"user",email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),ue.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:S=>ue.error(S.message)}),b=async S=>{var T,A;h(S.id);try{const P=await I_e({action:"check_status",sender_id:S.id});r.invalidateQueries({queryKey:["user-verified-senders",s]}),((T=P.sender)==null?void 0:T.status)==="verified"?ue.success(`${S.email} is verified! 🎉`):ue.info(`Status: ${((A=P.sender)==null?void 0:A.status)||"unknown"}`)}catch(P){ue.error(P.message)}finally{h(null)}},N=Lt({mutationFn:async S=>I_e({action:"delete",sender_id:S}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),ue.success("Sender removed"),x(null)},onError:S=>ue.error(S.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),v?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):g&&g.length>0?e.jsx("div",{className:"space-y-2",children:g.map(S=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:S.email}),e.jsx(dLs,{status:S.status})]}),S.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',S.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.status==="verified"&&t&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>t(S.email),children:"Use"}),S.status!=="verified"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>b(S),disabled:d===S.id,title:"Refresh status from AWS",children:d===S.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Di,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(S),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},S.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Email Address *"}),e.jsx(ke,{type:"email",value:n,onChange:S=>a(S.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ke,{value:i,onChange:S=>l(S.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",onClick:()=>j.mutate(),disabled:!n.trim()||j.isPending,children:[j.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Yo,{open:!!m,onOpenChange:S=>!S&&x(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Remove this sender?"}),e.jsxs(Uo,{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(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m&&N.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function hLs(){var A,P,D,B,z;const{user:s,isBrokerageManager:t,isAdmin:r,managedBrokerages:n,selectedBrokerageId:a}=As(),i=a||((A=n==null?void 0:n[0])==null?void 0:A.id)||null,l=(t||r)&&!!i,o=es(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,g]=k.useState(""),{data:v}=gt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:$}=await H.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if($)throw $;return F}}),{data:j}=gt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:$}=await H.from("profiles").select("email, name").eq("id",s.id).single();if($)throw $;return F}}),b=((P=v==null?void 0:v.reply_to_email)==null?void 0:P.trim())||((D=j==null?void 0:j.email)==null?void 0:D.trim())||"",N=((B=v==null?void 0:v.display_name)==null?void 0:B.trim())||((z=j==null?void 0:j.name)==null?void 0:z.trim())||"";k.useEffect(()=>{c||(m(b),g(N))},[c,b,N]);const S=Lt({mutationFn:async()=>{if(!s||!h.trim())throw new Error("Please enter a reply-to email");const F={reply_to_email:h.trim(),display_name:x.trim()||null,updated_at:new Date().toISOString()};if(v){const{error:$}=await H.from("mass_email_settings").update(F).eq("user_id",s.id);if($)throw $}else{const{error:$}=await H.from("mass_email_settings").insert({user_id:s.id,...F});if($)throw $}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ue.success("Reply-to email saved!"),d(!1)},onError:F=>ue.error(F.message)}),T=!!b;return e.jsxs(Ne,{children:[e.jsx(Ot,{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(Zr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Mass Email",T?e.jsxs(Ge,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(mi,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Nr,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[T&&!c?e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:N||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"})," Edit"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Display Name"}),e.jsx(ke,{placeholder:"e.g. 🏡 Karen Hall",value:x,onChange:F=>g(F.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(ke,{type:"email",placeholder:"your@email.com",value:h,onChange:F=>m(F.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",onClick:()=>S.mutate(),disabled:S.isPending||!h.trim(),children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{d(!1),m(b),g(N)},children:[e.jsx(_r,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(a0,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Before you can send mass emails ",e.jsx("em",{children:"from"})," an address, Amazon requires that address to be verified. Add the email you want to send from below and click the verification link Amazon sends to that inbox."]})]})]}),e.jsx(uLs,{userId:s.id,onVerifiedSelect:F=>{m(F),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(a0,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Brokerage-Shared Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Addresses verified here can be used by anyone managing this brokerage."})]})]}),e.jsx(Fxt,{brokerageId:i})]})]})]})]})}function mLs(){const{isAdmin:s}=As(),t=es(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=gt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:A,error:P}=await H.from("gmail_integrations").select("*").maybeSingle();if(P)throw P;return A}}),{data:h}=gt({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:A}}=await H.auth.getUser();if(!A)return[];const{data:P,error:D}=await H.from("social_accounts").select("*").eq("user_id",A.id).order("created_at",{ascending:!1});if(D)throw D;return P}}),m=async()=>{n(!0);try{const{data:A,error:P}=await H.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(P)throw P;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get authorization URL")}catch(A){console.error("Gmail OAuth error:",A),ue.error("Failed to start Gmail connection"),n(!1)}},x=async A=>{i(!0);try{const{data:P,error:D}=await H.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:A}});if(D)throw D;if(P!=null&&P.authUrl)window.location.href=P.authUrl;else throw new Error("Failed to get authorization URL")}catch(P){console.error("Meta OAuth error:",P),ue.error("Failed to start connection. Make sure Meta App credentials are configured."),i(!1)}},g=async()=>{o(!0);try{const{data:A,error:P}=await H.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(P)throw P;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(A){console.error("LinkedIn OAuth error:",A),ue.error("Failed to start LinkedIn connection. Please try again."),o(!1)}},v=Lt({mutationFn:async A=>{const{error:P}=await H.from("gmail_integrations").delete().eq("id",A);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["gmail-integration"]}),ue.success("Gmail disconnected")},onError:()=>{ue.error("Failed to disconnect Gmail")}}),j=Lt({mutationFn:async A=>{const{error:P}=await H.from("social_accounts").delete().eq("id",A);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["social-accounts"]}),ue.success("Account disconnected")},onError:()=>{ue.error("Failed to disconnect account")}}),b=!!(c!=null&&c.is_active),N=(h==null?void 0:h.filter(A=>A.platform==="facebook"))||[],S=(h==null?void 0:h.filter(A=>A.platform==="instagram"))||[],T=(h==null?void 0:h.filter(A=>A.platform==="linkedin"))||[];return e.jsx(_s,{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(Ne,{children:[e.jsx(Ot,{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(Qs,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Gmail",b&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(De,{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(mi,{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(mi,{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(mi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),b?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Gmail?"}),e.jsx(Uo,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>v.mutate(c.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(G,{className:"mt-4",onClick:m,disabled:r||d,children:[r?e.jsx(Di,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Ga,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{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(ku,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Facebook",N.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[N.length>0&&e.jsx("div",{className:"space-y-2",children:N.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:A.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(ku,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:A.page_name||A.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Facebook?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>j.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:()=>x("facebook"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{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(au,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Instagram",S.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[S.length>0&&e.jsx("div",{className:"space-y-2",children:S.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:A.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(au,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",A.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Instagram?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>j.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:()=>x("instagram"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{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(Ne,{children:[e.jsx(Ot,{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(om,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",T.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[T.length>0&&e.jsx("div",{className:"space-y-2",children:T.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(vn,{className:"h-8 w-8",children:[e.jsx(ga,{src:A.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(om,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:A.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect LinkedIn?"}),e.jsx(Uo,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>j.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:g,disabled:l,variant:"outline",className:"gap-2",children:[l?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(oLs,{}),e.jsx(lLs,{}),e.jsx(hLs,{}),s&&e.jsx(Oxt,{})]})})}const fLs="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function pLs(){const[s,t]=k.useState(null),[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",h=window.location.hostname.startsWith("id-preview--"),m=async b=>{const N=new Uint8Array(await b.slice(0,4).arrayBuffer());return N[0]===80&&N[1]===75&&N[2]===3&&N[3]===4||N[0]===80&&N[1]===75&&N[2]===5&&N[3]===6||N[0]===80&&N[1]===75&&N[2]===7&&N[3]===8},x=b=>{const N=document.createElement("a");N.href=b,N.download="levelup-extension.zip",N.rel="noopener noreferrer",N.target="_blank",document.body.appendChild(N),N.click(),N.remove()},g=async()=>{o(!0);try{if(h){x(`${d}?v=${Date.now()}`);return}const b=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!b.ok)throw new Error(`Download failed (${b.status})`);const N=await b.blob();if(!await m(N)){x(`${d}?v=${Date.now()}`);return}const S=new Blob([N],{type:"application/zip"}),T=URL.createObjectURL(S),A=document.createElement("a");A.href=T,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(T),1e3)}catch(b){ue.error(b.message||"Download failed")}finally{o(!1)}},v=async()=>{n(!0);try{await H.auth.refreshSession();const{data:b}=await H.auth.getSession();if(!b.session){ue.error("Your session has expired. Please sign in again.");return}const{data:N,error:S}=await H.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${b.session.access_token}`}});if(S)throw S;t(N.code),i(N.expires_in||300);const T=setInterval(()=>{i(A=>A<=1?(clearInterval(T),t(null),0):A-1)},1e3)}catch(b){console.error("generateCode error",b),ue.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{n(!1)}},j=()=>{s&&(navigator.clipboard.writeText(s),ue.success("Copied"))};return e.jsx(_s,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(il,{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(w3,{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(Ne,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(G,{size:"lg",className:"w-full",onClick:()=>window.open(fLs,"_blank","noopener,noreferrer"),children:[e.jsx(w3,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Yr,{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(Ne,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{onClick:j,variant:"outline",className:"flex-1",children:[e.jsx(Ra,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(G,{onClick:v,variant:"outline",className:"flex-1",children:[e.jsx(Di,{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(Hn,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx(G,{onClick:v,disabled:r,size:"lg",className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Di,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(Ne,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(G,{variant:"link",className:"h-auto p-0 text-sm",onClick:g,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 xLs(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Gmail account...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:m,error:x}=await H.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:h}});if(x)throw x;if(m!=null&&m.success)n("success"),i(m.message||"Gmail connected successfully!"),ue.success("Gmail connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Gmail OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Gmail"),ue.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(mi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Mc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"Back to Integrations":"Try Again"})})]})})}function gLs(){const s=vr();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 yLs(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:g}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(x&&x.success===!1)throw new Error(x.error||"Failed to connect accounts");if(g){let v=g.message||"Failed to connect accounts";try{const j=g.context;if(j&&typeof j.json=="function"){const b=await j.json();b!=null&&b.error&&(v=b.error)}}catch{}throw new Error(v)}if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||0} account(s)!`),ue.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect accounts"),ue.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(mi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Mc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Integrations":"Try Again"})})]})})}const Bxt=new Date().getFullYear(),vLs=Array.from({length:5},(s,t)=>Bxt-t);function bLs(){const[s,t]=k.useState(Bxt),r=vr(),{data:n,isLoading:a}=vUt();return a?e.jsx(_s,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Vs,{className:"h-24"},i))}),e.jsx(Vs,{className:"h-96"})]})}):e.jsx(_s,{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(zs,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:vLs.map(i=>e.jsx(mt,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fr,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ao,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agents with Scorecards"}),e.jsx(Nr,{children:"Click to view individual agent scorecards"})]}),e.jsx(De,{children:!n||n.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ao,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:n.map(i=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:i.name}),e.jsx(ft,{className:"text-muted-foreground",children:i.email}),e.jsx(ft,{className:"text-right",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r(`/admin/scorecard/${i.id}`),children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const zxt=new Date().getFullYear(),_Ls=Array.from({length:10},(s,t)=>zxt-t);function XVe(){var v;const{userId:s}=Xi(),t=vr(),n=sc().pathname.startsWith("/mission-control"),[a,i]=k.useState(zxt),{data:l,isLoading:o}=gt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:j,error:b}=await H.from("profiles").select("id, name, email").eq("id",s).single();if(b)throw b;return j},enabled:!!s}),{data:c,isLoading:d}=I5e(a,s),{yearStats:h,lifetimeStats:m,showCommission:x}=lat(a,s),{data:g}=oat(a,s);return o?e.jsx(_s,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(j=>e.jsx(Vs,{className:"h-24"},j))})]})}):e.jsx(_s,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t(n?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(wa,{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(zs,{value:String(a),onValueChange:j=>i(Number(j)),children:[e.jsx(Os,{className:"w-[120px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:_Ls.map(j=>e.jsx(mt,{value:String(j),children:j},j))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:h.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.totalTransactions," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[h.buyerCount,"/",h.sellerCount]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_l,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(h.totalVolume,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:uc(h.averagePrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(De,{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:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((v=h.topLeadSource)==null?void 0:v.name)||"-"})]})})]}),g&&e.jsx(Xmt,{goals:g,stats:h,year:a,showCommission:x}),e.jsxs(Rn,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"transactions",children:"Transactions"}),e.jsx(Xt,{value:"charts",children:"Charts"}),e.jsxs(Xt,{value:"map",children:[e.jsx(ja,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(as,{value:"transactions",children:e.jsx(uAe,{transactions:c||[],showCommission:x,isLoading:d})}),e.jsx(as,{value:"charts",children:e.jsx(hAe,{stats:h,year:a})}),e.jsx(as,{value:"map",children:e.jsx(mAe,{transactions:c||[],isLoading:d})})]})]})})}function wLs(){const s=es(),[t,r]=k.useState(""),[n,a]=k.useState("all"),[i,l]=k.useState(null);Crt();const{data:o,refetch:c}=gt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:F}=await H.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(F==null?void 0:F.enabled)??!1}}),{data:d,isLoading:h}=gt({queryKey:["admin-listings"],queryFn:async()=>{const{data:F,error:$}=await H.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($)throw $;return F}}),{data:m}=gt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:F}=await H.from("listings").select("id, is_approved, status"),{data:$}=await H.from("listing_shares").select("id"),{data:X}=await H.from("listing_views").select("id"),{count:K}=await H.from("listing_leads").select("id",{count:"exact",head:!0}),Q=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:Y}=await H.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",Q);return{total:(F==null?void 0:F.length)||0,pending:(F==null?void 0:F.filter(ne=>!ne.is_approved).length)||0,active:(F==null?void 0:F.filter(ne=>ne.status==="active").length)||0,totalShares:($==null?void 0:$.length)||0,totalViews:(X==null?void 0:X.length)||0,totalLeads:K||0,leadsLast7:Y||0}}}),{data:x}=gt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const F={};let $=0;const X=1e3;for(;;){const{data:K,error:Q}=await H.from("listing_leads").select("listing_id").range($,$+X-1);if(Q)throw Q;if(!K||K.length===0)break;for(const Y of K)Y.listing_id&&(F[Y.listing_id]=(F[Y.listing_id]||0)+1);if(K.length{const{data:F,error:$}=await H.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if($)throw $;return F}}),j=async(F,$,X="submit_url")=>{try{const{data:{session:K}}=await H.auth.getSession();if(!K)return;const{data:Q,error:Y}=await H.functions.invoke("google-indexing",{body:{action:X,listing_id:F,listing_slug:$}});if(Y)throw Y;if((Q==null?void 0:Q.configured)===!1)return;Q!=null&&Q.success&&ue.success("Submitted to Google for indexing")}catch(K){console.error("Google indexing submission failed:",K)}},b=Lt({mutationFn:async()=>{const{data:{session:F}}=await H.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:$,error:X}=await H.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(X)throw X;return $},onSuccess:F=>{if((F==null?void 0:F.configured)===!1){ue.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ue.success(`Submitted ${(F==null?void 0:F.succeeded)||0} URLs to Google (${(F==null?void 0:F.failed)||0} failed)`)},onError:F=>{ue.error("Failed to submit to Google"),console.error(F)}}),N=Lt({mutationFn:async({id:F,approved:$,slug:X})=>{const{error:K}=await H.from("listings").update({is_approved:$}).eq("id",F);if(K)throw K;return{id:F,approved:$,slug:X}},onSuccess:F=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ue.success(F.approved?"Listing approved":"Listing unapproved"),F.approved?j(F.id,F.slug||null,"submit_url"):j(F.id,F.slug||null,"remove_url")}}),S=Lt({mutationFn:async({id:F,featured:$})=>{const{error:X}=await H.from("listings").update({is_featured:$}).eq("id",F);if(X)throw X},onSuccess:(F,{featured:$})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ue.success($?"Listing featured":"Listing unfeatured")}}),T=Lt({mutationFn:async F=>{const{error:$}=await H.from("listings").delete().eq("id",F);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ue.success("Listing deleted")}}),A=Lt({mutationFn:async F=>{const{error:$}=await H.from("feature_flags").update({enabled:F}).eq("key","listing_exchange_enabled");if($)throw $},onSuccess:()=>{c(),ue.success("Feature flag updated")}}),P=o??!1,D=d==null?void 0:d.filter(F=>{var K,Q,Y,ne;const $=((K=F.city)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((Y=(Q=F.agent)==null?void 0:Q.name)==null?void 0:Y.toLowerCase().includes(t.toLowerCase()))||((ne=F.property_address)==null?void 0:ne.toLowerCase().includes(t.toLowerCase())),X=n==="all"||n==="pending"&&!F.is_approved||n==="approved"&&F.is_approved;return $&&X}),B=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),z=F=>{const $={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 $[F]||$.active};return e.jsxs(_s,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>b.mutate(),disabled:b.isPending,className:"gap-2",children:[b.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(gc,{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(br,{checked:P,onCheckedChange:F=>A.mutate(F)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.total)||0})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_o,{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(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{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(Ne,{children:e.jsxs(De,{className:"p-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:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalViews)||0})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pc,{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(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nl,{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(Ne,{children:e.jsx(De,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by city, address, or agent...",value:t,onChange:F=>r(F.target.value),className:"pl-9"})]}),e.jsx(Rn,{value:n,onValueChange:F=>a(F),children:e.jsxs(Dn,{children:[e.jsx(Xt,{value:"all",children:"All"}),e.jsx(Xt,{value:"pending",children:"Pending"}),e.jsx(Xt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{children:["Listings (",(D==null?void 0:D.length)||0,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-center",children:"Approved"}),e.jsx(Tt,{className:"text-center",children:"Featured"}),e.jsx(Tt,{children:"Views"}),e.jsx(Tt,{children:"Shares"}),e.jsx(Tt,{children:"Leads"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{})]})}),e.jsx(Bn,{children:h?e.jsx(qs,{children:e.jsx(ft,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):D==null?void 0:D.map(F=>{var $,X,K,Q,Y;return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(X=($=F.photos)==null?void 0:$[0])!=null&&X.photo_url?e.jsx("img",{src:F.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(Sa,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:F.property_address||`${F.city}, ${F.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(K=F.property_type)==null?void 0:K.replace("_"," ")})]})]})}),e.jsx(ft,{children:e.jsx("p",{className:"text-sm",children:((Q=F.agent)==null?void 0:Q.name)||"Unknown"})}),e.jsx(ft,{className:"font-medium",children:B(F.price)}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",className:z(F.status),children:(Y=F.status)==null?void 0:Y.replace("_"," ")})}),e.jsx(ft,{className:"text-center",children:e.jsx(br,{checked:F.is_approved??!1,onCheckedChange:ne=>N.mutate({id:F.id,approved:ne,slug:F.slug})})}),e.jsx(ft,{className:"text-center",children:e.jsx(br,{checked:F.is_featured??!1,onCheckedChange:ne=>S.mutate({id:F.id,featured:ne})})}),e.jsx(ft,{children:F.view_count||0}),e.jsx(ft,{children:F.share_count||0}),e.jsx(ft,{children:((x==null?void 0:x[F.id])??0)>0?e.jsx(G,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:F.id,label:F.property_address||`${F.city}, ${F.state}`}),children:x==null?void 0:x[F.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy")}),e.jsx(ft,{children:e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",children:e.jsx(ix,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",children:[e.jsxs(Da,{onClick:()=>window.open(`/mission-control/listings/${F.id}`,"_blank"),children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Da,{onClick:()=>S.mutate({id:F.id,featured:!F.is_featured}),children:[e.jsx(Qn,{className:"h-4 w-4 mr-2"}),F.is_featured?"Unfeature":"Feature"]}),e.jsxs(Da,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&T.mutate(F.id)},children:[e.jsx(_r,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},F.id)})})]})})})]})]}),e.jsx(vs,{open:!!i,onOpenChange:F=>!F&&l(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Leads from listing"}),e.jsx(Fr,{children:i==null?void 0:i.label})]}),v?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..."]}):!g||g.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Captured"})]})}),e.jsx(Bn,{children:g.map(F=>{var $;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:[F.first_name,F.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(ft,{children:F.email}),e.jsx(ft,{children:F.phone||"—"}),e.jsx(ft,{children:e.jsx(Ge,{variant:"outline",children:($=F.lead_type)==null?void 0:$.replace("_"," ")})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy h:mm a")})]},F.id)})})]})]})})]})}const jLs=()=>{var m,x;const[s,t]=k.useState(""),[r,n]=k.useState(null),{data:a,isLoading:i}=gt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:g,error:v}=await H.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(v)throw v;const j=(g==null?void 0:g.map(S=>S.user_id))||[],{data:b}=await H.from("profiles").select("id, name, email").in("id",j);return g==null?void 0:g.map(S=>({...S,profiles:(b==null?void 0:b.find(T=>T.id===S.user_id))||null}))}}),l=a==null?void 0:a.filter(g=>{var j,b,N,S,T;const v=s.toLowerCase();return((b=(j=g.profiles)==null?void 0:j.name)==null?void 0:b.toLowerCase().includes(v))||((S=(N=g.profiles)==null?void 0:N.email)==null?void 0:S.toLowerCase().includes(v))||((T=g.review_text)==null?void 0:T.toLowerCase().includes(v))}),o=a!=null&&a.length?(a.reduce((g,v)=>g+v.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((g,v)=>(g[v.rating]=(g[v.rating]||0)+1,g),{}),d=(a==null?void 0:a.filter(g=>g.posted_to_google).length)||0,h=g=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(v=>e.jsx(Qn,{className:Bt("h-4 w-4",g>=v?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},v))});return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{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(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Total Reviews"}),e.jsx(zt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Average Rating"}),e.jsxs(zt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Qn,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"5-Star Reviews"}),e.jsx(zt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(Ne,{children:e.jsxs(Ot,{className:"pb-2",children:[e.jsx(Nr,{children:"Posted to Google"}),e.jsxs(zt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Yr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, or review...",value:s,onChange:g=>t(g.target.value),className:"pl-9"})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Rating"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Tt,{children:"Google"}),e.jsx(Tt,{children:"Date"})]})}),e.jsx(Bn,{children:i?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(g=>{var v,j;return e.jsxs(qs,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>n(g),children:[e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((v=g.profiles)==null?void 0:v.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(j=g.profiles)==null?void 0:j.email})]})}),e.jsx(ft,{children:h(g.rating)}),e.jsx(ft,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:g.review_text||"-"})}),e.jsx(ft,{children:g.posted_to_google?e.jsx(Ge,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Ge,{variant:"outline",children:"No"})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:Ss(new Date(g.created_at),"MMM d, yyyy")})]},g.id)})})]})})}),e.jsx(vs,{open:!!r,onOpenChange:()=>n(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(js,{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"}),((x=r.profiles)==null?void 0:x.email)&&e.jsxs("a",{href:`mailto:${r.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(Qs,{className:"h-3 w-3"}),r.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[h(r.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[r.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rn,{className:"h-4 w-4"}),Ss(new Date(r.created_at),"MMMM d, yyyy 'at' h:mm a")]}),r.posted_to_google?e.jsxs(Ge,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Ge,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},NLs=[{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"}],kLs=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 SLs(){const s=es(),{user:t}=As(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=gt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:z,error:F}=await H.from("weekly_digest_settings").select("*").single();if(F)throw F;return z}}),{data:h,isLoading:m}=gt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:z,error:F}=await H.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(F)throw F;return z}}),{data:x}=gt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:z,error:F}=await H.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(F)throw F;return z||0}}),{data:g,refetch:v}=gt({queryKey:["digest-queue-status"],queryFn:async()=>{const z=new Date;z.setUTCHours(0,0,0,0);const[F,$,X,K]=await Promise.all([H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",z.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",z.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",z.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",z.toISOString())]);return{pending:F.count||0,processing:$.count||0,sent:X.count||0,failed:K.count||0,total:(F.count||0)+($.count||0)+(X.count||0)+(K.count||0)}},refetchInterval:5e3});k.useEffect(()=>{if(g&&(g.pending>0||g.processing>0)){const z=setInterval(()=>{v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(z)}},[g,v,s]);const{data:j=0}=gt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const z=new Date;z.setUTCHours(0,0,0,0);const{count:F,error:$}=await H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",z.toISOString());if($)throw $;return F||0}}),b=Lt({mutationFn:async z=>{const{error:F}=await H.from("weekly_digest_settings").update(z).eq("id",c==null?void 0:c.id);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ue.success("Settings updated")},onError:z=>{ue.error("Failed to update settings: "+z.message)}}),N=async()=>{n(!0);try{const{data:z,error:F}=await H.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(F)throw F;z.queued?ue.success(`${z.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):z.sent!==void 0&&ue.success(`Digest sent! ${z.sent} emails delivered, ${z.failed} failed`),v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(z){ue.error("Failed to send digest: "+z.message)}finally{n(!1)}},S=async()=>{var z,F,$,X,K,Q;if(!(t!=null&&t.email)){ue.error("No email found for your account");return}i(!0);try{const{data:Y,error:ne}=await H.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(ne)throw ne;const de=Y==null?void 0:Y.resendId,ce=Y==null?void 0:Y.resendDetails,ae=ce==null?void 0:ce.status,ie=((z=ce==null?void 0:ce.body)==null?void 0:z.status)||(($=(F=ce==null?void 0:ce.body)==null?void 0:F.data)==null?void 0:$.status),me=((K=(X=ce==null?void 0:ce.body)==null?void 0:X.error)==null?void 0:K.message)||((Q=ce==null?void 0:ce.body)==null?void 0:Q.message);ue.success(de?`Preview accepted by email provider (id: ${de})${ae?`, status check: ${ae}`:""}${ie?`, provider: ${ie}`:""}${me?` (${me})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(Y){ue.error("Failed to send preview: "+Y.message)}finally{i(!1)}},T=async()=>{o(!0);try{const{data:z,error:F}=await H.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(F)throw F;z.queued===0||z.sent===0&&z.failed===0&&!z.queued?ue.info("No failed emails to retry"):z.queued?ue.success(`${z.queued} emails queued for retry!`):ue.success(`Retry complete! ${z.sent} emails delivered, ${z.failed} failed`),v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(z){ue.error("Failed to retry: "+z.message)}finally{o(!1)}},A=g!=null&&g.total?Math.round((g.sent+g.failed)/g.total*100):0,P=((g==null?void 0:g.pending)||0)>0||((g==null?void 0:g.processing)||0)>0,{data:D}=gt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var Q,Y;const z=new Date;z.setUTCHours(0,0,0,0);const[F,$,X,K]=await Promise.all([H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",z.toISOString()),H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",z.toISOString()),H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",z.toISOString()),H.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:F.count||0,totalFailed:$.count||0,agentOsEngaged:X.count||0,lastSent:((Y=(Q=K.data)==null?void 0:Q[0])==null?void 0:Y.sent_at)||null}},refetchInterval:P?5e3:!1}),B={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(_s,{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(_s,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(Rn,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(lo,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Xt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(ao,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(as,{value:"settings",className:"space-y-6",children:[P&&g&&e.jsx(Ne,{className:"border-primary/50 bg-primary/5",children:e.jsxs(De,{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:[g.sent.toLocaleString()," sent, ",g.pending.toLocaleString()," pending",g.failed>0&&`, ${g.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(ri,{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(g.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsx(De,{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(fr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:x}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(Ne,{children:e.jsx(De,{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(Mn,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:B.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(Ne,{children:e.jsx(De,{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(Mc,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:B.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(Ne,{children:e.jsx(De,{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(cn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:B.lastSent?Ss(new Date(B.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(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Nr,{children:"Configure when the digest is sent"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(br,{checked:c==null?void 0:c.is_enabled,onCheckedChange:z=>b.mutate({is_enabled:z})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Cron Frequency"}),e.jsxs(zs,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:z=>b.mutate({cron_frequency:z}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(mt,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(c==null?void 0:c.cron_frequency)==="hourly"?"Cron runs every hour; digest sends when day & hour match.":"Cron runs once daily at the selected hour (UTC)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Day of Week"}),e.jsxs(zs,{value:String(c==null?void 0:c.send_day),onValueChange:z=>b.mutate({send_day:parseInt(z)}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:NLs.map(z=>e.jsx(mt,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Time (UTC)"}),e.jsxs(zs,{value:String(c==null?void 0:c.send_hour),onValueChange:z=>b.mutate({send_hour:parseInt(z)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:kLs.map(z=>e.jsx(mt,{value:z.value,children:z.label},z.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{onClick:S,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(G,{onClick:N,disabled:r,className:"flex-1",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),r?"Sending...":"Send to All"]})]}),j>0&&e.jsxs(G,{onClick:T,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Di,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${j} Failed`]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Nr,{children:"Choose what to include in the digest"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"New Resources"})]}),e.jsx(br,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:z=>b.mutate({include_new_resources:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Community Highlights"})]}),e.jsx(br,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:z=>b.mutate({include_community_posts:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ao,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Agent OS Stats"})]}),e.jsx(br,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:z=>b.mutate({include_agent_os_stats:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Upcoming Events"})]}),e.jsx(br,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:z=>b.mutate({include_upcoming_events:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zd,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Goals Progress"})]}),e.jsx(br,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:z=>b.mutate({include_goals_progress:z})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Custom Introduction"}),e.jsx(Nr,{children:"Personalize the intro message (optional)"})]}),e.jsx(De,{children:e.jsx(ur,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:z=>b.mutate({custom_intro_text:z.target.value||null}),rows:3})})]})]}),e.jsx(as,{value:"stats",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Nr,{children:"Recent digest emails sent to members"})]}),e.jsx(De,{children:m?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(z=>e.jsx("div",{className:"h-12 bg-muted rounded"},z))}):h&&h.length>0?e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Sent At"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Agent OS"})]})}),e.jsx(Bn,{children:h.map(z=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:z.email_sent_to}),e.jsx(ft,{children:Ss(new Date(z.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(ft,{children:e.jsx(Ge,{variant:z.delivery_status==="sent"?"default":"destructive",children:z.delivery_status})}),e.jsx(ft,{children:z.resources_count}),e.jsx(ft,{children:z.has_agent_os_activity?e.jsx(Ge,{variant:"secondary",children:"Active"}):e.jsx(Ge,{variant:"outline",children:"Not Started"})})]},z.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Qs,{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 CLs={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 TLs(){var ge,be,Oe;const s=es(),[t,r]=k.useState(""),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(!0),[j,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(null),{data:P,isLoading:D}=gt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Me,error:Pe}=await H.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Pe)throw Pe;const Ee=(Me==null?void 0:Me.map(ze=>ze.user_id))||[],{data:$e}=await H.from("profiles").select("id, name, email").in("id",Ee),Se=new Map(($e==null?void 0:$e.map(ze=>[ze.id,{name:ze.name,email:ze.email}]))||[]);return Me==null?void 0:Me.map(ze=>({...ze,profile:Se.get(ze.user_id)||null}))}}),{data:B}=gt({queryKey:["all-profiles-for-points",P],queryFn:async()=>{const Pe=[];let Ee=0;for(;;){const{data:$e,error:Se}=await H.from("profiles").select("id, name, email").order("name").range(Ee,Ee+1e3-1);if(Se)throw Se;if(Pe.push(...$e),!$e||$e.length<1e3)break;Ee+=1e3}return Pe}}),F=((B==null?void 0:B.filter(Me=>!(P!=null&&P.some(Pe=>Pe.user_id===Me.id))))||[]).filter(Me=>{var Ee,$e;if(!N)return!0;const Pe=N.toLowerCase();return((Ee=Me.name)==null?void 0:Ee.toLowerCase().includes(Pe))||(($e=Me.email)==null?void 0:$e.toLowerCase().includes(Pe))}),{data:$,isLoading:X}=gt({queryKey:["agent-point-history",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Me,error:Pe}=await H.from("agent_points").select("*").eq("user_id",n.user_id).order("created_at",{ascending:!1});if(Pe)throw Pe;return Me},enabled:!!(n!=null&&n.user_id)&&o}),{data:K}=gt({queryKey:["agent-badges",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Me,error:Pe}=await H.from("agent_badges").select("*").eq("user_id",n.user_id).order("earned_at",{ascending:!1});if(Pe)throw Pe;return Me},enabled:!!(n!=null&&n.user_id)}),Q=Lt({mutationFn:async({userId:Me,points:Pe,reason:Ee})=>{const{error:$e}=await H.from("agent_points").insert({user_id:Me,points:Pe,reason:Ee});if($e)throw $e;const{data:Se}=await H.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Me).maybeSingle(),ze=((Se==null?void 0:Se.total_points)||0)+Pe,Te=((Se==null?void 0:Se.spendable_points)||0)+Pe,{error:ye}=await H.from("agent_attendance_stats").upsert({user_id:Me,total_points:Math.max(0,ze),spendable_points:Math.max(0,Te),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ye)throw ye},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),h(""),x(""),ue.success(g?"Points awarded successfully!":"Points deducted successfully!")},onError:Me=>{console.error("Error modifying points:",Me),ue.error("Failed to modify points")}}),Y=()=>{if(!n||!d||!m){ue.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){ue.error("Please enter a valid positive number");return}Q.mutate({userId:n.user_id,points:g?Me:-Me,reason:m})},ne=()=>{if(!T||!d||!m){ue.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){ue.error("Please enter a valid positive number");return}Q.mutate({userId:T.id,points:Me,reason:m},{onSuccess:()=>{b(!1),A(null),S("")}})},de=(Me,Pe)=>{a(Me),v(Pe),l(!0)},ce=Me=>{a(Me),c(!0)},ae=P==null?void 0:P.filter(Me=>{var Se,ze,Te,ye;const Pe=((ze=(Se=Me.profile)==null?void 0:Se.name)==null?void 0:ze.toLowerCase())||"",Ee=((ye=(Te=Me.profile)==null?void 0:Te.email)==null?void 0:ye.toLowerCase())||"",$e=t.toLowerCase();return Pe.includes($e)||Ee.includes($e)}),ie=(P==null?void 0:P.reduce((Me,Pe)=>Me+Pe.total_points,0))||0,me=(P==null?void 0:P.length)||0,oe=me>0?Math.round(ie/me):0;return D?e.jsx(_s,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Me=>e.jsx(Vs,{className:"h-24"},Me))}),e.jsx(Vs,{className:"h-96"})]})}):e.jsx(_s,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:me}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ie.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:oe}),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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search agents...",value:t,onChange:Me=>r(Me.target.value),className:"pl-10"})]}),e.jsxs(G,{onClick:()=>b(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Agent Leaderboard"}),e.jsx(Nr,{children:"All agents with their points, events, and streaks"})]}),e.jsx(De,{children:!ae||ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Total Points"}),e.jsx(Tt,{className:"text-center",children:"Spendable"}),e.jsx(Tt,{className:"text-center",children:"Events"}),e.jsx(Tt,{className:"text-center",children:"Streak"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:ae.map((Me,Pe)=>{var Ee,$e,Se,ze;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:Pe<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Pe===0?"bg-yellow-100 text-yellow-700":Pe===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Pe+1}):e.jsx("span",{className:"text-muted-foreground",children:Pe+1})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vn,{className:"h-8 w-8",children:e.jsx(bn,{children:(($e=(Ee=Me.profile)==null?void 0:Ee.name)==null?void 0:$e.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Se=Me.profile)==null?void 0:Se.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ze=Me.profile)==null?void 0:ze.email})]})]})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),Me.total_points]})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(li,{className:"h-3 w-3 mr-1"}),Me.spendable_points||0]})}),e.jsx(ft,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3 text-muted-foreground"}),Me.total_events_attended]})}),e.jsx(ft,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(xc,{className:"h-3 w-3 text-orange-500"}),Me.current_streak]})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>de(Me,!0),title:"Award points",children:e.jsx(Ws,{className:"h-4 w-4 text-green-600"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>de(Me,!1),title:"Deduct points",children:e.jsx(qv,{className:"h-4 w-4 text-red-600"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ce(Me),title:"View history",children:e.jsx(aM,{className:"h-4 w-4"})})]})})]},Me.user_id)})})]})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:g?"Award Points":"Deduct Points"}),e.jsxs(Fr,{children:[g?"Award":"Deduct"," points ",g?"to":"from"," ",((ge=n==null?void 0:n.profile)==null?void 0:ge.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"points",children:"Points Amount"}),e.jsx(ke,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Me=>h(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"reason",children:"Reason"}),e.jsx(ur,{id:"reason",placeholder:"Enter reason for this adjustment...",value:m,onChange:Me=>x(Me.target.value)})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:Y,disabled:Q.isPending,className:g?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:Q.isPending?"Saving...":g?"Award Points":"Deduct Points"})]})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsxs(bs,{children:["Point History: ",(be=n==null?void 0:n.profile)==null?void 0:be.name]}),e.jsx(Fr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(Rn,{defaultValue:"history",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"history",children:"Point History"}),e.jsx(Xt,{value:"badges",children:"Badges"})]}),e.jsx(as,{value:"history",className:"mt-4",children:X?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Me=>e.jsx(Vs,{className:"h-12"},Me))}):!$||$.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(aM,{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:$.map(Me=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:Me.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ss(new Date(Me.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ge,{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(as,{value:"badges",className:"mt-4",children:!K||K.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Xl,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No badges earned yet"})]}):e.jsx("div",{className:"grid grid-cols-2 gap-3",children:K.map(Me=>e.jsxs("div",{className:`p-3 rounded-lg ${CLs[Me.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xl,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Me.badge_name})]}),Me.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Me.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Ss(new Date(Me.earned_at),"MMM d, yyyy")]})]},Me.id))})})]})]})}),e.jsx(vs,{open:j,onOpenChange:Me=>{b(Me),Me||(A(null),S(""),h(""),x(""))},children:e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Award Points to New Agent"}),e.jsx(Fr,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:T?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(vn,{className:"h-10 w-10",children:e.jsx(bn,{children:((Oe=T.name)==null?void 0:Oe.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:T.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.email})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(ke,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Me=>h(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"new-reason",children:"Reason"}),e.jsx(ur,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:m,onChange:Me=>x(Me.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:N,onChange:Me=>S(Me.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:F.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(fr,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:N?"No matching agents found":"All agents already have points"})]}):F.slice(0,20).map(Me=>{var Pe;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(vn,{className:"h-8 w-8",children:e.jsx(bn,{children:((Pe=Me.name)==null?void 0:Pe.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(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),T&&e.jsxs(G,{onClick:ne,disabled:Q.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function ELs(){const{data:s,isLoading:t}=jMt(),[r,n]=k.useState(null),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState("all"),[h,m]=k.useState("newest"),[x,g]=k.useState("table"),v=k.useMemo(()=>(s==null?void 0:s.map(T=>T.user_id))||[],[s]),j=k.useMemo(()=>(s==null?void 0:s.map(T=>T.id))||[],[s]),{data:b}=gt({queryKey:["card-profiles-lookup",v],queryFn:async()=>{if(v.length===0)return{};const{data:T}=await H.from("profiles").select("id, name, email").in("id",v),A={};return T==null||T.forEach(P=>{A[P.id]={name:P.name||"",email:P.email||""}}),A},enabled:v.length>0}),{data:N}=gt({queryKey:["card-stats-all",j],queryFn:async()=>{if(j.length===0)return{};const T={};j.forEach(D=>{T[D]={views:0,leads:0}});const{data:A}=await H.from("agent_card_interactions").select("card_id").in("card_id",j).eq("interaction_type","card_view");A==null||A.forEach(D=>{T[D.card_id]&&T[D.card_id].views++});const{data:P}=await H.from("agent_card_leads").select("card_id").in("card_id",j);return P==null||P.forEach(D=>{T[D.card_id]&&T[D.card_id].leads++}),T},enabled:j.length>0}),S=k.useMemo(()=>{if(!s)return[];let T=[...s];if(c==="live"?T=T.filter(A=>A.is_published):c==="draft"&&(T=T.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();T=T.filter(P=>{var B,z;const D=b==null?void 0:b[P.user_id];return P.slug.toLowerCase().includes(A)||((B=D==null?void 0:D.name)==null?void 0:B.toLowerCase().includes(A))||((z=D==null?void 0:D.email)==null?void 0:z.toLowerCase().includes(A))})}return h==="newest"?T.sort((A,P)=>new Date(P.created_at).getTime()-new Date(A.created_at).getTime()):h==="oldest"?T.sort((A,P)=>new Date(A.created_at).getTime()-new Date(P.created_at).getTime()):h==="name"?T.sort((A,P)=>{var D,B;return(((D=b==null?void 0:b[A.user_id])==null?void 0:D.name)||"").localeCompare(((B=b==null?void 0:b[P.user_id])==null?void 0:B.name)||"")}):h==="slug"?T.sort((A,P)=>A.slug.localeCompare(P.slug)):h==="views_desc"?T.sort((A,P)=>{var D,B;return(((D=N==null?void 0:N[P.id])==null?void 0:D.views)||0)-(((B=N==null?void 0:N[A.id])==null?void 0:B.views)||0)}):h==="views_asc"?T.sort((A,P)=>{var D,B;return(((D=N==null?void 0:N[A.id])==null?void 0:D.views)||0)-(((B=N==null?void 0:N[P.id])==null?void 0:B.views)||0)}):h==="leads_desc"?T.sort((A,P)=>{var D,B;return(((D=N==null?void 0:N[P.id])==null?void 0:D.leads)||0)-(((B=N==null?void 0:N[A.id])==null?void 0:B.leads)||0)}):h==="leads_asc"&&T.sort((A,P)=>{var D,B;return(((D=N==null?void 0:N[A.id])==null?void 0:D.leads)||0)-(((B=N==null?void 0:N[P.id])==null?void 0:B.leads)||0)}),T},[s,c,l,h,b]);return e.jsxs(_s,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(G,{onClick:()=>i(!0),children:[e.jsx(Ws,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name, email, or slug...",value:l,onChange:T=>o(T.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:c,onValueChange:d,children:[e.jsx(Os,{className:"w-full sm:w-36",children:e.jsx(Us,{placeholder:"Status"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All Status"}),e.jsx(mt,{value:"live",children:"Live"}),e.jsx(mt,{value:"draft",children:"Draft"})]})]}),e.jsxs(zs,{value:h,onValueChange:m,children:[e.jsx(Os,{className:"w-full sm:w-44",children:e.jsx(Us,{placeholder:"Sort by"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"newest",children:"Newest First"}),e.jsx(mt,{value:"oldest",children:"Oldest First"}),e.jsx(mt,{value:"name",children:"Name A–Z"}),e.jsx(mt,{value:"slug",children:"Slug A–Z"}),e.jsx(mt,{value:"views_desc",children:"Most Views"}),e.jsx(mt,{value:"views_asc",children:"Fewest Views"}),e.jsx(mt,{value:"leads_desc",children:"Most Leads"}),e.jsx(mt,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(G,{variant:x==="table"?"default":"ghost",size:"sm",onClick:()=>g("table"),className:"rounded-r-none",children:e.jsx(fM,{className:"h-4 w-4"})}),e.jsx(G,{variant:x==="grid"?"default":"ghost",size:"sm",onClick:()=>g("grid"),className:"rounded-l-none",children:e.jsx(Sf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",S.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(T=>e.jsx(Vs,{className:"h-48"},T))}):S.length>0?x==="table"?e.jsx(ALs,{cards:S,cardProfiles:b,cardStats:N,onEdit:n,sortBy:h,setSortBy:m}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:S.map(T=>e.jsx(MLs,{card:T,onEdit:()=>n(T),stats:N==null?void 0:N[T.id]},T.id))}):s&&s.length>0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(fn,{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(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(G,{onClick:()=>i(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(ILs,{open:a,onOpenChange:i}),r&&e.jsx(PLs,{card:r,open:!!r,onOpenChange:T=>!T&&n(null)})]})}function ALs({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(Ku,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Fd,{className:"h-3 w-3"}):e.jsx(Rd,{className:"h-3 w-3 opacity-40"});return e.jsx(Ne,{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(Fd,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],h=r==null?void 0:r[c.id],m=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(Ge,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(h==null?void 0:h.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(h==null?void 0:h.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(c),className:"h-8 w-8 p-0",children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(m),ue.success("Link copied!")},children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function MLs({card:s,onEdit:t,stats:r}){const[n,a]=k.useState(null);k.useEffect(()=>{(async()=>{const{data:c}=await H.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:h}=await H.storage.from("avatars").list(`${s.user_id}`);if(h&&h.length>0){const{data:m}=H.storage.from("avatars").getPublicUrl(`${s.user_id}/${h[0].name}`);d=m.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),ue.success("Link copied!")};return e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:(n==null?void 0:n.avatar_url)||void 0}),e.jsx(bn,{children:((n==null?void 0:n.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(n==null?void 0:n.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Ge,{variant:s.is_published?"default":"secondary",children:s.is_published?"Live":"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{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(fr,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(G,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Ra,{className:"h-3 w-3"})}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Yr,{className:"h-3 w-3"})})})]})]})})}function ILs({open:s,onOpenChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(!1),h=ket(),m=l.trim(),{data:x}=gt({queryKey:["profiles-search-for-cards",m],queryFn:async()=>{let S=H.from("profiles").select("id, name, email").order("name").limit(50);m.length>=2&&(S=S.or(`name.ilike.%${m}%,email.ilike.%${m}%`));const{data:T}=await S;return T||[]},enabled:s}),[g,v]=k.useState(null),j=(x==null?void 0:x.find(S=>S.id===r))||g,b=()=>{if(!r||!a.trim()){ue.error("Select an agent and enter a slug");return}h.mutate({user_id:r,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),n(""),i(""),o("")}})},N=S=>{var A;n(S),d(!1);const T=x==null?void 0:x.find(P=>P.id===S);T&&(v(T),i(((A=T.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(js,{children:[e.jsx(bs,{children:"Create Agent Card"}),e.jsx(Fr,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Agent"}),e.jsxs(Ao,{open:c,onOpenChange:d,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[j?`${j.name} (${j.email})`:"Search for an agent...",e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ix,{shouldFilter:!1,children:[e.jsx(Px,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Lx,{children:[e.jsx(Dx,{children:"No agents found."}),e.jsx(Rx,{children:(x||[]).map(S=>e.jsxs(vf,{value:S.id,onSelect:N,children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4",r===S.id?"opacity-100":"opacity-0")}),S.name," (",S.email,")"]},S.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(ke,{value:a,onChange:S=>i(S.target.value),placeholder:"john-doe"})]})]}),e.jsx(G,{onClick:b,disabled:h.isPending,className:"w-full",children:h.isPending?"Creating...":"Create Card"})]})]})})}function PLs({card:s,open:t,onOpenChange:r}){const n=Cet(),{data:a}=Tet(s.id),i=es(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(!1),[x,g]=k.useState(""),[v,j]=k.useState(s.slug),[b,N]=k.useState(!1),[S,T]=k.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});k.useEffect(()=>{t&&(async()=>{try{const{data:$}=await H.storage.from("avatars").list(`${s.user_id}`);if($&&$.length>0){const{data:X}=H.storage.from("avatars").getPublicUrl(`${s.user_id}/${$[0].name}`);o(`${X.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=F=>{var K;const $=(K=F.target.files)==null?void 0:K[0];if(!$)return;if(!$.type.startsWith("image/")){ue.error("Please select an image file");return}if($.size>5*1024*1024){ue.error("Image must be under 5MB");return}const X=new FileReader;X.onloadend=()=>{g(X.result),m(!0)},X.readAsDataURL($),F.target.value=""},P=async F=>{d(!0);try{const{data:$}=await H.storage.from("avatars").list(`${s.user_id}`);$&&$.length>0&&await H.storage.from("avatars").remove($.map(ne=>`${s.user_id}/${ne.name}`));const X=`${s.user_id}/avatar.jpg`,{error:K}=await H.storage.from("avatars").upload(X,F,{upsert:!0,contentType:"image/jpeg"});if(K)throw K;const{data:Q}=H.storage.from("avatars").getPublicUrl(X),Y=`${Q.publicUrl}?t=${Date.now()}`;o(Y),await H.from("profiles").update({avatar_url:Y}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ue.success("Photo updated!")}catch($){ue.error($.message||"Upload failed")}finally{d(!1)}},D=async()=>{const F=v.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!F){ue.error("Please enter a valid URL");return}if(F===s.slug){ue.info("No changes to save");return}N(!0);try{const{data:$}=await H.from("agent_cards").select("id").eq("slug",F).neq("id",s.id).maybeSingle();if($){ue.error("This URL is already taken. Try another one.");return}const{error:X}=await H.from("agent_cards").update({slug:F}).eq("id",s.id);if(X)throw X;j(F),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ue.success("Card address updated!")}catch{ue.error("Failed to update card address")}finally{N(!1)}},B=async(F,$)=>{var K;const X=(K=F.target.files)==null?void 0:K[0];if(X){if(!X.type.startsWith("image/")){ue.error("Please select an image file");return}try{const Q=X.name.split(".").pop()||"png",Y=$==="brokerage_logo_url"?"brokerage-logo":"team-logo",ne=`${s.user_id}/${Y}.${Q}`,{error:de}=await H.storage.from("card-logos").upload(ne,X,{upsert:!0});if(de)throw de;const{data:ce}=H.storage.from("card-logos").getPublicUrl(ne),ae=ce.publicUrl+"?t="+Date.now();T($==="brokerage_logo_url"?ie=>({...ie,[$]:ae,brokerage_display_name:""}):ie=>({...ie,[$]:ae,team_name:""})),ue.success("Logo uploaded!")}catch{ue.error("Failed to upload logo")}finally{F.target.value=""}}},z=()=>{n.mutate({id:s.id,...S,title:S.title||null,positioning_statement:S.positioning_statement||null,bio:S.bio||null,review_snippet:S.review_snippet||null,review_source_url:S.review_source_url||null,booking_url:S.booking_url||null,custom_cta_label:S.custom_cta_label||null,custom_cta_url:S.custom_cta_url||null,brokerage_display_name:S.brokerage_display_name||null,brokerage_logo_url:S.brokerage_logo_url||null,brokerage_logo_size:S.brokerage_logo_size,team_name:S.team_name||null,team_logo_url:S.team_logo_url||null,team_logo_size:S.team_logo_size},{onSuccess:()=>r(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(vs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Agent Card"}),e.jsxs(Fr,{children:["/card/",s.slug]})]}),e.jsxs(Rn,{defaultValue:"content",children:[e.jsxs(Dn,{className:"w-full",children:[e.jsx(Xt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Xt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Xt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Xt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(as,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Published"}),e.jsx(br,{checked:S.is_published,onCheckedChange:F=>T($=>({...$,is_published:F}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(vn,{className:"h-16 w-16",children:[e.jsx(ga,{src:l||void 0}),e.jsx(bn,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ke,{value:v,onChange:F=>j(F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:D,disabled:b||v===s.slug,className:"shrink-0",children:b?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Theme"}),e.jsxs(zs,{value:S.theme,onValueChange:F=>T($=>({...$,theme:F})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(mt,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(mt,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(mt,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Title / Tagline"}),e.jsx(ke,{value:S.title,onChange:F=>T($=>({...$,title:F.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Positioning Statement"}),e.jsx(ke,{value:S.positioning_statement,onChange:F=>T($=>({...$,positioning_statement:F.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Bio"}),e.jsx(ur,{value:S.bio,onChange:F=>T($=>({...$,bio:F.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review Snippet"}),e.jsx(ke,{value:S.review_snippet,onChange:F=>T($=>({...$,review_snippet:F.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review Source URL"}),e.jsx(ke,{value:S.review_source_url,onChange:F=>T($=>({...$,review_source_url:F.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(ke,{value:S.booking_url,onChange:F=>T($=>({...$,booking_url:F.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Custom CTA Label (optional)"}),e.jsx(ke,{value:S.custom_cta_label,onChange:F=>T($=>({...$,custom_cta_label:F.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Custom CTA URL (optional)"}),e.jsx(ke,{value:S.custom_cta_url,onChange:F=>T($=>({...$,custom_cta_url:F.target.value})),placeholder:"https://example.com/landing"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ke,{value:S.brokerage_display_name,onChange:F=>T($=>({...$,brokerage_display_name:F.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!S.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[S.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:S.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${S.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>T(F=>({...F,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(oa,{className:"h-3.5 w-3.5"}),S.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>B(F,"brokerage_logo_url")})]})]}),S.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[S.brokerage_logo_size||56,"px"]})]}),e.jsx(Xy,{value:[S.brokerage_logo_size||56],onValueChange:([F])=>T($=>({...$,brokerage_logo_size:F})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ke,{value:S.team_name,onChange:F=>T($=>({...$,team_name:F.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!S.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[S.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:S.team_logo_url,alt:"Team logo",style:{height:`${S.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>T(F=>({...F,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(oa,{className:"h-3.5 w-3.5"}),S.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>B(F,"team_logo_url")})]})]}),S.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[S.team_logo_size||56,"px"]})]}),e.jsx(Xy,{value:[S.team_logo_size||56],onValueChange:([F])=>T($=>({...$,team_logo_size:F})),min:24,max:120,step:4})]})]})]})]}),e.jsx(as,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:F,label:$,hint:X})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(he,{children:$}),X&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[X," ",F==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(br,{checked:S[F],onCheckedChange:K=>T(Q=>({...Q,[F]:K}))})]},F))}),e.jsx(as,{value:"blocks",className:"mt-4",children:e.jsx(kxt,{cardId:s.id})}),e.jsx(as,{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(Ne,{children:e.jsxs(De,{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(Ne,{children:e.jsxs(De,{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(Ne,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(F=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:F.name}),F.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",F.phone]}),F.intent&&e.jsx(Ge,{variant:"secondary",className:"ml-2 text-xs",children:F.intent})]},F.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(G,{onClick:z,disabled:n.isPending,className:"w-full mt-4",children:n.isPending?"Saving...":"Save Changes"})]})}),e.jsx(TTe,{open:h,onClose:()=>m(!1),imageSrc:x,onCropComplete:P,aspectRatio:1})]})}const OM={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"},pMe={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 xMe(s=!0){return gt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=H.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 LLs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("marketplace_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category created successfully")},onError:t=>{ue.error("Failed to create category: "+t.message)}})}function DLs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("marketplace_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category updated successfully")},onError:t=>{ue.error("Failed to update category: "+t.message)}})}function RLs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("marketplace_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category deleted successfully")},onError:t=>{ue.error("Failed to delete category: "+t.message)}})}function $xt(s,t=!0){return gt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let r=H.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 OLs(s){return gt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:r}=await H.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 FLs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("marketplace_products").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ue.success("Product created successfully")},onError:t=>{ue.error("Failed to create product: "+t.message)}})}function BLs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("marketplace_products").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.id]}),ue.success("Product updated successfully")},onError:t=>{ue.error("Failed to update product: "+t.message)}})}function zLs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("marketplace_products").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ue.success("Product deleted successfully")},onError:t=>{ue.error("Failed to delete product: "+t.message)}})}function $Ls(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 ULs(){const s=es();return Lt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await H.from("marketplace_product_images").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Image deleted successfully")},onError:t=>{ue.error("Failed to delete image: "+t.message)}})}function qLs(){const s=es();return Lt({mutationFn:async({imageId:t,productId:r})=>{const{error:n}=await H.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:a}=await H.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Primary image updated")},onError:t=>{ue.error("Failed to set primary image: "+t.message)}})}function VLs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("marketplace_product_variants").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),ue.success("Variant added successfully")}})}function HLs(){const s=es();return Lt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await H.from("marketplace_product_variants").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Variant deleted successfully")}})}function GLs(){const s=es();return Lt({mutationFn:async({productId:t,videoUrl:r})=>{await H.from("marketplace_product_videos").delete().eq("product_id",t);const{data:n,error:a}=await H.from("marketplace_product_videos").insert({product_id:t,video_url:r}).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.productId]}),ue.success("Video updated successfully")}})}function WLs(s){const{isAdmin:t}=As();return gt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let r=H.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 H.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 KLs(){const{user:s}=As();return gt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await H.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 YLs(s){return gt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:r}=await H.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 ZLs(){const s=es(),{user:t}=As();return Lt({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 H.from("marketplace_orders").update(c).eq("id",r);if(d)throw d;const{error:h}=await H.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:a,created_by:t==null?void 0:t.id});if(h)throw h;if(["shipped","in_production","processing","completed"].includes(n)&&n!==o)try{await H.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:i,trackingUrl:l}})}catch(x){console.error("Failed to send notification email:",x)}},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Order status updated")},onError:r=>{ue.error("Failed to update order: "+r.message)}})}function XLs(){const s=es();return Lt({mutationFn:async({itemId:t,proofUrl:r,proofNotes:n,orderId:a})=>{const{error:i}=await H.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",t);if(i)throw i;await H.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await H.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Proof uploaded & customer notified")}})}function QLs(){const s=es();return Lt({mutationFn:async({itemId:t,orderId:r})=>{const{error:n}=await H.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Proof approved")}})}function JLs(){const s=es();return Lt({mutationFn:async({itemId:t,orderId:r,reason:n})=>{const{error:a}=await H.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Proof rejected - please upload a new proof")}})}function e6s(){const{data:s,isLoading:t}=xMe(!1),r=LLs(),n=DLs(),a=RLs(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),m=()=>{h({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},x=j=>{c(j),h({name:j.name,description:j.description||"",image_url:j.image_url||"",sort_order:j.sort_order,is_active:j.is_active}),l(!0)},g=async j=>{j.preventDefault(),o?await n.mutateAsync({id:o.id,...d}):await r.mutateAsync(d),l(!1),m()},v=async j=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(j)};return t?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(Vs,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(j=>e.jsx(Vs,{className:"h-12 w-full"},j))})})]}):e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Categories"}),e.jsxs(vs,{open:i,onOpenChange:j=>{l(j),j||m()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:g,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(ke,{id:"name",value:d.name,onChange:j=>h({...d,name:j.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",value:d.description,onChange:j=>h({...d,description:j.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"image_url",children:"Image URL"}),e.jsx(ke,{id:"image_url",value:d.image_url,onChange:j=>h({...d,image_url:j.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ke,{id:"sort_order",type:"number",value:d.sort_order,onChange:j=>h({...d,sort_order:parseInt(j.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"is_active",checked:d.is_active,onCheckedChange:j=>h({...d,is_active:j})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:r.isPending||n.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(De,{children:s&&s.length>0?e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Sort Order"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(j=>e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium",children:j.name}),e.jsx(ft,{className:"max-w-xs truncate",children:j.description}),e.jsx(ft,{children:j.sort_order}),e.jsx(ft,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${j.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:j.is_active?"Active":"Inactive"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(j),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(j.id),disabled:a.isPending,children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},j.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function t6s(){var oe,ge;const{data:s,isLoading:t}=$xt(void 0,!1),{data:r}=xMe(!1),n=FLs(),a=BLs(),i=zLs(),l=$Ls(),o=ULs(),c=qLs(),d=VLs(),h=HLs(),m=GLs(),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,P]=k.useState(null),[D,B]=k.useState(!1),[z,F]=k.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[$,X]=k.useState({name:"",price_adjustment:0}),[K,Q]=k.useState(""),Y=()=>{F({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),T(null)},ne=be=>{T(be),F({name:be.name,description:be.description||"",base_price:Number(be.base_price),shipping_fee:Number(be.shipping_fee),category_id:be.category_id||"",allow_artwork_upload:be.allow_artwork_upload,requires_proof_approval:be.requires_proof_approval,is_active:be.is_active,sort_order:be.sort_order}),g(!0)},de=async be=>{be.preventDefault();const Oe={...z,category_id:z.category_id||null};S?await a.mutateAsync({id:S.id,...Oe}):await n.mutateAsync(Oe),g(!1),Y()},ce=async be=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(be)},ae=async be=>{if(!A||!be.target.files||be.target.files.length===0)return;B(!0);const Oe=be.target.files[0],Me=Oe.name.split(".").pop(),Pe=`products/${A.id}/${Date.now()}.${Me}`;try{const{error:Ee}=await H.storage.from("marketplace").upload(Pe,Oe);if(Ee)throw Ee;const{data:{publicUrl:$e}}=H.storage.from("marketplace").getPublicUrl(Pe);await l.mutateAsync({product_id:A.id,image_url:$e,is_primary:!A.images||A.images.length===0}),ue.success("Image uploaded successfully")}catch(Ee){ue.error("Failed to upload image: "+Ee.message)}finally{B(!1)}},ie=async be=>{be.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:$.name,price_adjustment:$.price_adjustment}),X({name:"",price_adjustment:0}))},me=async()=>{!A||!K||(await m.mutateAsync({productId:A.id,videoUrl:K}),Q(""))};return t?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(Vs,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(be=>e.jsx(Vs,{className:"h-64 w-full"},be))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Products"}),e.jsxs(vs,{open:x,onOpenChange:be=>{g(be),be||Y()},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{children:[e.jsx(Ws,{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(js,{children:e.jsx(bs,{children:S?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:de,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Product Name"}),e.jsx(ke,{id:"name",value:z.name,onChange:be=>F({...z,name:be.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"category",children:"Category"}),e.jsxs(zs,{value:z.category_id,onValueChange:be=>F({...z,category_id:be}),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsx(Fs,{children:r==null?void 0:r.map(be=>e.jsx(mt,{value:be.id,children:be.name},be.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(ur,{id:"description",value:z.description,onChange:be=>F({...z,description:be.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(ke,{id:"base_price",type:"number",step:"0.01",min:"0",value:z.base_price,onChange:be=>F({...z,base_price:parseFloat(be.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(ke,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:z.shipping_fee,onChange:be=>F({...z,shipping_fee:parseFloat(be.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ke,{id:"sort_order",type:"number",value:z.sort_order,onChange:be=>F({...z,sort_order:parseInt(be.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"allow_artwork_upload",checked:z.allow_artwork_upload,onCheckedChange:be=>F({...z,allow_artwork_upload:be})}),e.jsx(he,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"requires_proof_approval",checked:z.requires_proof_approval,onCheckedChange:be=>F({...z,requires_proof_approval:be})}),e.jsx(he,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"is_active",checked:z.is_active,onCheckedChange:be=>F({...z,is_active:be})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:n.isPending||a.isPending,children:S?"Update Product":"Create Product"})]})]})]})]}),e.jsx(De,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(be=>{var Oe,Me;return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[be.images&&be.images.length>0?e.jsx("img",{src:((Oe=be.images.find(Pe=>Pe.is_primary))==null?void 0:Oe.image_url)||be.images[0].image_url,alt:be.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!be.is_active&&e.jsx(Ge,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:be.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Me=be.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(be.base_price).toFixed(2)]}),Number(be.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(be.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[be.allow_artwork_upload&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),be.requires_proof_approval&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Proof Required"}),be.variants&&be.variants.length>0&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:[be.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>ne(be),children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{P(be),j(!0)},children:[e.jsx($v,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{P(be),N(!0)},children:[e.jsx(Ah,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ce(be.id),children:e.jsx(yr,{className:"h-3 w-3 text-destructive"})})]})]})]},be.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(vs,{open:v,onOpenChange:j,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{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:(oe=A==null?void 0:A.images)==null?void 0:oe.map(be=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:be.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),be.is_primary&&e.jsx(Ge,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!be.is_primary&&e.jsx(G,{variant:"secondary",size:"icon",onClick:async()=>{var Oe;await c.mutateAsync({imageId:be.id,productId:A.id}),P({...A,images:(Oe=A.images)==null?void 0:Oe.map(Me=>({...Me,is_primary:Me.id===be.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Qn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"destructive",size:"icon",onClick:async()=>{var Me;await o.mutateAsync({id:be.id,productId:A.id});const Oe=s==null?void 0:s.find(Pe=>Pe.id===A.id);Oe&&P({...Oe,images:(Me=Oe.images)==null?void 0:Me.filter(Pe=>Pe.id!==be.id)})},disabled:o.isPending,children:e.jsx(yr,{className:"h-4 w-4"})})]})]},be.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ae,className:"hidden",id:"image-upload",disabled:D}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx($v,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(he,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(ke,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:K,onChange:be=>Q(be.target.value)}),e.jsxs(G,{onClick:me,disabled:!K,children:[e.jsx(sn,{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:N,children:e.jsxs(ys,{children:[e.jsx(js,{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:ie,className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Variant name (e.g., 500 count)",value:$.name,onChange:be=>X({...$,name:be.target.value}),required:!0}),e.jsx(ke,{type:"number",step:"0.01",placeholder:"Price adj.",value:$.price_adjustment,onChange:be=>X({...$,price_adjustment:parseFloat(be.target.value)||0}),className:"w-32"}),e.jsx(G,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ge=A==null?void 0:A.variants)==null?void 0:ge.map(be=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:be.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(be.price_adjustment)>=0?"+":"","$",Number(be.price_adjustment).toFixed(2)]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h.mutateAsync({id:be.id,productId:A.id}),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]},be.id)),(!(A!=null&&A.variants)||A.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const s6s=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function r6s(){var j,b,N;const{data:s,isLoading:t}=WLs(),r=ZLs(),n=XLs(),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[h,m]=k.useState(!1),x=S=>{i(S),d({status:S.status,notes:"",trackingNumber:S.tracking_number||"",trackingUrl:S.tracking_url||""}),o(!0)},g=async()=>{a&&(await r.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},v=async(S,T)=>{if(!a||!S.target.files||S.target.files.length===0)return;m(!0);const A=S.target.files[0],P=A.name.split(".").pop(),D=`proofs/${a.id}/${T}/${Date.now()}.${P}`;try{const{error:B}=await H.storage.from("marketplace").upload(D,A);if(B)throw B;const{data:{publicUrl:z}}=H.storage.from("marketplace").getPublicUrl(D);await n.mutateAsync({itemId:T,proofUrl:z,orderId:a.id}),ue.success("Proof uploaded successfully")}catch(B){ue.error("Failed to upload proof: "+B.message)}finally{m(!1)}};return t?e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(Vs,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(S=>e.jsx(Vs,{className:"h-16 w-full"},S))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Orders"})}),e.jsx(De,{children:s&&s.length>0?e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Order #"}),e.jsx(Tt,{children:"Customer"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Total"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:s.map(S=>{var T,A;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-mono",children:S.order_number}),e.jsx(ft,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((T=S.user)==null?void 0:T.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=S.user)==null?void 0:A.email})]})}),e.jsx(ft,{children:Ss(new Date(S.created_at),"MMM d, yyyy")}),e.jsxs(ft,{className:"font-bold",children:["$",Number(S.total).toFixed(2)]}),e.jsx(ft,{children:e.jsx(Ge,{className:pMe[S.status],children:OM[S.status]})}),e.jsx(ft,{className:"text-right",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>x(S),children:[e.jsx(jn,{className:"h-4 w-4 mr-1"}),"View"]})})]},S.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{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:(j=a.user)==null?void 0:j.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(b=a.user)==null?void 0:b.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(N=a.items)==null?void 0:N.map(S=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:S.product_name}),S.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(S.unit_price).toFixed(2)," x ",S.quantity]})]}),S.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:S.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(Ge,{variant:S.proof_status==="approved"?"default":"secondary",children:S.proof_status||"No proof yet"})]}),S.proof_url?e.jsx("a",{href:S.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:T=>v(T,S.id),className:"hidden",id:`proof-${S.id}`,disabled:h}),e.jsx("label",{htmlFor:`proof-${S.id}`,children:e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-4 w-4 mr-1"}),h?"Uploading...":"Upload Proof"]})})})]})]})})]},S.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Status"}),e.jsxs(zs,{value:c.status,onValueChange:S=>d({...c,status:S}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:s6s.map(S=>e.jsx(mt,{value:S,children:OM[S]},S))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Tracking Number"}),e.jsx(ke,{value:c.trackingNumber,onChange:S=>d({...c,trackingNumber:S.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Tracking URL"}),e.jsx(ke,{value:c.trackingUrl,onChange:S=>d({...c,trackingUrl:S.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes (optional)"}),e.jsx(ur,{value:c.notes,onChange:S=>d({...c,notes:S.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(G,{onClick:g,disabled:r.isPending,className:"w-full",children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(S=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Ge,{variant:"outline",children:OM[S.status]}),S.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:S.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Ss(new Date(S.created_at),"MMM d, h:mm a")})]},S.id))})]})]})]})})]})}function n6s(){const[s,t]=k.useState("products"),r=vr();return e.jsx(_s,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(G,{variant:"outline",onClick:()=>r("/marketplace"),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(Rn,{value:s,onValueChange:t,children:[e.jsxs(Dn,{className:"grid w-full grid-cols-3",children:[e.jsxs(Xt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Xt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(im,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Xt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(lp,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(as,{value:"products",children:e.jsx(t6s,{})}),e.jsx(as,{value:"categories",children:e.jsx(e6s,{})}),e.jsx(as,{value:"orders",children:e.jsx(r6s,{})})]})]})})}function Uxt(){return gt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await H.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function a6s(s){return gt({queryKey:["reward-items",s],queryFn:async()=>{let t=H.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 i6s(s){return gt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=H.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 o6s(s){return gt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 l6s(){return gt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await H.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 H.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 c6s(s){return gt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:r}=await H.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 d6s(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 u6s(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("reward_store_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function h6s(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("reward_store_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function m6s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("reward_store_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function f6s(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 p6s(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 x6s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 g6s(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function P_e(s,t){const r=g6s(s);if(r)try{const{data:n,error:a}=await H.storage.from(r.bucket).download(r.path);if(a){console.error("Error downloading file:",a),ue.error("Failed to download file");return}const i=URL.createObjectURL(n),l=document.createElement("a");l.href=i,l.download=t||r.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("Download error:",n),ue.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("External download error:",n),ue.error("Failed to download file")}}function qxt(){return gt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await H.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function y6s(){const s=es();return Lt({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 H.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 v6s(){const{user:s}=As(),[t,r]=k.useState("items"),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(null),[j,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(""),[P,D]=k.useState(""),[B,z]=k.useState(null),[F,$]=k.useState(""),[X,K]=k.useState("file"),[Q,Y]=k.useState(""),[ne,de]=k.useState(""),[ce,ae]=k.useState(""),[ie,me]=k.useState(!0),[oe,ge]=k.useState(null),[be,Oe]=k.useState(!1),[Me,Pe]=k.useState(!1),Ee=k.useRef(null),$e=k.useRef(null),{data:Se,isLoading:ze}=Uxt(),{data:Te,isLoading:ye}=a6s(),{data:ct,isLoading:ve}=l6s(),{data:rt,isLoading:Re}=qxt(),Qe=u6s(),Ke=h6s(),Ce=m6s(),nt=f6s(),$t=p6s(),lt=x6s(),it=y6s(),[Nt,Ft]=k.useState({}),at=yt=>{yt?(l(yt),c(yt.name),h(yt.description||""),x(yt.icon||"")):(l(null),c(""),h(""),x("")),a(!0)},Ie=async()=>{if(!o.trim()){ue.error("Please enter a category name");return}try{i?(await Ke.mutateAsync({id:i.id,name:o,description:d||null,icon:m||null}),ue.success("Category updated successfully")):(await Qe.mutateAsync({name:o,description:d||null,icon:m||null,sort_order:((Se==null?void 0:Se.length)||0)+1}),ue.success("Category created successfully")),a(!1)}catch(yt){console.error("Error saving category:",yt),ue.error("Failed to save category")}},et=async()=>{if(g)try{await Ce.mutateAsync(g),ue.success("Category deleted successfully"),v(null)}catch(yt){console.error("Error deleting category:",yt),ue.error("Failed to delete category")}},Dt=yt=>{var ss;yt?(S(yt),A(yt.name),D(yt.description||""),z(yt.category_id),$(yt.points_cost.toString()),K(yt.item_type),Y(yt.file_url||""),de(yt.preview_image_url||""),ae(((ss=yt.max_quantity)==null?void 0:ss.toString())||""),me(yt.is_active)):(S(null),A(""),D(""),z(null),$(""),K("file"),Y(""),de(""),ae(""),me(!0)),b(!0)},Jt=async(yt,ss)=>{ss==="file"?Oe(!0):Pe(!0);try{const Is=yt.name.split(".").pop(),fs=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Is}`,ar=`${ss==="file"?"items":"previews"}/${fs}`,{error:Er}=await H.storage.from("reward-store").upload(ar,yt);if(Er)throw Er;const{data:{publicUrl:Tr}}=H.storage.from("reward-store").getPublicUrl(ar);ss==="file"?Y(Tr):de(Tr),ue.success("File uploaded successfully")}catch(Is){console.error("Error uploading file:",Is),ue.error("Failed to upload file")}finally{ss==="file"?Oe(!1):Pe(!1)}},cs=async()=>{if(!T.trim()){ue.error("Please enter an item name");return}if(!F||parseInt(F)<0){ue.error("Please enter a valid points cost");return}try{const yt={name:T,description:P||null,category_id:B,points_cost:parseInt(F),item_type:X,file_url:Q||null,preview_image_url:ne||null,max_quantity:ce?parseInt(ce):null,current_quantity:ce?parseInt(ce):null,is_active:ie,created_by:s==null?void 0:s.id};N?(await $t.mutateAsync({id:N.id,...yt,current_quantity:N.max_quantity!==(ce?parseInt(ce):null)?ce?parseInt(ce):null:N.current_quantity}),ue.success("Item updated successfully")):(await nt.mutateAsync(yt),ue.success("Item created successfully")),b(!1)}catch(yt){console.error("Error saving item:",yt),ue.error("Failed to save item")}},Ht=async()=>{if(oe)try{await lt.mutateAsync(oe),ue.success("Item deleted successfully"),ge(null)}catch(yt){console.error("Error deleting item:",yt),ue.error("Failed to delete item")}},dt=async(yt,ss)=>{const Is=Nt[yt];if(Is===void 0||Is===ss.toString())return;const fs=parseInt(Is);if(isNaN(fs)||fs<0){ue.error("Please enter a valid positive number");return}try{await it.mutateAsync({id:yt,points:fs}),ue.success("Points updated successfully"),Ft(ar=>{const Er={...ar};return delete Er[yt],Er})}catch(ar){console.error("Error updating points:",ar),ue.error("Failed to update points")}};return ze||ye||ve||Re?e.jsx(_s,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{className:"h-8 w-64"}),e.jsx(Vs,{className:"h-96"})]})}):e.jsxs(_s,{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(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Te==null?void 0:Te.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Te==null?void 0:Te.filter(yt=>yt.is_active).length)||0," active"]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(im,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Se==null?void 0:Se.length)||0})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Qn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg. Cost"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[Te&&Te.length>0?Math.round(Te.reduce((yt,ss)=>yt+ss.points_cost,0)/Te.length):0," pts"]})]})})]}),e.jsxs(Rn,{value:t,onValueChange:r,children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"items",children:"Items"}),e.jsx(Xt,{value:"categories",children:"Categories"}),e.jsx(Xt,{value:"purchases",children:"Purchases"}),e.jsx(Xt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(as,{value:"items",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Store Items"}),e.jsx(Nr,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(G,{onClick:()=>Dt(),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(De,{children:!Te||Te.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(li,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{className:"text-center",children:"Cost"}),e.jsx(Tt,{className:"text-center",children:"Type"}),e.jsx(Tt,{className:"text-center",children:"Quantity"}),e.jsx(Tt,{className:"text-center",children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:Te.map(yt=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[yt.preview_image_url?e.jsx("img",{src:yt.preview_image_url,alt:yt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(li,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:yt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:yt.description||"No description"})]})]})}),e.jsx(ft,{children:yt.category?e.jsx(Ge,{variant:"outline",children:yt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),yt.points_cost]})}),e.jsx(ft,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[yt.item_type==="file"?e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(xo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:yt.item_type})]})}),e.jsx(ft,{className:"text-center",children:yt.max_quantity!==null?e.jsxs("span",{className:yt.current_quantity===0?"text-red-500":"",children:[yt.current_quantity,"/",yt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(ft,{className:"text-center",children:e.jsx(Ge,{variant:yt.is_active?"default":"secondary",children:yt.is_active?"Active":"Inactive"})}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Dt(yt),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ge(yt.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},yt.id))})]})})]})}),e.jsx(as,{value:"categories",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Categories"}),e.jsx(Nr,{children:"Organize your store items into categories"})]}),e.jsxs(G,{onClick:()=>at(),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(De,{children:!Se||Se.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(im,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center",children:"Items"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Bn,{children:Se.map(yt=>e.jsxs(qs,{children:[e.jsxs(ft,{className:"font-medium",children:[yt.icon&&e.jsx("span",{className:"mr-2",children:yt.icon}),yt.name]}),e.jsx(ft,{className:"text-muted-foreground",children:yt.description||"—"}),e.jsx(ft,{className:"text-center",children:(Te==null?void 0:Te.filter(ss=>ss.category_id===yt.id).length)||0}),e.jsx(ft,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>at(yt),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>v(yt.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},yt.id))})]})})]})}),e.jsx(as,{value:"purchases",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(lp,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Nr,{children:"View all reward redemptions by agents"})]}),e.jsx(De,{children:!ct||ct.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(lp,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(Bn,{children:ct.map(yt=>{var ss,Is,fs,ar;return e.jsxs(qs,{children:[e.jsx(ft,{className:"text-muted-foreground",children:Ss(new Date(yt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(ft,{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(Bi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ss=yt.user)==null?void 0:ss.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Is=yt.user)==null?void 0:Is.email)||"—"})]})]})}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(fs=yt.item)!=null&&fs.preview_image_url?e.jsx("img",{src:yt.item.preview_image_url,alt:yt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((ar=yt.item)==null?void 0:ar.name)||"Deleted item"})]})}),e.jsx(ft,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),yt.points_spent]})})]},yt.id)})})]})})]})})]})]}),e.jsx(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:i?"Edit Category":"Add Category"}),e.jsx(Fr,{children:i?"Update the category details":"Create a new category for your store items"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"categoryName",children:"Name"}),e.jsx(ke,{id:"categoryName",value:o,onChange:yt=>c(yt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(ur,{id:"categoryDescription",value:d,onChange:yt=>h(yt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(ke,{id:"categoryIcon",value:m,onChange:yt=>x(yt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{onClick:Ie,disabled:Qe.isPending||Ke.isPending,children:Qe.isPending||Ke.isPending?"Saving...":"Save"})]})]})}),e.jsx(vs,{open:j,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(bs,{children:N?"Edit Item":"Add Item"}),e.jsx(Fr,{children:N?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemName",children:"Name *"}),e.jsx(ke,{id:"itemName",value:T,onChange:yt=>A(yt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemDescription",children:"Description"}),e.jsx(ur,{id:"itemDescription",value:P,onChange:yt=>D(yt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(zs,{value:B||"none",onValueChange:yt=>z(yt==="none"?null:yt),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select category"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No category"}),Se==null?void 0:Se.map(yt=>e.jsxs(mt,{value:yt.id,children:[yt.icon&&`${yt.icon} `,yt.name]},yt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(ke,{id:"itemPointsCost",type:"number",min:"0",value:F,onChange:yt=>$(yt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemType",children:"Type"}),e.jsxs(zs,{value:X,onValueChange:K,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"file",children:"File Download"}),e.jsx(mt,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(ke,{id:"itemMaxQuantity",type:"number",min:"1",value:ce,onChange:yt=>ae(yt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:Q,onChange:yt=>Y(yt.target.value),placeholder:X==="file"?"Upload a file or paste URL":"Paste external link"}),X==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>{var yt;return(yt=Ee.current)==null?void 0:yt.click()},disabled:be,children:e.jsx(oa,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",className:"hidden",onChange:yt=>{var Is;const ss=(Is=yt.target.files)==null?void 0:Is[0];ss&&Jt(ss,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:ne,onChange:yt=>de(yt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>{var yt;return(yt=$e.current)==null?void 0:yt.click()},disabled:Me,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("input",{ref:$e,type:"file",accept:"image/*",className:"hidden",onChange:yt=>{var Is;const ss=(Is=yt.target.files)==null?void 0:Is[0];ss&&Jt(ss,"preview")}})]}),ne&&e.jsx("img",{src:ne,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{id:"itemIsActive",checked:ie,onCheckedChange:me}),e.jsx(he,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(G,{onClick:cs,disabled:nt.isPending||$t.isPending,children:nt.isPending||$t.isPending?"Saving...":"Save"})]})]})}),e.jsx(Yo,{open:!!g,onOpenChange:()=>v(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Category"}),e.jsx(Uo,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:et,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Yo,{open:!!oe,onOpenChange:()=>ge(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Item"}),e.jsx(Uo,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:Ht,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(Ne,{className:"mt-4",children:[e.jsx(Ot,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lo,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(zt,{children:"Point Reward Settings"}),e.jsx(Nr,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(De,{children:!rt||rt.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(lo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center w-32",children:"Points"}),e.jsx(Tt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(Bn,{children:rt.map(yt=>e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsx("p",{className:"font-medium",children:yt.action_name})}),e.jsx(ft,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:yt.description})}),e.jsx(ft,{className:"text-center",children:e.jsx(ke,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Nt[yt.id]??yt.points.toString(),onChange:ss=>Ft(Is=>({...Is,[yt.id]:ss.target.value}))})}),e.jsx(ft,{className:"text-right",children:e.jsx(G,{size:"sm",variant:"outline",disabled:Nt[yt.id]===void 0||Nt[yt.id]===yt.points.toString()||it.isPending,onClick:()=>dt(yt.id,yt.points),children:e.jsx(ql,{className:"h-4 w-4"})})})]},yt.id))})]})})]})]})}const QVe=()=>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"})]}),JVe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function b6s(){const s=es(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:h}=gt({queryKey:["canva-integration"],queryFn:async()=>{const{data:S,error:T}=await H.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(T)throw T;return S}}),{data:m}=gt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:S,error:T}=await H.from("brokerages").select("id, name").order("name");if(T)throw T;return S}}),{data:x}=gt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:S,error:T}=await H.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(T)throw T;return S}}),g=async()=>{var S;r(!0);try{const{data:T}=await H.auth.getSession(),A=(S=T==null?void 0:T.session)==null?void 0:S.access_token;if(!A)throw new Error("Not authenticated");const B=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"})}),z=await B.json();if(!B.ok||z!=null&&z.error)throw new Error((z==null?void 0:z.error)||"Failed to get authorization URL");if(z!=null&&z.authUrl){localStorage.setItem("canva_code_verifier",z.codeVerifier),localStorage.setItem("canva_oauth_state",z.state);const F=window.open(z.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!F){ue.error("Popup was blocked. Please allow popups for this site and try again."),r(!1);return}const $=K=>{var Q,Y;K.origin===window.location.origin&&(((Q=K.data)==null?void 0:Q.type)==="canva-oauth-success"?(window.removeEventListener("message",$),ue.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1)):((Y=K.data)==null?void 0:Y.type)==="canva-oauth-error"&&(window.removeEventListener("message",$),ue.error("Canva connection failed: "+(K.data.error||"Unknown error")),r(!1)))};window.addEventListener("message",$);const X=setInterval(()=>{F.closed&&(clearInterval(X),window.removeEventListener("message",$),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(T){console.error("Canva connect error:",T);const A=(T==null?void 0:T.message)||"";A.includes("CANVA_CLIENT_ID")?ue.error("Canva app credentials not configured yet."):ue.error(A||"Failed to start Canva connection"),r(!1)}},v=Lt({mutationFn:async S=>{var F;const{data:T}=await H.auth.getSession(),A=(F=T==null?void 0:T.session)==null?void 0:F.access_token;if(!A)throw new Error("Not authenticated");const B=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:S})}),z=await B.json();if(!B.ok||z!=null&&z.error)throw new Error((z==null?void 0:z.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ue.success("Canva disconnected")},onError:S=>{ue.error(S.message||"Failed to disconnect Canva")}}),j=Lt({mutationFn:async S=>{const{error:T}=await H.from("canva_brokerage_folders").insert({brokerage_id:S.brokerage_id,folder_id:S.folder_id.trim(),folder_name:S.folder_name.trim(),folder_type:S.folder_type,description:S.description.trim()||null,sort_order:(x==null?void 0:x.length)||0});if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ue.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ue.error("Failed to add folder")}),b=Lt({mutationFn:async S=>{const{error:T}=await H.from("canva_brokerage_folders").delete().eq("id",S);if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ue.success("Folder removed")},onError:()=>ue.error("Failed to remove folder")}),N=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ot,{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(QVe,{})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",N&&e.jsx(Ge,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Nr,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(De,{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(mi,{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(mi,{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(mi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),N?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Canva?"}),e.jsx(Uo,{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(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>v.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!n),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(im,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",x&&x.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:x.length})]}),n?e.jsx(xp,{className:"h-4 w-4"}):e.jsx(so,{className:"h-4 w-4"})]}),n&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[x&&x.length>0?x.map(S=>{var T,A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:S.folder_name}),e.jsx(Ge,{variant:"outline",className:"text-xs shrink-0",children:((T=JVe.find(P=>P.value===S.folder_type))==null?void 0:T.label)||S.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=S.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:S.folder_id})]})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>b.mutate(S.id),children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]},S.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Ws,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(G,{className:"mt-4",onClick:g,disabled:t||h,children:[t?e.jsx(Di,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(QVe,{})}),"Connect Canva",e.jsx(Ga,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(js,{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(he,{children:"Brokerage"}),e.jsxs(zs,{value:o.brokerage_id,onValueChange:S=>c(T=>({...T,brokerage_id:S})),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a brokerage…"})}),e.jsx(Fs,{children:m==null?void 0:m.map(S=>e.jsx(mt,{value:S.id,children:S.name},S.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Canva Folder ID"}),e.jsx(ke,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:S=>c(T=>({...T,folder_id:S.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Folder Display Name"}),e.jsx(ke,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:S=>c(T=>({...T,folder_name:S.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Folder Type"}),e.jsxs(zs,{value:o.folder_type,onValueChange:S=>c(T=>({...T,folder_type:S})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:JVe.map(S=>e.jsx(mt,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(ke,{placeholder:"What's in this folder?",value:o.description,onChange:S=>c(T=>({...T,description:S.target.value}))})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>j.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||j.isPending,children:[j.isPending?e.jsx(Di,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function _6s(){const s=vr();return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(rh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(Ne,{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(Pc,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs(G,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(Ga,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(b6s,{}),e.jsx(Oxt,{})]})})}const eHe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(ku,{className:t}):s==="instagram"?e.jsx(au,{className:t}):s==="linkedin"?e.jsx(om,{className:t}):s==="google"?e.jsx(Qs,{className:t}):null},w6s=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function j6s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all");k.useEffect(()=>{(async()=>{n(!0);const{data:x,error:g}=await H.rpc("admin_get_social_connections");if(g){ue.error(g.message),n(!1);return}t(x||[]),n(!1)})()},[]);const c=k.useMemo(()=>{const x=a.trim().toLowerCase();return s.filter(g=>l!=="all"&&g.platform!==l?!1:x?(g.user_name||"").toLowerCase().includes(x)||(g.user_email||"").toLowerCase().includes(x)||(g.page_name||"").toLowerCase().includes(x)||(g.platform_username||"").toLowerCase().includes(x):!0)},[s,a,l]),d=k.useMemo(()=>{const x=new Map;return s.forEach(g=>{const v=x.get(g.user_id)||{name:g.user_name,email:g.user_email,platforms:new Set,count:0};v.platforms.add(g.platform),v.count+=1,x.set(g.user_id,v)}),Array.from(x.entries()).map(([g,v])=>({user_id:g,...v}))},[s]),h=k.useMemo(()=>{const x=new Map;return s.forEach(g=>x.set(g.platform,(x.get(g.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(x.entries())}},[s,d]),m=x=>x&&new Date(x).getTime()e.jsxs(Ne,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[eHe(x)," ",x]}),e.jsx("div",{className:"text-2xl font-bold",children:g})]},x))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(ke,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:x=>i(x.target.value),className:"md:max-w-md"}),e.jsxs(zs,{value:l,onValueChange:o,children:[e.jsx(Os,{className:"md:w-48",children:e.jsx(Us,{placeholder:"All platforms"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All platforms"}),e.jsx(mt,{value:"facebook",children:"Facebook"}),e.jsx(mt,{value:"instagram",children:"Instagram"}),e.jsx(mt,{value:"linkedin",children:"LinkedIn"}),e.jsx(mt,{value:"google",children:"Google"})]})]})]}),e.jsx(Ne,{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(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Platform"}),e.jsx(Tt,{children:"Page / Account"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Connected"})]})}),e.jsx(Bn,{children:c.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(x=>{const g=m(x.token_expires_at);return e.jsxs(qs,{children:[e.jsxs(ft,{children:[e.jsx("div",{className:"font-medium",children:x.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.user_email})]}),e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[eHe(x.platform)," ",x.platform]})}),e.jsxs(ft,{children:[e.jsx("div",{className:"font-medium",children:x.page_name||x.platform_username||"—"}),x.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",x.instagram_business_id]})]}),e.jsx(ft,{children:x.is_active?g?e.jsxs(Ge,{variant:"destructive",className:"gap-1",children:[e.jsx(Hi,{className:"h-3 w-3"})," Expired"]}):e.jsx(Ge,{children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Inactive"})}),e.jsx(ft,{className:"text-sm text-muted-foreground",children:w6s(x.created_at)})]},x.id)})})]})})]})})}const N6s={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 oR(s,t=18,r=10){return s.length<=t+r+3?s:`${s.slice(0,t)}…${s.slice(-r)}`}function k6s(){var X,K,Q,Y,ne;const s=es(),[t,r]=k.useState("Test Push"),[n,a]=k.useState("Testing web push notification"),[i,l]=k.useState("/community"),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[g,v]=k.useState(null),[j,b]=k.useState(null),{data:N,isLoading:S}=gt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:de,error:ce}=await H.from("push_notification_settings").select("*").order("setting_key");if(ce)throw ce;return de}}),{data:T,isLoading:A}=gt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:de,error:ce}=await H.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ce)throw ce;return{totalSubscriptions:de||0}}}),P=Lt({mutationFn:async({settingKey:de,isEnabled:ce})=>{const{error:ae}=await H.from("push_notification_settings").update({is_enabled:ce}).eq("setting_key",de);if(ae)throw ae},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ue.success("Notification setting updated")},onError:de=>{ue.error("Failed to update setting: "+de.message)}}),D=k.useMemo(()=>{var de,ce;return m.isSupported?`perm=${m.permission??"unknown"} · controller=${m.controllerPresent?"yes":"no"} · sw=${((de=m.serviceWorker)==null?void 0:de.activeState)??"unknown"} · sub=${(ce=m.subscription)!=null&&ce.endpoint?"yes":"no"}`:"Push not supported in this browser."},[m]);k.useEffect(()=>{let de=!0;const ce=async()=>{var oe,ge,be,Oe,Me,Pe,Ee;const ie="serviceWorker"in navigator&&"PushManager"in window,me={isSupported:ie,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((oe=navigator.serviceWorker)!=null&&oe.controller)};if(!ie){de&&x(me);return}try{const{data:$e,error:Se}=await H.functions.invoke("get-vapid-public-key",{body:{}});if(Se)throw Se;me.vapidPublicKey=$e==null?void 0:$e.vapidPublicKey;const Te=(await navigator.serviceWorker.getRegistrations()).find(ye=>{var ve,rt,Re;return(((ve=ye.active)==null?void 0:ve.scriptURL)||((rt=ye.waiting)==null?void 0:rt.scriptURL)||((Re=ye.installing)==null?void 0:Re.scriptURL)||"").includes("/sw.js")});if(Te){me.pushWorkerScriptUrl=((ge=Te.active)==null?void 0:ge.scriptURL)||((be=Te.waiting)==null?void 0:be.scriptURL)||((Oe=Te.installing)==null?void 0:Oe.scriptURL),me.serviceWorker={scope:Te.scope,activeState:(Me=Te.active)==null?void 0:Me.state};const ye=await Te.pushManager.getSubscription();if(ye){const ct=ye.toJSON();me.subscription={endpoint:ct.endpoint,p256dh:(Pe=ct.keys)==null?void 0:Pe.p256dh,auth:(Ee=ct.keys)==null?void 0:Ee.auth}}}}catch($e){me.error=($e==null?void 0:$e.message)||String($e)}de&&x(me)};ce();const ae=window.setInterval(ce,4e3);return()=>{de=!1,window.clearInterval(ae)}},[]);const B=async()=>{if(typeof Notification>"u"){ue.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ue.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ue.success("Triggered a local notification (not push).")}catch(de){ue.error(`Local notification failed: ${(de==null?void 0:de.message)||String(de)}`)}},z=async()=>{c(!0),v(null);try{const{data:de,error:ce}=await H.functions.invoke("send-push-notification",{body:{title:t,body:n,url:i}});if(ce)throw ce;v({sent:de==null?void 0:de.sent,failed:de==null?void 0:de.failed,expiredCleaned:de==null?void 0:de.expiredCleaned,vapidPublicKey:de==null?void 0:de.vapidPublicKey}),(de==null?void 0:de.sent)>0?ue.success(`Test notification sent to ${de.sent} subscriber(s)`):(de==null?void 0:de.failed)>0?ue.warning(`Notification failed for ${de.failed} subscriber(s). ${de.expired||0} expired subscriptions cleaned up.`):ue.info("No active subscriptions to send to")}catch(de){console.error("Error sending test notification:",de),v({error:(de==null?void 0:de.message)||String(de)}),ue.error("Failed to send test notification: "+(de.message||"Unknown error"))}finally{c(!1)}},F=async()=>{h(!0),b(null);try{const{data:de,error:ce}=await H.functions.invoke("generate-vapid-keys",{body:{}});if(ce)throw ce;const ae=de==null?void 0:de.publicKey,ie=de==null?void 0:de.privateKey;if(!ae||!ie)throw new Error("generate-vapid-keys did not return keys");b({publicKey:ae,privateKey:ie}),ue.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(de){console.error("Error generating VAPID keys:",de),ue.error("Failed to generate VAPID keys: "+((de==null?void 0:de.message)||"Unknown error"))}finally{h(!1)}},$=Lt({mutationFn:async()=>{const{error:de}=await H.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(de)throw de},onSuccess:()=>{ue.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:de=>{ue.error("Failed to clear subscriptions: "+de.message)}});return e.jsx(_s,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Nr,{children:"Current active push notification subscriptions"})]}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(T==null?void 0:T.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(lo,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Nr,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(De,{children:S?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:N==null?void 0:N.map(de=>{const ce=N6s[de.setting_key]||{label:de.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:ce.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ce.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:de.description})]})]}),e.jsx(br,{checked:de.is_enabled,onCheckedChange:ae=>P.mutate({settingKey:de.setting_key,isEnabled:ae}),disabled:P.isPending})]},de.id)})})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Rm,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Nr,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(De,{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?oR(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: ",(X=m.serviceWorker)!=null&&X.scope?oR(m.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((K=m.serviceWorker)==null?void 0:K.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(Q=m.subscription)!=null&&Q.endpoint?oR(m.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(Y=m.subscription)!=null&&Y.p256dh?oR(m.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(ne=m.subscription)!=null&&ne.auth?oR(m.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(G,{variant:"outline",onClick:B,children:"Local notification test"}),e.jsx(G,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(ke,{id:"test-title",value:t,onChange:de=>r(de.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(ur,{id:"test-body",value:n,onChange:de=>a(de.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(ke,{id:"test-url",value:i,onChange:de=>l(de.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(G,{onClick:z,disabled:o||!t||!n,className:"w-full sm:w-auto",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),g&&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"}),g.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",g.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",g.sent??0," sent, ",g.failed??0," failed, ",g.expiredCleaned??0," expired cleaned"]}),g.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:g.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(yr,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Nr,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(G,{variant:"destructive",onClick:()=>$.mutate(),disabled:$.isPending,children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),$.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(G,{variant:"outline",onClick:F,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),j&&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:j.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:j.privateKey})]})]})]})]})]})]})})}function S6s(){const{toast:s}=Ea(),[t,r]=k.useState([]),[n,a]=k.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=k.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=mz("presentation_count","desc"),m=h(t,{name:v=>{var j;return((j=v.name)==null?void 0:j.toLowerCase())||""},presentations:v=>v.presentation_count,views:v=>v.total_views,leads:v=>v.total_leads,cta_clicks:v=>v.total_cta_clicks,conversion:v=>v.total_views>0?v.total_leads/v.total_views*100:0});k.useEffect(()=>{x()},[]);const x=async()=>{try{l(!0);const{data:v,error:j}=await H.rpc("get_admin_presentation_stats");if(j)throw j;if(!v||v.length===0){l(!1);return}const b=v.map(P=>P.owner_user_id),{data:N,error:S}=await H.from("profiles").select("id, name, email, avatar_url").in("id",b);if(S)throw S;const T=new Map((N==null?void 0:N.map(P=>[P.id,P]))||[]),A=v.map(P=>{const D=T.get(P.owner_user_id);return{owner_user_id:P.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(P.presentation_count),total_views:Number(P.total_views),total_leads:Number(P.total_leads),total_cta_clicks:Number(P.total_cta_clicks)}});r(A),r(A),a({totalPresentations:A.reduce((P,D)=>P+D.presentation_count,0),totalViews:A.reduce((P,D)=>P+D.total_views,0),totalLeads:A.reduce((P,D)=>P+D.total_leads,0),totalCtaClicks:A.reduce((P,D)=>P+D.total_cta_clicks,0),agentsUsing:A.length})}catch(v){console.error("Error loading presentation stats:",v),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},g=[{label:"Agents Using",value:n.agentsUsing,icon:fr,color:"text-blue-600"},{label:"Total Presentations",value:n.totalPresentations,icon:n0,color:"text-violet-600"},{label:"Total Views",value:n.totalViews,icon:jn,color:"text-emerald-600"},{label:"Total Leads",value:n.totalLeads,icon:nl,color:"text-amber-600"},{label:"CTA Clicks",value:n.totalCtaClicks,icon:Dd,color:"text-rose-600"}];return e.jsx(_s,{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:g.map(v=>e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:v.label}),e.jsx(v.icon,{className:`h-4 w-4 ${v.color}`})]}),e.jsx(De,{children:i?e.jsx(Vs,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:v.value.toLocaleString()})})]},v.label))}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((v,j)=>e.jsx(Vs,{className:"h-12 w-full"},j))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Al,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Al,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Al,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Al,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Al,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Al,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(Bn,{children:m.map(v=>{var b,N;const j=v.total_views>0?(v.total_leads/v.total_views*100).toFixed(1):"0.0";return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((N=(b=v.name)==null?void 0:b.charAt(0))==null?void 0:N.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.email})]})]})}),e.jsx(ft,{className:"text-center font-medium",children:v.presentation_count}),e.jsx(ft,{className:"text-center",children:v.total_views.toLocaleString()}),e.jsx(ft,{className:"text-center",children:v.total_leads>0?e.jsx(Ge,{variant:"secondary",children:v.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ft,{className:"text-center",children:v.total_cta_clicks}),e.jsx(ft,{className:"text-center",children:e.jsxs("span",{className:Number(j)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[j,"%"]})})]},v.owner_user_id)})})]})})]})]})})}function C6s(){const{toast:s}=Ea(),[t,r]=k.useState([]),[n,a]=k.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=k.useState(!0);k.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:h}=await H.rpc("get_admin_guest_book_stats");if(h)throw h;if(!d||d.length===0){l(!1);return}const m=d.map(b=>b.agent_id),{data:x,error:g}=await H.from("profiles").select("id, name, email, avatar_url").in("id",m);if(g)throw g;const v=new Map((x==null?void 0:x.map(b=>[b.id,b]))||[]),j=d.map(b=>{const N=v.get(b.agent_id);return{agent_id:b.agent_id,name:(N==null?void 0:N.name)||"Unknown",email:(N==null?void 0:N.email)||"",avatar_url:(N==null?void 0:N.avatar_url)||null,open_house_count:Number(b.open_house_count),total_visitors:Number(b.total_visitors),total_leads:Number(b.total_leads),active_count:Number(b.active_count)}});j.sort((b,N)=>N.total_visitors-b.total_visitors),r(j),a({totalOpenHouses:j.reduce((b,N)=>b+N.open_house_count,0),totalVisitors:j.reduce((b,N)=>b+N.total_visitors,0),totalLeads:j.reduce((b,N)=>b+N.total_leads,0),activeOpenHouses:j.reduce((b,N)=>b+N.active_count,0),agentsUsing:j.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:fr,color:"text-blue-600"},{label:"Total Open Houses",value:n.totalOpenHouses,icon:Cn,color:"text-violet-600"},{label:"Active Now",value:n.activeOpenHouses,icon:mi,color:"text-emerald-600"},{label:"Total Visitors",value:n.totalVisitors,icon:jn,color:"text-amber-600"},{label:"Leads Created",value:n.totalLeads,icon:nl,color:"text-rose-600"}];return e.jsx(_s,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(zt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(De,{children:i?e.jsx(Vs,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,h)=>e.jsx(Vs,{className:"h-12 w-full"},h))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Open Houses"}),e.jsx(Tt,{className:"text-center",children:"Active"}),e.jsx(Tt,{className:"text-center",children:"Visitors"}),e.jsx(Tt,{className:"text-center",children:"Leads"}),e.jsx(Tt,{className:"text-center",children:"Conversion"})]})}),e.jsx(Bn,{children:t.map(d=>{var m,x;const h=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(qs,{children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((x=(m=d.name)==null?void 0:m.charAt(0))==null?void 0:x.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(ft,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(ft,{className:"text-center",children:d.active_count>0?e.jsx(Ge,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ft,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(ft,{className:"text-center",children:d.total_leads>0?e.jsx(Ge,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ft,{className:"text-center",children:e.jsxs("span",{className:Number(h)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[h,"%"]})})]},d.agent_id)})})]})})]})]})})}function T6s(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing connection...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Failed to connect: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("Failed to connect: No authorization code");return}try{const{data:m,error:x}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(x){let g=x.message||"Failed to connect accounts";try{const v=x.context;if(v&&typeof v.json=="function"){const j=await v.json();j!=null&&j.error&&(g=j.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)n("success"),i(m.message||"Accounts connected successfully!"),ue.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),n("error"),i(m.message||"Failed to complete connection"),ue.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{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(mi,{className:"h-12 w-12 text-green-500"}),r==="error"&&e.jsx(Mc,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(zt,{children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/admin/integrations"),children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function E6s(){const s=es(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),o=k.useRef(null),{data:c,isLoading:d}=gt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:N}=await H.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(N)throw N;return b}}),h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=Lt({mutationFn:async b=>{const{data:N,error:S}=await H.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return N},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ue.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),r(""),a(""),l([])},onError:b=>{ue.error("Failed to send: "+b.message)}}),x=Lt({mutationFn:async()=>{var T,A;const{data:{user:b}}=await H.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:N,error:S}=await H.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(A=(T=b.user_metadata)==null?void 0:T.name)==null?void 0:A.split(" ")[0]}],test_mode:!0}});if(S)throw S;return N},onSuccess:()=>{ue.success("Test email sent to your inbox!")},onError:b=>{ue.error("Failed to send test: "+b.message)}}),g=()=>{if(!t.trim()){ue.error("Please enter an email address");return}if(c==null?void 0:c.find(N=>N.email.toLowerCase()===t.trim().toLowerCase())){ue.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:n.trim()||void 0}])},v=b=>{var T;const N=(T=b.target.files)==null?void 0:T[0];if(!N)return;const S=new FileReader;S.onload=A=>{var F,$;const D=((F=A.target)==null?void 0:F.result).split(` `).filter(X=>X.trim()),B=[],z=($=D[0])!=null&&$.toLowerCase().includes("email")?1:0;for(let X=z;Xne.trim().replace(/"/g,"")),Q=K[0],Y=K[1];Q&&Q.includes("@")&&B.push({email:Q,first_name:Y||void 0})}l(B),ue.success(`${B.length} entries loaded from CSV`)},S.readAsText(N),o.current&&(o.current.value="")},j=()=>{if(i.length===0){ue.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),N=i.filter(S=>!b.has(S.email.toLowerCase()));if(N.length===0){ue.error("All emails have already been prospected");return}N.lengthx.mutate(),disabled:x.isPending,className:"gap-2 ml-4 shrink-0",children:[x.isPending?e.jsx(ls,{className:"h-3 w-3 animate-spin"}):e.jsx(Qs,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(De,{children:e.jsxs(Rn,{defaultValue:"single",children:[e.jsxs(Dn,{className:"mb-4",children:[e.jsxs(Xt,{value:"single",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Xt,{value:"bulk",children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(as,{value:"single",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(ke,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>r(b.target.value),onKeyDown:b=>b.key==="Enter"&&g()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(he,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(ke,{id:"prospect-name",placeholder:"First name (optional)",value:n,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&g()})]}),e.jsxs(G,{onClick:g,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(as,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:v,className:"hidden"}),e.jsxs(G,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fr,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(G,{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,N)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},N)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(G,{onClick:j,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Nr,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(De,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,N)=>e.jsx(Vs,{className:"h-12 w-full"},N))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Ss(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"}),"Converted"]}):e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?Ss(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zd,{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 zz(s){const t=es(),{toast:r}=Ea(),n=gt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await H.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=gt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],h=0,m=!0;for(;m;){const{data:x,error:g}=await H.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(h,h+c-1);if(g)throw g;d=d.concat(x),m=x.length===c,h+=c}return d},enabled:!!s}),i=Lt({mutationFn:async c=>{const{data:{user:d}}=await H.auth.getUser();if(!d)throw new Error("Not authenticated");const h={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:m,error:x}=await H.from("recruit_prospects").insert(h).select().single();if(x)throw x;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect added"})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),l=Lt({mutationFn:async({id:c,...d})=>{const{data:h,error:m}=await H.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),o=Lt({mutationFn:async c=>{const{error:d}=await H.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 A6s(s){const t=es(),{toast:r}=Ea(),n=gt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await H.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=Lt({mutationFn:async i=>{const{data:{user:l}}=await H.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await H.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 tHe=(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 Vxt({open:s,onOpenChange:t,stages:r,defaultStageId:n,onSubmit:a,isSubmitting:i}){const[l,o]=k.useState(tHe(n,r)),c=h=>m=>o(x=>({...x,[h]:m.target.value})),d=h=>{h.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(tHe(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(js,{children:e.jsx(bs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(Rn,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-4",children:[e.jsx(Xt,{value:"basic",children:"Basic Info"}),e.jsx(Xt,{value:"production",children:"Production"}),e.jsx(Xt,{value:"social",children:"Social & Web"}),e.jsx(Xt,{value:"personal",children:"Personal"})]}),e.jsxs(as,{value:"basic",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"First Name *"}),e.jsx(ke,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Name"}),e.jsx(ke,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(ke,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(ke,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Current Brokerage"}),e.jsx(ke,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"License #"}),e.jsx(ke,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Experience (years)"}),e.jsx(ke,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Address"}),e.jsx(ke,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"City"}),e.jsx(ke,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"State"}),e.jsx(ke,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Zip"}),e.jsx(ke,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Pipeline Stage"}),e.jsxs(zs,{value:l.stage_id,onValueChange:h=>o(m=>({...m,stage_id:h})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:r.map(h=>e.jsx(mt,{value:h.id,children:h.name},h.id))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Referred By"}),e.jsx(ke,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(as,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Annual Production Volume"}),e.jsx(ke,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Last Year Volume"}),e.jsx(ke,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Year Transactions"}),e.jsx(ke,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Avg Sale Price"}),e.jsx(ke,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Specialties / Niche"}),e.jsx(ke,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(as,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"LinkedIn URL"}),e.jsx(ke,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Website URL"}),e.jsx(ke,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Instagram Handle"}),e.jsx(ke,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Facebook URL"}),e.jsx(ke,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(as,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Birthday"}),e.jsx(ke,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Spouse / Partner Name"}),e.jsx(ke,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Interests / Hobbies"}),e.jsx(ke,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(ur,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}const qSe=[{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 M6s(s){return gt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function I6s(s){return gt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Hxt(){const s=es(),{toast:t}=Ea();return Lt({mutationFn:async r=>{const{data:{user:n}}=await H.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await H.from("recruit_videos").insert({prospect_id:r.prospect_id,video_id:r.video_id,brokerage_id:r.brokerage_id,message:r.message||null,created_by:n.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status)").single();if(i)throw i;return a},onSuccess:r=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",r.prospect_id]}),t({title:"Video linked to prospect"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function Gxt(){const s=es();return Lt({mutationFn:async({id:t,sent_via:r})=>{const{error:n}=await H.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 Wxt(s){return gt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 P6s(){const s=es(),{toast:t}=Ea();return Lt({mutationFn:async r=>{const{data:{user:n}}=await H.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await H.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 L6s(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("recruit_video_scripts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function D6s({prospectId:s,prospectName:t,brokerageId:r}){var F;const{data:n=[],isLoading:a}=I6s(s),{data:i=[]}=Wxt(r),l=Hxt(),o=O_(),c=Gxt(),[d,h]=k.useState("idle"),[m,x]=k.useState(0),[g,v]=k.useState(0),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(!1),P=((F=i.find($=>$.id===j))==null?void 0:F.script_text)||"",D=()=>{h("idle"),x(0),v(0),b(""),S("")},B=k.useCallback(async($,X)=>{h("uploading");try{const K=`Recruiting: ${t}`,{videoId:Q,libraryId:Y}=await sT(K),{uploadUrl:ne,apiKey:de}=await rT(Q),ce=new XMLHttpRequest;ce.upload.onprogress=Me=>{Me.lengthComputable&&x(Me.loaded/Me.total*100)},await new Promise((Me,Pe)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Me():Pe(new Error("Upload failed")),ce.onerror=()=>Pe(new Error("Upload failed")),ce.open("PUT",ne),ce.setRequestHeader("AccessKey",de),ce.send($)}),h("processing");let ae=0;const ie=Date.now(),me=9e4,oe=`https://iframe.mediadelivery.net/embed/${Y}/${Q}`;for(;ae<4&&(await new Promise(Pe=>setTimeout(Pe,3e3)),!(Date.now()-ie>me));){const Me=await u1(Q);if(ae=Me.status,v(Me.encodeProgress||0),ae===5||ae===6)throw new Error("Video processing failed")}const ge=await u1(Q),be=(ge.storageSize||$.size)/(1024*1024),Oe=await o.mutateAsync({bunny_video_id:Q,playback_url:ge.directPlayUrl||oe,thumbnail_url:ge.thumbnailUrl,preview_url:ge.previewUrl||null,duration_seconds:ge.length||X,file_size_mb:be,title:K,status:ae>=4?"ready":"processing",touch_type:"recruiting"});await l.mutateAsync({prospect_id:s,video_id:Oe.id,brokerage_id:r,message:N||void 0}),h("done"),ue.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),D()},1500)}catch(K){ue.error(K.message||"Failed to upload video"),h("record")}},[s,t,r,N,o,l]),z=$=>{$&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${$}`),ue.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(vs,{open:T,onOpenChange:$=>{!$&&(d==="uploading"||d==="processing")||(A($),$||D())},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>h("script"),children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(js,{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(he,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(zs,{value:j,onValueChange:b,children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"No script — speak freely"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"none",children:"No script"}),i.map($=>{var X;return e.jsx(mt,{value:$.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[$.title,e.jsx(Ge,{variant:"outline",className:"text-[9px] ml-1",children:(X=qSe.find(K=>K.value===$.category))==null?void 0:X.label})]})},$.id)})]})]}),P&&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:P})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(ur,{value:N,onChange:$=>S($.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(G,{onClick:()=>h("record"),className:"w-full",children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(xL,{maxDurationSeconds:600,onRecordingComplete:B,teleprompterContent:P||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(ri,{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(ri,{value:g,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(g),"%"]})]}),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(Ho,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),a?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"})}):n.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:n.map($=>{var X,K;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:(X=$.video)!=null&&X.thumbnail_url?e.jsx("img",{src:$.video.thumbnail_url,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(sn,{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:((K=$.video)==null?void 0:K.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[$.view_count>0?e.jsxs(Ge,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(jn,{className:"h-2.5 w-2.5 mr-0.5"}),$.view_count]}):$.sent_at?e.jsxs(Ge,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Ge,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(cn,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ss(new Date($.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>z($.share_token),children:e.jsx(Ra,{className:"h-3 w-3"})}),!$.sent_at&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>c.mutate({id:$.id,sent_via:"email"}),children:e.jsx(Zr,{className:"h-3 w-3"})})]})]},$.id)})})]})}function R6s(s){return gt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 sHe=[{value:"call",label:"Phone Call",icon:Nn},{value:"email",label:"Email",icon:Qs},{value:"text",label:"Text Message",icon:bi},{value:"meeting",label:"Meeting",icon:rn},{value:"note",label:"Note",icon:ln},{value:"campaign_email",label:"Campaign Email",icon:Zr}];function Gp({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 rq({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(Yr,{className:"h-3 w-3 opacity-50"})]}):null}function kc({label:s,value:t,onChange:r,type:n="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:s}),e.jsx(ke,{type:n,value:t,onChange:i=>r(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Kxt({prospect:s,stages:t,brokerageId:r,open:n,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=A6s((s==null?void 0:s.id)||null),{data:d=[]}=R6s((s==null?void 0:s.id)||null),[h,m]=k.useState({type:"note",title:"",description:""}),[x,g]=k.useState(!1),[v,j]=k.useState(!1),[b,N]=k.useState({});if(!s)return null;const S=()=>{var K,Q;N({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((K=s.experience_years)==null?void 0:K.toString())||"",notes:s.notes||"",source:s.source||"",address:s.address||"",city:s.city||"",state:s.state||"",zip_code:s.zip_code||"",last_year_volume:s.last_year_volume||"",last_year_transactions:((Q=s.last_year_transactions)==null?void 0:Q.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||""}),j(!0)},T=()=>{const K={id:s.id};for(const[Q,Y]of Object.entries(b))Q==="experience_years"||Q==="last_year_transactions"?K[Q]=Y?parseInt(Y):null:K[Q]=Y||null;i(K),j(!1)},A=()=>j(!1),P=K=>Q=>N(Y=>({...Y,[K]:Q})),D=()=>{h.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:h.type,title:h.title,description:h.description||null}),m({type:"note",title:"",description:""}),g(!1))},B=t.find(K=>K.id===s.stage_id),z=s.address||s.city||s.state,F=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,$=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,X=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsx(G2,{open:n,onOpenChange:K=>{K||j(!1),a(K)},children:e.jsx(I_,{className:"w-full sm:max-w-lg p-0",children:e.jsx(ti,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(W2,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(K2,{className:"text-xl",children:[s.first_name," ",s.last_name]}),B&&e.jsx(Ge,{variant:"outline",style:{borderColor:B.color,color:B.color},className:"mt-1",children:B.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[v?e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:A,children:e.jsx(_r,{className:"h-4 w-4"})}),e.jsx(G,{variant:"default",size:"icon",onClick:T,children:e.jsx(ql,{className:"h-4 w-4"})})]}):e.jsx(G,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete prospect?"}),e.jsx(Uo,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!v&&e.jsxs("div",{className:"space-y-1.5 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"})," ",s.email]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," ",s.phone]}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ja,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(zs,{value:s.stage_id||"",onValueChange:K=>i({id:s.id,stage_id:K}),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{})}),e.jsx(Fs,{children:t.map(K=>e.jsx(mt,{value:K.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:K.color}}),K.name]})},K.id))})]})]}),e.jsxs(Rn,{defaultValue:"details",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Xt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Xt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Xt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Xt,{value:"personal",className:"text-xs",children:"Personal"})]}),v?e.jsxs(e.Fragment,{children:[e.jsxs(as,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(kc,{label:"First Name",value:b.first_name,onChange:P("first_name")}),e.jsx(kc,{label:"Last Name",value:b.last_name,onChange:P("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(kc,{label:"Email",value:b.email,onChange:P("email"),type:"email"}),e.jsx(kc,{label:"Phone",value:b.phone,onChange:P("phone")})]}),e.jsx(kc,{label:"Current Brokerage",value:b.current_brokerage,onChange:P("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(kc,{label:"License #",value:b.license_number,onChange:P("license_number")}),e.jsx(kc,{label:"Experience (years)",value:b.experience_years,onChange:P("experience_years"),type:"number"})]}),e.jsx(kc,{label:"Address",value:b.address,onChange:P("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(kc,{label:"City",value:b.city,onChange:P("city")}),e.jsx(kc,{label:"State",value:b.state,onChange:P("state")}),e.jsx(kc,{label:"Zip",value:b.zip_code,onChange:P("zip_code")})]}),e.jsx(kc,{label:"Source",value:b.source,onChange:P("source")}),e.jsx(kc,{label:"Referred By",value:b.referred_by,onChange:P("referred_by")}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Notes"}),e.jsx(ur,{value:b.notes,onChange:K=>N(Q=>({...Q,notes:K.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(as,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(kc,{label:"Annual Production",value:b.annual_production,onChange:P("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(kc,{label:"Last Year Volume",value:b.last_year_volume,onChange:P("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(kc,{label:"Last Year Transactions",value:b.last_year_transactions,onChange:P("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(kc,{label:"Avg Sale Price",value:b.avg_sale_price,onChange:P("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(kc,{label:"Specialties / Niche",value:b.specialties,onChange:P("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(as,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(kc,{label:"LinkedIn URL",value:b.linkedin_url,onChange:P("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(kc,{label:"Website URL",value:b.website_url,onChange:P("website_url"),type:"url",placeholder:"https://..."}),e.jsx(kc,{label:"Instagram Handle",value:b.instagram_handle,onChange:P("instagram_handle"),placeholder:"@handle"}),e.jsx(kc,{label:"Facebook URL",value:b.facebook_url,onChange:P("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(as,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(kc,{label:"Birthday",value:b.birthday,onChange:P("birthday"),type:"date"}),e.jsx(kc,{label:"Spouse / Partner",value:b.spouse_name,onChange:P("spouse_name")}),e.jsx(kc,{label:"Interests / Hobbies",value:b.interests,onChange:P("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(as,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Gp,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(Gp,{label:"License #",value:s.license_number}),e.jsx(Gp,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(Gp,{label:"Referred By",value:s.referred_by}),e.jsx(Gp,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(as,{value:"production",className:"mt-3",children:F?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Gp,{label:"Annual Production",value:s.annual_production}),e.jsx(Gp,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(Gp,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(Gp,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(Gp,{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(as,{value:"social",className:"mt-3",children:$?e.jsxs("div",{className:"space-y-2",children:[e.jsx(rq,{label:"LinkedIn",url:s.linkedin_url,icon:om}),e.jsx(rq,{label:"Website",url:s.website_url,icon:gc}),s.instagram_handle&&e.jsx(rq,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:au}),e.jsx(rq,{label:"Facebook",url:s.facebook_url,icon:ku})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(as,{value:"personal",className:"mt-3",children:X?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Gp,{label:"Birthday",value:s.birthday?Ss(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:li}),e.jsx(Gp,{label:"Spouse / Partner",value:s.spouse_name,icon:hi}),e.jsx("div",{className:"col-span-2",children:e.jsx(Gp,{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(D6s,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,brokerageId:r}),e.jsx(po,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>g(!x),children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),x&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(zs,{value:h.type,onValueChange:K=>m(Q=>({...Q,type:K})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:sHe.map(K=>e.jsx(mt,{value:K.value,children:K.label},K.value))})]}),e.jsx(ke,{placeholder:"Subject / Title",value:h.title,onChange:K=>m(Q=>({...Q,title:K.target.value}))}),e.jsx(ur,{placeholder:"Details (optional)",value:h.description,onChange:K=>m(Q=>({...Q,description:K.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>g(!1),children:"Cancel"}),e.jsx(G,{size:"sm",onClick:D,disabled:!h.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const K=[...o.map(Q=>({type:"manual",data:Q,date:Q.created_at})),...d.map(Q=>({type:"campaign_email",data:Q,date:Q.sent_at||Q.created_at}))].sort((Q,Y)=>new Date(Y.date).getTime()-new Date(Q.date).getTime());return K.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):K.map(Q=>{if(Q.type==="manual"){const ne=Q.data,de=sHe.find(ae=>ae.value===ne.activity_type),ce=(de==null?void 0:de.icon)||ln;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:ne.title}),ne.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ne.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ss(new Date(ne.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ne.id}`)}const Y=Q.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(Zr,{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 #",Y.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Y.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Y.status==="failed"?e.jsx(Ge,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Y.opened_at?e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(jn,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Ss(new Date(Y.opened_at),"MMM d, h:mm a")]}):Y.status!=="failed"?e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Y.clicked_at&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(tm,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Ss(new Date(Y.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ss(new Date(Y.sent_at||Y.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Y.id}`)})})()})]})]})})})})}const O6s=["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 Yxt({open:s,onOpenChange:t,brokerageId:r,stages:n}){var $;const{toast:a}=Ea(),i=es(),l=k.useRef(null),[o,c]=k.useState([]),[d,h]=k.useState([]),[m,x]=k.useState({}),[g,v]=k.useState((($=n[0])==null?void 0:$.id)||""),[j,b]=k.useState(!1),[N,S]=k.useState("upload"),[T,A]=k.useState(0),P=()=>{c([]),h([]),x({}),S("upload"),A(0)},D=X=>{var Y;const K=(Y=X.target.files)==null?void 0:Y[0];if(!K)return;const Q=new FileReader;Q.onload=ne=>{var ge;const ce=((ge=ne.target)==null?void 0:ge.result).split(/\r?\n/).filter(be=>be.trim());if(ce.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ae=B(ce[0]);h(ae);const ie={},me=new Set;ae.forEach((be,Oe)=>{const Me=be.toLowerCase().replace(/[^a-z0-9]/g,"");let Pe=null;/^firstname$/.test(Me)||Me==="first"?Pe="first_name":/^lastname$/.test(Me)||Me==="last"?Pe="last_name":/^email$/.test(Me)||Me==="emailaddress"?Pe="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Me)?Pe="phone":/officename|currentbrokerage|brokerage|company/.test(Me)?Pe="current_brokerage":/membernumber|licensenumber|license/.test(Me)?Pe="license_number":/experienceyears|yearsexperience/.test(Me)?Pe="experience_years":/^totalvolume$|annualproduction/.test(Me)?Pe="annual_production":/^address$/.test(Me)?Pe="address":/^city$/.test(Me)?Pe="city":/^state$/.test(Me)?Pe="state":/^postalcode$|^zip$|^zipcode$/.test(Me)?Pe="zip_code":/listsidevolume|lastyearvolume/.test(Me)?Pe="last_year_volume":/^totalcount$|lastyeartransactions/.test(Me)?Pe="last_year_transactions":/avgsaleprice|averageprice/.test(Me)?Pe="avg_sale_price":/linkedin/.test(Me)?Pe="linkedin_url":/website/.test(Me)?Pe="website_url":/specialt/.test(Me)?Pe="specialties":/referr/.test(Me)?Pe="referred_by":/^notes$|^note$/.test(Me)&&(Pe="notes"),Pe&&!me.has(Pe)&&(ie[String(Oe)]=Pe,me.add(Pe))}),x(ie);const oe=ce.slice(1).map(be=>{const Oe=B(be),Me={};return ae.forEach((Pe,Ee)=>{Me[String(Ee)]=Oe[Ee]||""}),Me});c(oe),S("map")},Q.readAsText(K)},B=X=>{const K=[];let Q="",Y=!1;for(const ne of X)ne==='"'?Y=!Y:ne===","&&!Y?(K.push(Q.trim()),Q=""):Q+=ne;return K.push(Q.trim()),K},z=async()=>{b(!0);try{const{data:{user:X}}=await H.auth.getUser();if(!X)throw new Error("Not authenticated");const K=o.map(Y=>{const ne={brokerage_id:r,created_by:X.id,stage_id:g,source:"csv_import",first_name:"Unknown"},de=ne;return Object.entries(m).forEach(([ce,ae])=>{var me;const ie=(me=Y[ce])==null?void 0:me.trim();ie&&(ae==="experience_years"||ae==="last_year_transactions"?de[ae]=parseInt(ie.replace(/[^0-9.-]/g,""))||null:ae==="annual_production"||ae==="last_year_volume"||ae==="avg_sale_price"?de[ae]=ie.replace(/[^0-9.$,.-]/g,""):de[ae]=ie)}),ne});let Q=0;for(let Y=0;Y{const X=`first_name,last_name,email,phone,current_brokerage,license_number,experience_years,annual_production,notes Jane,Smith,jane@example.com,555-0100,ABC Realty,RE12345,8,$5M,Met at conference`,K=new Blob([X],{type:"text/csv"}),Q=URL.createObjectURL(K),Y=document.createElement("a");Y.href=Q,Y.download="recruit-prospects-template.csv",Y.click(),URL.revokeObjectURL(Q)};return e.jsx(vs,{open:s,onOpenChange:X=>{X||P(),t(X)},children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:"Import Prospects from CSV"})}),N==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx(Jb,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:D}),e.jsxs(G,{onClick:()=>{var X;return(X=l.current)==null?void 0:X.click()},children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(G,{variant:"link",className:"text-xs",onClick:F,children:"Download CSV template"})]}),N==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{className:"w-[180px]",children:e.jsx(Us,{})}),e.jsx(Fs,{children:n.map(X=>e.jsx(mt,{value:X.id,children:X.name},X.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Tt,{className:"w-[160px]",children:"Map To"}),e.jsx(Tt,{children:"Preview"})]})}),e.jsx(Bn,{children:d.map((X,K)=>{var Q;return e.jsxs(qs,{children:[e.jsx(ft,{className:"font-medium text-xs",children:X}),e.jsx(ft,{children:e.jsxs(zs,{value:m[String(K)]||"skip",onValueChange:Y=>x(ne=>({...ne,[String(K)]:Y==="skip"?"":Y})),children:[e.jsx(Os,{className:"h-8 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"skip",children:"— Skip —"}),O6s.map(Y=>e.jsx(mt,{value:Y,children:Y.replace(/_/g," ")},Y))]})]})}),e.jsx(ft,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((Q=o[0])==null?void 0:Q[String(K)])||"—"})]},K)})})]})}),!Object.values(m).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Hi,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>{P()},children:"Back"}),e.jsx(G,{onClick:z,disabled:j||!Object.values(m).includes("first_name"),children:j?"Importing...":`Import ${o.length} Prospects`})]})]}),N==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(Hn,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[T," prospects imported successfully!"]}),e.jsx(G,{onClick:()=>{P(),t(!1)},children:"Close"})]})]})})}function Zxt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=zz(s),[o,c]=k.useState(!1),[d,h]=k.useState(),[m,x]=k.useState(null),[g,v]=k.useState(!1),[j,b]=k.useState(!1),[N,S]=k.useState(null);if(n)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const T=F=>r.filter($=>$.stage_id===F),A=(F,$)=>{S($),F.dataTransfer.effectAllowed="move"},P=F=>{F.preventDefault(),F.dataTransfer.dropEffect="move"},D=(F,$)=>{F.preventDefault(),N&&(i.mutate({id:N,stage_id:$}),S(null))},B=F=>{h(F),c(!0)},z=F=>{x(F),v(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.length," prospect",r.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(G,{onClick:()=>{h(void 0),c(!0)},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(ti,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(F=>{const $=T(F.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:P,onDrop:X=>D(X,F.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:F.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:F.name}),e.jsx(Ge,{variant:"secondary",className:"text-xs h-5 px-1.5",children:$.length})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>B(F.id),children:e.jsx(Ws,{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:$.map(X=>e.jsx(Ne,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:F.color},draggable:!0,onDragStart:K=>A(K,X.id),onClick:()=>z(X),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Su,{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(Bi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[X.first_name," ",X.last_name]})]}),X.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Sa,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:X.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[X.email&&e.jsx(Qs,{className:"h-3 w-3 text-muted-foreground"}),X.phone&&e.jsx(Nn,{className:"h-3 w-3 text-muted-foreground"}),X.experience_years!=null&&e.jsxs(Ge,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[X.experience_years,"yr"]})]})]})]})},X.id))})]},F.id)})}),e.jsx(Ppe,{orientation:"horizontal"})]}),e.jsx(Vxt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:F=>a.mutate(F),isSubmitting:a.isPending}),e.jsx(Kxt,{prospect:m,stages:t,brokerageId:s,open:g,onOpenChange:v,onUpdate:F=>{i.mutate(F),x($=>$?{...$,...F}:null)},onDelete:F=>l.mutate(F)}),e.jsx(Yxt,{open:j,onOpenChange:b,brokerageId:s,stages:t})]})}function hfe({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=zz(s),{user:o}=As(),c=es(),[d,h]=k.useState(!1),[m,x]=k.useState(null),[g,v]=k.useState(!1),[j,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState("all"),[P,D]=k.useState("all"),[B,z]=k.useState("all"),[F,$]=k.useState(null),[X,K]=k.useState("asc"),[Q,Y]=k.useState(new Set),[ne,de]=k.useState(!1),[ce,ae]=k.useState(""),ie=k.useMemo(()=>{const ye=new Set;return r.forEach(ct=>{ct.current_brokerage&&ye.add(ct.current_brokerage)}),Array.from(ye).sort()},[r]),{data:me=[]}=gt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ye,error:ct}=await H.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(ct)throw ct;return ye}}),{data:oe=[]}=gt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let ct=[],ve=0;for(;;){const{data:rt,error:Re}=await H.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(ve,ve+1e3-1);if(Re)throw Re;if(ct=ct.concat(rt??[]),!rt||rt.length<1e3)break;ve+=1e3}return ct}}),ge=k.useMemo(()=>{const ye=new Map;return oe.forEach(ct=>{ye.has(ct.prospect_id)||ye.set(ct.prospect_id,new Set),ye.get(ct.prospect_id).add(ct.campaign_id)}),ye},[oe]),be=ye=>{F===ye?K(ct=>ct==="asc"?"desc":"asc"):($(ye),K("asc"))},Oe=({column:ye})=>F!==ye?e.jsx(Rd,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):X==="asc"?e.jsx(Fd,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Ku,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Me=ye=>t.find(ct=>ct.id===ye),Pe=k.useMemo(()=>{let ye=r.filter(ct=>{var Ke,Ce,nt;const ve=!N||`${ct.first_name} ${ct.last_name}`.toLowerCase().includes(N.toLowerCase())||((Ke=ct.email)==null?void 0:Ke.toLowerCase().includes(N.toLowerCase()))||((Ce=ct.current_brokerage)==null?void 0:Ce.toLowerCase().includes(N.toLowerCase())),rt=T==="all"||ct.stage_id===T,Re=P==="all"||ct.current_brokerage===P;let Qe=!0;return B==="in_campaign"?Qe=ge.has(ct.id):B==="not_in_campaign"?Qe=!ge.has(ct.id):B!=="all"&&(Qe=((nt=ge.get(ct.id))==null?void 0:nt.has(B))??!1),ve&&rt&&Re&&Qe});return F&&(ye=[...ye].sort((ct,ve)=>{var Ke,Ce;let rt=null,Re=null;switch(F){case"name":rt=`${ct.first_name} ${ct.last_name||""}`.toLowerCase(),Re=`${ve.first_name} ${ve.last_name||""}`.toLowerCase();break;case"stage":rt=((Ke=Me(ct.stage_id))==null?void 0:Ke.sort_order)??999,Re=((Ce=Me(ve.stage_id))==null?void 0:Ce.sort_order)??999;break;case"brokerage":rt=(ct.current_brokerage||"").toLowerCase(),Re=(ve.current_brokerage||"").toLowerCase();break;case"experience":rt=ct.experience_years??-1,Re=ve.experience_years??-1;break;case"production":rt=(ct.annual_production||"").toLowerCase(),Re=(ve.annual_production||"").toLowerCase();break;case"source":rt=(ct.source||"").toLowerCase(),Re=(ve.source||"").toLowerCase();break;default:return 0}if(rt===Re)return 0;if(rt==null)return 1;if(Re==null)return-1;const Qe=rt0&&Pe.every(ye=>Q.has(ye.id)),$e=Pe.some(ye=>Q.has(ye.id)),Se=()=>{Y(Ee?new Set:new Set(Pe.map(ye=>ye.id)))},ze=ye=>{Y(ct=>{const ve=new Set(ct);return ve.has(ye)?ve.delete(ye):ve.add(ye),ve})},Te=Lt({mutationFn:async()=>{if(!ce||!(o!=null&&o.id))throw new Error("Select a campaign");const ye=new Set(oe.filter(rt=>rt.campaign_id===ce).map(rt=>rt.prospect_id)),ct=Array.from(Q).filter(rt=>!ye.has(rt)).map(rt=>({prospect_id:rt,campaign_id:ce,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(ct.length===0)throw new Error("All selected prospects are already in this campaign");const{error:ve}=await H.from("recruit_campaign_assignments").insert(ct);if(ve)throw ve;return ct.length},onSuccess:ye=>{ue.success(`${ye} prospect(s) added to campaign`),de(!1),Y(new Set),ae(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ye=>ue.error(ye.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(fn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search prospects...",value:N,onChange:ye=>S(ye.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[Q.size>0&&e.jsxs(G,{variant:"secondary",onClick:()=>de(!0),className:"gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4"})," Add ",Q.size," to Campaign"]}),e.jsxs(G,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(G,{onClick:()=>h(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(s0,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(zs,{value:T,onValueChange:A,children:[e.jsx(Os,{className:"w-[160px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All stages"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All stages"}),t.map(ye=>e.jsx(mt,{value:ye.id,children:ye.name},ye.id))]})]}),e.jsxs(zs,{value:P,onValueChange:D,children:[e.jsxs(Os,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Us,{placeholder:"All brokerages"})]}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All brokerages"}),ie.map(ye=>e.jsx(mt,{value:ye,children:ye},ye))]})]}),e.jsxs(zs,{value:B,onValueChange:z,children:[e.jsxs(Os,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Us,{placeholder:"Campaign status"})]}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All contacts"}),e.jsx(mt,{value:"in_campaign",children:"In any campaign"}),e.jsx(mt,{value:"not_in_campaign",children:"Not in any campaign"}),me.map(ye=>e.jsxs(mt,{value:ye.id,children:["In: ",ye.name]},ye.id))]})]}),(T!=="all"||P!=="all"||B!=="all")&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),D("all"),z("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(Ei,{checked:Ee,onCheckedChange:Se,"aria-label":"Select all",...$e&&!Ee?{"data-state":"indeterminate"}:{}})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>be("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Oe,{column:"name"})]})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>be("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Oe,{column:"stage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>be("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Oe,{column:"brokerage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>be("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Oe,{column:"experience"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>be("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Oe,{column:"production"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(Bn,{children:Pe.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Pe.map(ye=>{const ct=Me(ye.stage_id),ve=ge.get(ye.id),rt=(ve==null?void 0:ve.size)??0;return e.jsxs(qs,{className:"cursor-pointer",onClick:()=>{x(ye),v(!0)},children:[e.jsx(ft,{onClick:Re=>Re.stopPropagation(),children:e.jsx(Ei,{checked:Q.has(ye.id),onCheckedChange:()=>ze(ye.id),"aria-label":`Select ${ye.first_name}`})}),e.jsxs(ft,{className:"font-medium",children:[ye.first_name," ",ye.last_name]}),e.jsx(ft,{children:ct?e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:ct.color,color:ct.color,backgroundColor:`${ct.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:ct.color}}),ct.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(ft,{className:"hidden md:table-cell",children:ye.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ye.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ft,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ye.email&&e.jsx(Qs,{className:"h-3.5 w-3.5 text-muted-foreground"}),ye.phone&&e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ye.email&&!ye.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(ft,{className:"hidden lg:table-cell",children:ye.experience_years!=null?`${ye.experience_years} yr`:"—"}),e.jsx(ft,{className:"hidden lg:table-cell",children:ye.annual_production||"—"}),e.jsx(ft,{className:"hidden lg:table-cell",children:rt>0?e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[rt," campaign",rt>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(ft,{children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Re=>{Re.stopPropagation(),l.mutate(ye.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})})]},ye.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 · "]}),Pe.length," of ",r.length," prospects"]}),e.jsx(vs,{open:ne,onOpenChange:de,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(js,{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(he,{children:"Campaign"}),e.jsxs(zs,{value:ce,onValueChange:ae,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a campaign..."})}),e.jsx(Fs,{children:me.map(ye=>e.jsxs(mt,{value:ye.id,children:[ye.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ye.warmth_level,")"]})]},ye.id))})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>Te.mutate(),disabled:!ce||Te.isPending,children:Te.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Vxt,{open:d,onOpenChange:h,stages:t,onSubmit:ye=>a.mutate(ye),isSubmitting:a.isPending}),e.jsx(Kxt,{prospect:m,stages:t,brokerageId:s,open:g,onOpenChange:v,onUpdate:ye=>{i.mutate(ye),x(ct=>ct?{...ct,...ye}:null)},onDelete:ye=>l.mutate(ye)}),e.jsx(Yxt,{open:j,onOpenChange:b,brokerageId:s,stages:t})]})}function Xxt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n}=zz(s),a=k.useMemo(()=>{if(!t.length||!r.length)return null;const i=r.length,l=t.find(N=>N.name==="Signed"),o=t.find(N=>N.name==="Onboarded"),c=r.filter(N=>N.stage_id===(l==null?void 0:l.id)||N.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",h=new Date,m=i>0?Math.round(r.reduce((N,S)=>N+Kg(h,new Date(S.created_at)),0)/i):0,x=t.map(N=>({...N,count:r.filter(S=>S.stage_id===N.id).length})),g={};r.forEach(N=>{const S=N.source||"unknown";g[S]=(g[S]||0)+1});const v=Object.entries(g).sort((N,S)=>S[1]-N[1]),j=new Date;j.setDate(j.getDate()-30);const b=r.filter(N=>new Date(N.created_at)>=j).length;return{total:i,signed:c,conversionRate:d,avgDays:m,byStage:x,bySrc:v,recentCount:b}},[t,r]);return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsx(De,{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(fr,{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(Ne,{children:e.jsx(De,{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(_o,{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(Ne,{children:e.jsx(De,{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(cn,{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(Ne,{children:e.jsx(De,{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(zd,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(De,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(De,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ge,{variant:"secondary",className:"capitalize",children:i.replace(/_/g," ")}),e.jsx("span",{className:"text-sm font-medium",children:l})]},i)),a.bySrc.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No source data"})]})]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No prospect data yet. Add prospects to see metrics."})}const rHe=[{id:"value-prop",category:"Outreach",title:"Value Proposition Introduction",subject:"A Better Way to Grow Your Real Estate Business",body:`Hi [First Name], I hope this message finds you well. I've been following your work in [Area/Market] and I'm impressed by what you've accomplished. I'm reaching out because I believe our brokerage offers unique tools and support that could help take your business to the next level: • Industry-leading commission splits • Full marketing suite with customizable templates • Advanced CRM and lead generation tools • Ongoing training and mentorship programs • Collaborative team environment I'd love to share more about how we're helping agents like you grow their business. Would you be open to a brief conversation this week? Best regards, [Your Name]`},{id:"follow-up",category:"Follow-up",title:"Gentle Follow-up",subject:"Following Up – Quick Chat?",body:`Hi [First Name], I wanted to follow up on my previous message. I understand you're busy – that's the sign of a successful agent! I'd love just 15 minutes of your time to show you what makes our brokerage different. Many agents who've made the switch tell us they wish they'd done it sooner. Would [Day/Time] work for a quick call or coffee? Looking forward to connecting, [Your Name]`},{id:"interview-invite",category:"Interview",title:"Interview / Meeting Invitation",subject:"Invitation to Learn More About [Brokerage Name]",body:`Hi [First Name], Thank you for your interest in exploring opportunities with [Brokerage Name]! I'd love to set up a time for us to meet and discuss how we can support your career goals. Here's what we'll cover: • Our commission structure and agent benefits • Technology and marketing tools available to you • Training and professional development opportunities • Culture and team dynamics • Your questions and goals I have availability on: • [Date/Time Option 1] • [Date/Time Option 2] • [Date/Time Option 3] Please let me know which time works best, or suggest an alternative that suits your schedule. Warm regards, [Your Name]`},{id:"offer",category:"Offer",title:"Formal Offer / Welcome",subject:"Welcome to the Team – Your Offer Details",body:`Hi [First Name], I'm thrilled to extend a formal invitation to join [Brokerage Name]! Based on our conversations, I'm confident this will be a great fit for both of us. Here's a summary of your offer: • Commission Split: [Details] • Start Date: [Date] • Desk/Office: [Details] • Technology Package: [Details] • Additional Benefits: [Details] Next steps: 1. Review the attached agreement 2. Complete the onboarding paperwork 3. Schedule your first-week orientation Please feel free to reach out with any questions. We're excited to have you on the team! Welcome aboard, [Your Name]`},{id:"referral-ask",category:"Referral",title:"Agent Referral Request",subject:"Know Any Great Agents Looking for a Change?",body:`Hi [First Name], Hope you're having a great [week/month]! I'm reaching out because our brokerage is growing and we're looking for talented agents to join our team. Since you know the industry well, I was wondering if you know any agents who might be: • Looking for better technology and support • Seeking a more collaborative environment • Ready to take their business to the next level We offer a referral bonus of [Amount/Details] for any successful placement. It's a great way to help a colleague while earning something extra. If anyone comes to mind, I'd appreciate the introduction! Thanks, [Your Name]`},{id:"market-update",category:"Outreach",title:"Market Insights Outreach",subject:"Market Update + Growth Opportunity",body:`Hi [First Name], With the recent changes in [local market conditions], I wanted to share some insights on how top-performing agents are adapting: 📊 [Market Stat 1] 📈 [Market Stat 2] 🏠 [Market Stat 3] At [Brokerage Name], we're equipping our agents with cutting-edge tools to thrive in this market: • AI-powered lead generation • Automated marketing campaigns • Real-time market analytics dashboard I'd love to share how our agents are outperforming the market. Do you have 15 minutes this week? Best, [Your Name]`}];function Qxt({brokerageId:s}){const{toast:t}=Ea(),[r,n]=k.useState(null),[a,i]=k.useState(null),l=(c,d)=>{navigator.clipboard.writeText(c),n(d),t({title:"Copied to clipboard!"}),setTimeout(()=>n(null),2e3)},o=[...new Set(rHe.map(c=>c.category))];return e.jsxs("div",{className:"space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built email templates for recruiting outreach. Click to expand and copy."}),o.map(c=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"})," ",c]}),rHe.filter(d=>d.category===c).map(d=>e.jsxs(Ne,{className:`cursor-pointer transition-all ${a===d.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,onClick:()=>i(a===d.id?null:d.id),children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-sm",children:d.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Subject: ",d.subject]})]}),e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:d.category})]})}),a===d.id&&e.jsxs(De,{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:d.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:d.body})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:h=>{h.stopPropagation(),l(d.subject,d.id+"-subject")},children:[r===d.id+"-subject"?e.jsx(Hn,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(G,{size:"sm",onClick:h=>{h.stopPropagation(),l(d.body,d.id+"-body")},children:[r===d.id+"-body"?e.jsx(Hn,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]})]})]})]},d.id))]},c))]})}const nHe={call:Nn,email:Qs,text:bi,meeting:rn,note:ln};function Jxt({brokerageId:s}){const{data:t,isLoading:r}=gt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:n,error:a}=await H.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(n==null?void 0:n.map(g=>g.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await H.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...n.map(g=>g.created_by),...(l||[]).map(g=>g.created_by)])],{data:d}=await H.from("profiles").select("id, name, email").in("id",c),h=Object.fromEntries((d||[]).map(g=>[g.id,g])),m=fde(new Date,30);return{recruiters:c.map(g=>{var S,T;const v=(l||[]).filter(A=>A.created_by===g),j=v.filter(A=>new Date(A.created_at)>=m),b={};j.forEach(A=>{b[A.activity_type]=(b[A.activity_type]||0)+1});const N=n.filter(A=>A.created_by===g).length;return{id:g,name:((S=h[g])==null?void 0:S.name)||"Unknown",email:((T=h[g])==null?void 0:T.email)||"",totalActivities:v.length,recentActivities:j.length,byType:b,prospectsCreated:N}}).sort((g,v)=>v.recentActivities-g.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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(De,{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(Bi,{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=nHe[i]||ln;return e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},n.id))})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Recent Activity"})}),e.jsx(De,{className:"space-y-3",children:t.recentActivities.map(n=>{const a=nHe[n.activity_type]||ln;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:n.title}),n.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Ss(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 egt({brokerageId:s}){const{toast:t}=Ea(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=gt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:b,error:N}=await H.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(N)throw N;return b}}),d=[...new Set(o.map(b=>b.referred_by))],{data:h=[]}=gt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:b}=await H.from("profiles").select("id, name, email").in("id",d);return b||[]},enabled:d.length>0}),m=Object.fromEntries(h.map(b=>[b.id,b])),x=Lt({mutationFn:async b=>{const{data:{user:N}}=await H.auth.getUser();if(!N)throw new Error("Not authenticated");const{error:S}=await H.from("recruit_referrals").insert({brokerage_id:s,referred_by:N.id,referee_first_name:b.first_name,referee_last_name:b.last_name||null,referee_email:b.email||null,referee_phone:b.phone||null,referee_current_brokerage:b.current_brokerage||null,notes:b.notes||null});if(S)throw S},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),g=Lt({mutationFn:async({id:b,status:N,incentive_status:S})=>{const T={updated_at:new Date().toISOString()};N&&(T.status=N),S&&(T.incentive_status=S);const{error:A}=await H.from("recruit_referrals").update(T).eq("id",b);if(A)throw A},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-referrals",s]})}),v=b=>b==="approved"||b==="signed"?e.jsx(Hn,{className:"h-3 w-3"}):b==="rejected"?e.jsx(Mc,{className:"h-3 w-3"}):e.jsx(cn,{className:"h-3 w-3"}),j=b=>b==="approved"||b==="signed"||b==="paid"?"bg-green-500/10 text-green-600 border-green-200":b==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(G,{onClick:()=>a(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(Ne,{className:"py-12 text-center",children:[e.jsx(nl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(b=>{var N;return e.jsx(Ne,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[b.referee_first_name," ",b.referee_last_name]}),e.jsxs(Ge,{variant:"outline",className:j(b.status),children:[v(b.status)," ",b.status]}),b.incentive_status&&e.jsxs(Ge,{variant:"outline",className:j(b.incentive_status),children:[e.jsx(li,{className:"h-3 w-3 mr-1"})," ",b.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[b.referee_email&&e.jsx("p",{children:b.referee_email}),b.referee_phone&&e.jsx("p",{children:b.referee_phone}),b.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",b.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((N=m[b.referred_by])==null?void 0:N.name)||"Unknown"," • ",Ss(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(zs,{value:b.status,onValueChange:S=>g.mutate({id:b.id,status:S}),children:[e.jsx(Os,{className:"h-7 text-xs w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"pending",children:"Pending"}),e.jsx(mt,{value:"contacted",children:"Contacted"}),e.jsx(mt,{value:"approved",children:"Approved"}),e.jsx(mt,{value:"signed",children:"Signed"}),e.jsx(mt,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(zs,{value:b.incentive_status||"pending",onValueChange:S=>g.mutate({id:b.id,incentive_status:S}),children:[e.jsx(Os,{className:"h-7 text-xs w-[100px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"pending",children:"Unpaid"}),e.jsx(mt,{value:"paid",children:"Paid"}),e.jsx(mt,{value:"n/a",children:"N/A"})]})]})]})]})},b.id)})}),e.jsx(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),x.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"First Name *"}),e.jsx(ke,{required:!0,value:i.first_name,onChange:b=>l(N=>({...N,first_name:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Name"}),e.jsx(ke,{value:i.last_name,onChange:b=>l(N=>({...N,last_name:b.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(ke,{type:"email",value:i.email,onChange:b=>l(N=>({...N,email:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(ke,{value:i.phone,onChange:b=>l(N=>({...N,phone:b.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Current Brokerage"}),e.jsx(ke,{value:i.current_brokerage,onChange:b=>l(N=>({...N,current_brokerage:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(ur,{value:i.notes,onChange:b=>l(N=>({...N,notes:b.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:x.isPending,children:"Submit"})]})]})]})})]})}function tgt({brokerageId:s}){const{toast:t}=Ea(),r=es(),[n,a]=k.useState(!1),{data:i}=gt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:x,error:g}=await H.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(g)throw g;return x}}),{data:l=[]}=gt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:x,error:g}=await H.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(g)throw g;return x}}),o=Lt({mutationFn:async x=>{const{error:g}=await H.from("brokerages").update({recruit_form_enabled:x}).eq("id",s);if(g)throw g},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=Lt({mutationFn:async({id:x,status:g})=>{const{error:v}=await H.from("recruit_interest_submissions").update({status:g}).eq("id",x);if(v)throw v},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,h=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},m=x=>x==="contacted"||x==="converted"?"bg-green-500/10 text-green-600":x==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Enable Public Form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow agents to express interest in joining via a public link"})]}),e.jsx(br,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:x=>o.mutate(x)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx(G,{size:"sm",variant:"outline",onClick:h,children:n?e.jsx(Hn,{className:"h-3.5 w-3.5"}):e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(De,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(nl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(x=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[x.first_name," ",x.last_name]}),e.jsx(Ge,{variant:"outline",className:m(x.status),children:x.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[x.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qs,{className:"h-3 w-3"}),x.email]}),x.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),x.phone]}),x.current_brokerage&&e.jsxs("span",{children:["From: ",x.current_brokerage]}),x.experience_years&&e.jsxs("span",{children:[x.experience_years,"yr exp"]})]}),x.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',x.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Ss(new Date(x.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(zs,{value:x.status,onValueChange:g=>c.mutate({id:x.id,status:g}),children:[e.jsx(Os,{className:"h-7 text-xs w-[110px]",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"new",children:"New"}),e.jsx(mt,{value:"contacted",children:"Contacted"}),e.jsx(mt,{value:"converted",children:"Converted"}),e.jsx(mt,{value:"dismissed",children:"Dismissed"})]})]})]},x.id))})})]})]})}function sgt({brokerageId:s}){const{toast:t}=Ea(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState({prospect_id:"",title:"",description:"",due_date:Ss(Hl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=k.useState("pending"),{data:d=[]}=gt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:P,error:D}=await H.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(D)throw D;return P}}),{data:h=[],isLoading:m}=gt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const P=d.map(z=>z.id);if(!P.length)return[];const{data:D,error:B}=await H.from("recruit_follow_ups").select("*").in("prospect_id",P).order("due_date");if(B)throw B;return D},enabled:d.length>0}),x=Object.fromEntries(d.map(P=>[P.id,P])),g=Lt({mutationFn:async P=>{const{data:{user:D}}=await H.auth.getUser();if(!D)throw new Error("Not authenticated");const{error:B}=await H.from("recruit_follow_ups").insert({prospect_id:P.prospect_id,assigned_to:D.id,title:P.title,description:P.description||null,due_date:new Date(P.due_date).toISOString()});if(B)throw B},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Ss(Hl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:P=>t({title:"Error",description:P.message,variant:"destructive"})}),v=Lt({mutationFn:async({id:P,completed:D})=>{const{error:B}=await H.from("recruit_follow_ups").update({completed_at:D?new Date().toISOString():null}).eq("id",P);if(B)throw B},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),j=h.filter(P=>o==="pending"?!P.completed_at:o==="completed"?!!P.completed_at:!0),b=j.filter(P=>!P.completed_at&&Xv(new Date(P.due_date))&&!qu(new Date(P.due_date))),N=j.filter(P=>!P.completed_at&&qu(new Date(P.due_date))),S=j.filter(P=>!P.completed_at&&!Xv(new Date(P.due_date))&&!qu(new Date(P.due_date))),T=j.filter(P=>!!P.completed_at),A=P=>{const D=x[P.prospect_id],B=!P.completed_at&&Xv(new Date(P.due_date))&&!qu(new Date(P.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Ei,{checked:!!P.completed_at,onCheckedChange:z=>v.mutate({id:P.id,completed:z}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${P.completed_at?"line-through text-muted-foreground":""}`,children:P.title}),P.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:P.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[D&&e.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[D.first_name," ",D.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${B?"text-destructive font-medium":""}`,children:[B?e.jsx(Hi,{className:"h-3 w-3"}):e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(P.due_date),"MMM d, h:mm a")]}),P.is_automated&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},P.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(P=>e.jsxs(G,{size:"sm",variant:o===P?"default":"outline",onClick:()=>c(P),className:"capitalize text-xs",children:[P," ",P==="pending"&&b.length+N.length+S.length>0&&`(${b.length+N.length+S.length})`]},P))}),e.jsxs(G,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Ws,{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(Hi,{className:"h-3.5 w-3.5"})," Overdue (",b.length,")"]}),b.map(A)]}),o!=="completed"&&N.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Today (",N.length,")"]}),N.map(A)]}),o!=="completed"&&S.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(rn,{className:"h-3.5 w-3.5"})," Upcoming (",S.length,")"]}),S.map(A)]}),o!=="pending"&&T.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Hn,{className:"h-3.5 w-3.5"})," Completed (",T.length,")"]}),T.map(A)]}),j.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(js,{children:e.jsx(bs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:P=>{P.preventDefault(),g.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Prospect *"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",required:!0,value:i.prospect_id,onChange:P=>l(D=>({...D,prospect_id:P.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(P=>e.jsxs("option",{value:P.id,children:[P.first_name," ",P.last_name]},P.id))]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Task *"}),e.jsx(ke,{required:!0,value:i.title,onChange:P=>l(D=>({...D,title:P.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Details"}),e.jsx(ur,{value:i.description,onChange:P=>l(D=>({...D,description:P.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Due Date *"}),e.jsx(ke,{type:"datetime-local",required:!0,value:i.due_date,onChange:P=>l(D=>({...D,due_date:P.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:g.isPending,children:"Schedule"})]})]})]})})]})}const F6s=[{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 rgt({brokerageId:s}){const{toast:t}=Ea(),r=es(),[n,a]=k.useState(null),{data:i,isLoading:l}=gt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:b,error:N}=await H.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(N)throw N;return b}}),[o,c]=k.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:F6s,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=Lt({mutationFn:async()=>{const b={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:N}=await H.from("recruit_landing_page_settings").update(b).eq("id",o.id);if(N)throw N}else{const{error:N}=await H.from("recruit_landing_page_settings").insert(b);if(N)throw N}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),h=async(b,N)=>{const S=b.name.split(".").pop(),T=`${s}/${N}-${Date.now()}.${S}`,{error:A}=await H.storage.from("recruit-landing").upload(T,b);if(A)throw A;const{data:{publicUrl:P}}=H.storage.from("recruit-landing").getPublicUrl(T);return P},m=async(b,N)=>{var T;const S=(T=b.target.files)==null?void 0:T[0];if(S){a(N);try{const A=await h(S,N);c(P=>({...P,[N]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},x=async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){a("gallery");try{const T=await h(N,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,T]})),t({title:"Gallery image added!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}},g=async(b,N)=>{var T;const S=(T=b.target.files)==null?void 0:T[0];if(S){a(`testimonial-${N}`);try{const A=await h(S,`testimonial-${N}`);c(P=>{const D=[...P.testimonials];return D[N]={...D[N],photo_url:A},{...P,testimonials:D}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:v}=gt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:b,error:N}=await H.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(N)throw N;return b}}),j=`https://bestbrokerage.relevelup.com/join-brokerage/${(v==null?void 0:v.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(v==null?void 0:v.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:j}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Branding"})}),e.jsx(De,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="logo_url",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),n==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:b=>c(N=>({...N,primary_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ke,{value:o.primary_color,onChange:b=>c(N=>({...N,primary_color:b.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:b=>c(N=>({...N,accent_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ke,{value:o.accent_color,onChange:b=>c(N=>({...N,accent_color:b.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(ke,{value:o.hero_headline,onChange:b=>c(N=>({...N,hero_headline:b.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Subtext"}),e.jsx(ur,{value:o.hero_subtext,onChange:b=>c(N=>({...N,hero_subtext:b.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),n==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"hero_image_url")})]}),o.hero_image_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,hero_image_url:null})),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,benefits:[...b.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.benefits.map((b,N)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Su,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(ke,{value:b.icon,onChange:S=>{const T=[...o.benefits];T[N]={...b,icon:S.target.value},c(A=>({...A,benefits:T}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ke,{value:b.title,onChange:S=>{const T=[...o.benefits];T[N]={...b,title:S.target.value},c(A=>({...A,benefits:T}))},placeholder:"Benefit title"}),e.jsx(ke,{value:b.description,onChange:S=>{const T=[...o.benefits];T[N]={...b,description:S.target.value},c(A=>({...A,benefits:T}))},placeholder:"Short description"})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(S=>({...S,benefits:S.benefits.filter((T,A)=>A!==N)})),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},N)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Testimonials"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,testimonials:[...b.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.testimonials.map((b,N)=>{var S;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((S=b.name)==null?void 0:S[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:n===`testimonial-${N}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:T=>g(T,N)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ke,{value:b.name,onChange:T=>{const A=[...o.testimonials];A[N]={...b,name:T.target.value},c(P=>({...P,testimonials:A}))},placeholder:"Name"}),e.jsx(ke,{value:b.role,onChange:T=>{const A=[...o.testimonials];A[N]={...b,role:T.target.value},c(P=>({...P,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(ur,{value:b.quote,onChange:T=>{const A=[...o.testimonials];A[N]={...b,quote:T.target.value},c(P=>({...P,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(T=>({...T,testimonials:T.testimonials.filter((A,P)=>P!==N)})),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},N)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{size:"sm",variant:"outline",asChild:!0,disabled:n==="gallery",children:e.jsxs("span",{children:[e.jsx(fl,{className:"h-3.5 w-3.5 mr-1"}),n==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x})]})]}),e.jsx(De,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((b,N)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b,alt:`Gallery ${N+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(G,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(S=>({...S,gallery_images:S.gallery_images.filter((T,A)=>A!==N)})),children:e.jsx(yr,{className:"h-3 w-3"})})]},N))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Application Form Style"}),e.jsxs(zs,{value:o.form_style,onValueChange:b=>c(N=>({...N,form_style:b})),children:[e.jsx(Os,{className:"mt-1.5",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(mt,{value:"multi_step",children:"Multi-Step Wizard — 3-step soft CTA (recommended)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Multi-step wizards convert ~30% better than single long forms."})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(he,{children:"Show Confidentiality Badges"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Adds "100% Confidential" + "No spam" trust signals around the form.'})]})]}),e.jsx(br,{checked:o.confidential_messaging,onCheckedChange:b=>c(N=>({...N,confidential_messaging:b}))})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(QA,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(br,{checked:o.calculator_enabled,onCheckedChange:b=>c(N=>({...N,calculator_enabled:b}))})]}),o.calculator_enabled&&e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Calculator Headline"}),e.jsx(ke,{value:o.calculator_config.headline||"",onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,headline:b.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subtext"}),e.jsx(ke,{value:o.calculator_config.subtext||"",onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,subtext:b.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(ke,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,commission_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(ke,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,cap_amount:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(ke,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,post_cap_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(ke,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,monthly_fee:parseFloat(b.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(ke,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,transaction_fee:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm",children:"Capture email at end of calculator"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After seeing results, agents can request a full breakdown via email."})]}),e.jsx(br,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,show_email_capture:b}}))})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(S3,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(br,{checked:o.lead_magnet_enabled,onCheckedChange:b=>c(N=>({...N,lead_magnet_enabled:b}))})]}),o.lead_magnet_enabled&&e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Title"}),e.jsx(ke,{value:o.lead_magnet_config.title||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,title:b.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Description"}),e.jsx(ur,{rows:2,value:o.lead_magnet_config.description||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,description:b.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Button Text"}),e.jsx(ke,{value:o.lead_magnet_config.button_text||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,button_text:b.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ke,{value:o.lead_magnet_config.pdf_url||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,pdf_url:b.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),n==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){a("lead_magnet_pdf");try{const T=await h(N,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:T}})),t({title:"PDF uploaded!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(B6s,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function B6s({brokerageId:s}){const{data:t=[]}=gt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:r,error:n}=await H.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(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(De,{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:[Ss(new Date(r.created_at),"MMM d, yyyy h:mm a")," · via ",r.source]})]})},r.id))})})]})}function z6s(s){if(!s)return"—";const t=Math.floor(s/60),r=s%60;return t>0?`${t}m ${r}s`:`${r}s`}function $6s({video:s}){return s.cta_clicked_at?e.jsx(Ge,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Ge,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Draft"]})}function ngt({brokerageId:s}){const{data:t=[],isLoading:r}=M6s(s),{data:n=[]}=Wxt(s),a=P6s(),i=L6s(),l=Gxt(),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState({title:"",script_text:"",category:"general"}),g=t.filter(S=>{var A,P,D,B;return o?`${((A=S.prospect)==null?void 0:A.first_name)||""} ${((P=S.prospect)==null?void 0:P.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((B=(D=S.video)==null?void 0:D.title)==null?void 0:B.toLowerCase().includes(o.toLowerCase())):!0}),v={total:t.length,sent:t.filter(S=>S.sent_at).length,viewed:t.filter(S=>S.view_count>0).length,ctaClicked:t.filter(S=>S.cta_clicked_at).length},j=k.useCallback(S=>{if(!S)return;const T=`${window.location.origin}/recruit-video/${S}`;navigator.clipboard.writeText(T),ue.success("Share link copied")},[]),b=k.useCallback((S,T)=>{l.mutate({id:S,sent_via:T})},[l]),N=()=>{!m.title.trim()||!m.script_text.trim()||a.mutate({brokerage_id:s,...m},{onSuccess:()=>{x({title:"",script_text:"",category:"general"}),h(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:sn,color:"text-primary"},{label:"Sent",value:v.sent,icon:Zr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:jn,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:Mn,color:"text-emerald-500"}].map(S=>e.jsx(Ne,{children:e.jsxs(De,{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 ${S.color}`,children:e.jsx(S.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:S.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.label})]})]})},S.label))}),e.jsxs(Rn,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"videos",children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Xt,{value:"scripts",children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Xt,{value:"analytics",children:[e.jsx(ao,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(as,{value:"videos",children:e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or title...",value:o,onChange:S=>c(S.target.value),className:"pl-9"})]})]})}),e.jsx(De,{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"})}):g.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(sn,{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:g.map(S=>{var T,A,P,D,B,z;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:[(T=S.video)!=null&&T.thumbnail_url?e.jsx("img",{src:S.video.thumbnail_url,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(sn,{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:z6s(((A=S.video)==null?void 0:A.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:[(P=S.prospect)==null?void 0:P.first_name," ",(D=S.prospect)==null?void 0:D.last_name]}),e.jsx($6s,{video:S})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((B=S.video)==null?void 0:B.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(S.created_at),"MMM d, yyyy"),((z=S.prospect)==null?void 0:z.current_brokerage)&&` · ${S.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(S.share_token),title:"Copy share link",children:e.jsx(Ra,{className:"h-4 w-4"})}),!S.sent_at&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>b(S.id,"email"),title:"Mark as sent",children:e.jsx(Zr,{className:"h-4 w-4"})}),S.share_token&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${S.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Yr,{className:"h-4 w-4"})})]})]},S.id)})})})]})}),e.jsx(as,{value:"scripts",children:e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(zt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(vs,{open:d,onOpenChange:h,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:m.title,onChange:S=>x(T=>({...T,title:S.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Category"}),e.jsxs(zs,{value:m.category,onValueChange:S=>x(T=>({...T,category:S})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:qSe.map(S=>e.jsx(mt,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Script"}),e.jsx(ur,{value:m.script_text,onChange:S=>x(T=>({...T,script_text:S.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(G,{onClick:N,disabled:!m.title.trim()||!m.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(De,{children:n.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:n.map(S=>{var A;const T=((A=qSe.find(P=>P.value===S.category))==null?void 0:A.label)||S.category;return e.jsx(Ne,{className:"relative group",children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] mb-2",children:T}),e.jsx("h4",{className:"font-medium text-sm",children:S.title})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(S.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:S.script_text}),S.is_global&&e.jsx(Ge,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},S.id)})})})]})}),e.jsx(as,{value:"analytics",children:e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(De,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.viewed*100):0,color:"bg-emerald-500"}].map(S=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:S.label}),e.jsxs("span",{className:"font-medium",children:[S.count," (",S.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${S.color} rounded-full transition-all`,style:{width:`${S.pct}%`}})})]},S.label))}),t.filter(S=>S.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(S=>S.view_count>0).sort((S,T)=>T.view_count-S.view_count).slice(0,5).map(S=>{var T,A;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:[(T=S.prospect)==null?void 0:T.first_name," ",(A=S.prospect)==null?void 0:A.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(jn,{className:"h-3.5 w-3.5"})," ",S.view_count]}),S.cta_clicked_at&&e.jsx(Mn,{className:"h-4 w-4 text-emerald-500"})]})]},S.id)})})]})]})]})})]})]})}function agt({brokerageId:s}){const{toast:t}=Ea(),r=es(),{stages:n,prospects:a}=zz(s),[i,l]=k.useState(!1),[o,c]=k.useState({title:"",target_count:"10",target_stage_id:"",period_start:Ss(new Date,"yyyy-MM-dd"),period_end:Ss(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:h}=gt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:v,error:j}=await H.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(j)throw j;return v}}),m=Lt({mutationFn:async v=>{const{data:{user:j}}=await H.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:b}=await H.from("recruit_goals").insert({brokerage_id:s,title:v.title,target_count:parseInt(v.target_count),target_stage_id:v.target_stage_id||null,period_start:v.period_start,period_end:v.period_end,created_by:j.id});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),x=Lt({mutationFn:async v=>{const{error:j}=await H.from("recruit_goals").delete().eq("id",v);if(j)throw j},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),g=v=>{const j=n.find(N=>N.id===v.target_stage_id);return{count:a.filter(N=>$y(new Date(N.created_at),{start:new Date(v.period_start),end:new Date(v.period_end)})?v.target_stage_id?N.stage_id===v.target_stage_id:!0:!1).length,stage:j}};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs(G,{size:"sm",onClick:()=>l(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(Ne,{className:"py-12 text-center",children:[e.jsx(zd,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(v=>{const{count:j,stage:b}=g(v),N=Math.min(100,j/v.target_count*100),S=$y(new Date,{start:new Date(v.period_start),end:new Date(v.period_end)});return e.jsxs(Ne,{className:S?"":"opacity-60",children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{className:"text-sm",children:v.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(v.period_start),"MMM d")," – ",Ss(new Date(v.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S?e.jsx(Ge,{className:"text-[10px]",children:"Active"}):e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>x.mutate(v.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{className:"space-y-2",children:[b&&e.jsxs(Ge,{variant:"outline",className:"text-[10px]",style:{borderColor:b.color,color:b.color},children:["Stage: ",b.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:j}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",v.target_count]})]}),e.jsx(ri,{value:N,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[N.toFixed(0),"% complete"]})]})]},v.id)})}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),m.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Goal Title *"}),e.jsx(ke,{required:!0,value:o.title,onChange:v=>c(j=>({...j,title:v.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Target Count *"}),e.jsx(ke,{type:"number",min:"1",required:!0,value:o.target_count,onChange:v=>c(j=>({...j,target_count:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:v=>c(j=>({...j,target_stage_id:v.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),n.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Start Date"}),e.jsx(ke,{type:"date",required:!0,value:o.period_start,onChange:v=>c(j=>({...j,period_start:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"End Date"}),e.jsx(ke,{type:"date",required:!0,value:o.period_end,onChange:v=>c(j=>({...j,period_end:v.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:m.isPending,children:"Create Goal"})]})]})]})})]})}const U6s={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function igt({email:s,mergeValues:t=U6s,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(js,{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(Ge,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,h)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${h===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:h===l?"Selected":h===0?"Primary":`Alt ${h}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},h))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function gMe({brokerageId:s}){const t=es(),[r,n]=k.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:a}=gt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:c,error:d}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(d)throw d;return c}}),{data:i}=gt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:c,error:d}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(d)throw d;return c}});k.useEffect(()=>{a?n({...a,merge_fields:a.merge_fields||{city:"",broker_name:""}}):i&&n(c=>({...c,merge_fields:{...c.merge_fields,brokerage_name:i.name,city:i.city||""}}))},[a,i]);const l=Lt({mutationFn:async()=>{const c={brokerage_id:s,sender_name:r.sender_name,sender_email:r.sender_email,reply_to_email:r.reply_to_email||null,merge_fields:r.merge_fields,updated_at:new Date().toISOString()};if(a!=null&&a.id){const{error:d}=await H.from("brokerage_recruit_settings").update(c).eq("id",a.id);if(d)throw d}else{const{error:d}=await H.from("brokerage_recruit_settings").insert(c);if(d)throw d}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ue.success("Recruiting email settings saved!")},onError:c=>ue.error(c.message)}),o=(c,d)=>{n(h=>({...h,merge_fields:{...h.merge_fields,[c]:d}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Sender Display Name"}),e.jsx(ke,{value:r.sender_name,onChange:c=>n({...r,sender_name:c.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Sender Email Address"}),e.jsx(ke,{value:r.sender_email,onChange:c=>n({...r,sender_email:c.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(ke,{value:r.reply_to_email,onChange:c=>n({...r,reply_to_email:c.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(a0,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Sender Verification (Amazon SES)"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-4",children:["Verify any email address with AWS so recruiting emails can be sent from that address (e.g. your own broker email, instead of ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-muted text-[10px]",children:"recruiting@relevelup.com"}),")."]}),e.jsx(Fxt,{brokerageId:s,onVerifiedSelect:c=>{n(d=>({...d,sender_email:c})),ue.success(`Sender set to ${c}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(ke,{value:r.merge_fields.brokerage_name||"",onChange:c=>o("brokerage_name",c.target.value),placeholder:(i==null?void 0:i.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"{{city}}"}),e.jsx(ke,{value:r.merge_fields.city||"",onChange:c=>o("city",c.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(ke,{value:r.merge_fields.sender_name||"",onChange:c=>o("sender_name",c.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(G,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const q6s=m0.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",Zc(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()}}}),aHe=[{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 Vh({onClick:s,active:t,disabled:r,icon:n,tooltip:a}){return e.jsxs(hc,{children:[e.jsx(mc,{asChild:!0,children:e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:r,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(n,{className:"h-4 w-4"})})}),e.jsx(Wl,{side:"bottom",className:"text-xs",children:a})]})}function V6s({content:s,onChange:t}){const r=cTe({extensions:[uTe.configure({heading:{levels:[1,2,3]}}),q6s,_Te.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),wTe.configure({types:["heading","paragraph"]}),jTe,fmt],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(A_,{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(Vh,{onClick:()=>r.chain().focus().toggleBold().run(),active:r.isActive("bold"),icon:qj,tooltip:"Bold"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleItalic().run(),active:r.isActive("italic"),icon:Kj,tooltip:"Italic"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleUnderline().run(),active:r.isActive("underline"),icon:xM,tooltip:"Underline"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleStrike().run(),active:r.isActive("strike"),icon:IO,tooltip:"Strikethrough"}),e.jsx(po,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleHeading({level:1}).run(),active:r.isActive("heading",{level:1}),icon:rM,tooltip:"Heading 1"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleHeading({level:2}).run(),active:r.isActive("heading",{level:2}),icon:nM,tooltip:"Heading 2"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleHeading({level:3}).run(),active:r.isActive("heading",{level:3}),icon:dO,tooltip:"Heading 3"}),e.jsx(po,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleBulletList().run(),active:r.isActive("bulletList"),icon:lm,tooltip:"Bullet List"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleOrderedList().run(),active:r.isActive("orderedList"),icon:r0,tooltip:"Numbered List"}),e.jsx(Vh,{onClick:()=>r.chain().focus().toggleBlockquote().run(),active:r.isActive("blockquote"),icon:z3,tooltip:"Blockquote"}),e.jsx(Vh,{onClick:()=>r.chain().focus().setHorizontalRule().run(),icon:qv,tooltip:"Divider"}),e.jsx(po,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Vh,{onClick:()=>r.chain().focus().setTextAlign("left").run(),active:r.isActive({textAlign:"left"}),icon:y3,tooltip:"Align Left"}),e.jsx(Vh,{onClick:()=>r.chain().focus().setTextAlign("center").run(),active:r.isActive({textAlign:"center"}),icon:g3,tooltip:"Align Center"}),e.jsx(Vh,{onClick:()=>r.chain().focus().setTextAlign("right").run(),active:r.isActive({textAlign:"right"}),icon:v3,tooltip:"Align Right"}),e.jsx(po,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Vh,{onClick:n,active:r.isActive("link"),icon:xo,tooltip:"Insert Link"}),e.jsx(po,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Vh,{onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),icon:s2,tooltip:"Undo"}),e.jsx(Vh,{onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),icon:e2,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{r&&r.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(gM,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Vd,{align:"end",className:"w-56",children:aHe.map(i=>e.jsxs(Da,{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(oTe,{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:"}),aHe.map(i=>e.jsx(Ge,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-[10px] px-2 py-0.5",onClick:()=>a(i.key),children:`{{${i.key}}}`},i.key))]})})]})}):null}function H6s({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(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-5 w-5 text-primary"}),r," — Engagement Stats"]}),e.jsx(Fr,{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(Zr,{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(nq,{icon:Qs,color:"text-blue-500",label:"Total Sent",value:n.sent.toLocaleString()}),e.jsx(nq,{icon:jn,color:"text-amber-500",label:"Opens",value:`${n.opened.toLocaleString()}`,sub:`${n.openRate.toFixed(1)}% open rate`}),e.jsx(nq,{icon:Dd,color:"text-green-500",label:"Clicks",value:`${n.clicked.toLocaleString()}`,sub:`${n.clickRate.toFixed(1)}% click rate`}),e.jsx(nq,{icon:od,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(cn,{className:"h-3 w-3"})," Last sent: ",Ss(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(Ne,{className:"overflow-hidden",children:e.jsxs(De,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Qs,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(jn,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Dd,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(od,{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 nq({icon:s,color:t,label:r,value:n,sub:a}){return e.jsx(Ne,{children:e.jsx(De,{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 ogt(s){return gt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:r}=await H.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 iHe={cold:{icon:Ev,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:n_,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:xc,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function lgt({brokerageId:s}){var Ee,$e,Se,ze;const{user:t}=As(),r=es(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState("editor"),[j,b]=k.useState(null),[N,S]=k.useState(null),{data:T={}}=ogt(s),[A,P]=k.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:D}=gt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Te,error:ye}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(ye)throw ye;return Te}}),{data:B}=gt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Te,error:ye}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ye)throw ye;return Te}}),z={first_name:"Sarah",brokerage_name:((Ee=B==null?void 0:B.merge_fields)==null?void 0:Ee.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:(($e=B==null?void 0:B.merge_fields)==null?void 0:$e.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Se=B==null?void 0:B.merge_fields)==null?void 0:Se.sender_name)||(B==null?void 0:B.sender_name)||"Your Name"},F=Te=>Te.replace(/\{\{first_name\}\}/g,z.first_name).replace(/\{\{brokerage_name\}\}/g,z.brokerage_name).replace(/\{\{city\}\}/g,z.city).replace(/\{\{sender_name\}\}/g,z.sender_name),{data:$=[],isLoading:X}=gt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Te,error:ye}=await H.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ye)throw ye;return Te}}),{data:K={}}=gt({queryKey:["recruit-campaign-emails",s],enabled:$.length>0,queryFn:async()=>{const Te=$.map(rt=>rt.id),{data:ye,error:ct}=await H.from("recruit_campaign_emails").select("*").in("campaign_id",Te).order("email_number");if(ct)throw ct;const ve={};return ye.forEach(rt=>{ve[rt.campaign_id]||(ve[rt.campaign_id]=[]),ve[rt.campaign_id].push(rt)}),ve}}),Q=Object.values(K).flat().map(Te=>Te.id),{data:Y=[]}=gt({queryKey:["recruit-subject-overrides",s],enabled:Q.length>0,queryFn:async()=>{const{data:Te,error:ye}=await H.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ye)throw ye;return Te}}),ne={};Y.forEach(Te=>{ne[Te.campaign_email_id]=Te.selected_subject_index});const de=Lt({mutationFn:async({campaignEmailId:Te,selectedIndex:ye})=>{const{error:ct}=await H.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Te,selected_subject_index:ye,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(ct)throw ct},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ue.success("Subject line updated for your brokerage")},onError:Te=>ue.error(Te.message)}),ce=Lt({mutationFn:async Te=>{const{error:ye}=await H.from("recruit_campaign_emails").update({title:Te.title,subject_line:Te.subject_line,subject_line_options:Te.subject_line_options,body_html:Te.body_html,body_text:Te.body_text,delay_days:Te.delay_days,updated_at:new Date().toISOString()}).eq("id",Te.id);if(ye)throw ye},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email template saved!"),l(null)},onError:Te=>ue.error(Te.message)}),ae=Lt({mutationFn:async()=>{const Te=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ye,error:ct}=await H.from("recruit_campaigns").insert({name:A.name,slug:Te,description:A.description||null,theme:A.theme||null,goal:A.goal||null,primary_cta:A.primary_cta||"Learn more",warmth_level:A.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:A.sender_name||null,sender_email:A.sender_email||null,reply_to_email:A.reply_to_email||null,is_active:!0,sort_order:$.length+1}).select().single();if(ct)throw ct;const ve=[{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:rt}=await H.from("recruit_campaign_emails").insert(ve.map(Re=>({campaign_id:ye.id,...Re,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(rt)throw rt;return ye},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Campaign created with 4 starter emails!"),x(!1),P({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Te=>ue.error(Te.message)}),ie=Lt({mutationFn:async Te=>{const{error:ye}=await H.from("recruit_campaigns").update({name:Te.name,description:Te.description,theme:Te.theme,goal:Te.goal,primary_cta:Te.primary_cta,warmth_level:Te.warmth_level,sender_name:Te.sender_name,sender_email:Te.sender_email,reply_to_email:Te.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Te.id);if(ye)throw ye},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),ue.success("Campaign settings saved!"),b(null)},onError:Te=>ue.error(Te.message)}),me=Lt({mutationFn:async Te=>{var Qe,Ke;const{data:ye}=await H.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Te).order("email_number",{ascending:!1}).limit(1),ct=((Qe=ye==null?void 0:ye[0])==null?void 0:Qe.email_number)??0,ve=((Ke=ye==null?void 0:ye[0])==null?void 0:Ke.delay_days)??0,rt=ct+1,{error:Re}=await H.from("recruit_campaign_emails").insert({campaign_id:Te,email_number:rt,title:`Email ${rt}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:ve+7,is_active:!0});if(Re)throw Re},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email added to campaign!")},onError:Te=>ue.error(Te.message)}),oe=Lt({mutationFn:async Te=>{const{error:ye}=await H.from("recruit_campaigns").delete().eq("id",Te);if(ye)throw ye},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Campaign deleted")},onError:Te=>ue.error(Te.message)}),ge=Lt({mutationFn:async Te=>{const{error:ye}=await H.from("recruit_campaign_emails").delete().eq("id",Te);if(ye)throw ye},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email removed from campaign")},onError:Te=>ue.error(Te.message)}),be=Lt({mutationFn:async({emailId:Te,delay_days:ye})=>{const{error:ct}=await H.from("recruit_campaign_emails").update({delay_days:ye,updated_at:new Date().toISOString()}).eq("id",Te);if(ct)throw ct},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Send delay updated")},onError:Te=>ue.error(Te.message)});if(X)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 Oe=$.filter(Te=>!Te.brokerage_id),Me=$.filter(Te=>Te.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-1.5",children:[e.jsx(lo,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(G,{size:"sm",onClick:()=>x(!0),className:"gap-1.5",children:[e.jsx(Ws,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(Ne,{className:"border-primary/20 bg-primary/5",children:e.jsx(De,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(jr,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(lo,{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(fO,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Me.map(Te=>Pe(Te,!0))})]}),Oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Oe.map(Te=>Pe(Te,!1))})]}),$.length===0&&e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Qs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(G,{className:"mt-4",onClick:()=>x(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(H6s,{open:!!N,onClose:()=>S(null),campaignName:(N==null?void 0:N.name)||"",stat:N&&T[N.id]||null}),o&&e.jsx(igt,{email:o,mergeValues:z,selectedSubjectIndex:ne[o.id],onClose:()=>c(null)}),e.jsx(vs,{open:!!i,onOpenChange:Te=>!Te&&l(null),children:e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Wj,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Fr,{children:i==null?void 0:i.title})]}),i&&e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(ke,{value:i.title,onChange:Te=>l({...i,title:Te.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(ke,{type:"number",min:0,max:90,value:i.delay_days,onChange:Te=>l({...i,delay_days:parseInt(Te.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(ke,{value:i.subject_line,onChange:Te=>l({...i,subject_line:Te.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Alternative Subject Lines ",e.jsx("span",{className:"text-muted-foreground font-normal normal-case",children:"(one per line, for A/B testing)"})]}),e.jsx(ur,{value:((ze=i.subject_line_options)==null?void 0:ze.join(` `))||"",onChange:Te=>l({...i,subject_line_options:Te.target.value.split(` `).filter(Boolean)}),rows:2,className:"text-sm resize-none"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(Rn,{value:g,onValueChange:Te=>v(Te),children:e.jsxs(Dn,{className:"h-7",children:[e.jsx(Xt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Xt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),g==="editor"?e.jsx(V6s,{content:i.body_html,onChange:Te=>l({...i,body_html:Te})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[z.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:[z.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:F(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:F(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(G,{size:"sm",onClick:()=>ce.mutate(i),disabled:ce.isPending,className:"gap-1.5",children:[e.jsx(ql,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(vs,{open:m,onOpenChange:x,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Fr,{children:"Build your own recruiting email sequence with custom sender settings."})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(ke,{value:A.name,onChange:Te=>P({...A,name:Te.target.value}),placeholder:"e.g. Q2 Agent Outreach"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(zs,{value:A.warmth_level,onValueChange:Te=>P({...A,warmth_level:Te}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(mt,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(mt,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(ke,{value:A.primary_cta,onChange:Te=>P({...A,primary_cta:Te.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Description"}),e.jsx(ur,{value:A.description,onChange:Te=>P({...A,description:Te.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ke,{value:A.goal,onChange:Te=>P({...A,goal:Te.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(bx,{children:[e.jsx(_x,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(so,{className:"h-3.5 w-3.5"})]})}),e.jsxs(wx,{className:"space-y-3 pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use brokerage defaults."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Name"}),e.jsx(ke,{value:A.sender_name,onChange:Te=>P({...A,sender_name:Te.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Email"}),e.jsx(ke,{value:A.sender_email,onChange:Te=>P({...A,sender_email:Te.target.value}),placeholder:"e.g. recruiting@send.relevelup.com"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ke,{value:A.reply_to_email,onChange:Te=>P({...A,reply_to_email:Te.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(G,{className:"w-full",disabled:!A.name.trim()||ae.isPending,onClick:()=>ae.mutate(),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(vs,{open:!!j,onOpenChange:Te=>!Te&&b(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(lo,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Fr,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),j&&e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(ke,{value:j.name,onChange:Te=>b({...j,name:Te.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(zs,{value:j.warmth_level,onValueChange:Te=>b({...j,warmth_level:Te}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"cold",children:"❄️ Cold"}),e.jsx(mt,{value:"warm",children:"☀️ Warm"}),e.jsx(mt,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ke,{value:j.goal||"",onChange:Te=>b({...j,goal:Te.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Qs,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Name"}),e.jsx(ke,{value:j.sender_name||"",onChange:Te=>b({...j,sender_name:Te.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Email"}),e.jsx(ke,{value:j.sender_email||"",onChange:Te=>b({...j,sender_email:Te.target.value}),placeholder:"Uses brokerage default"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ke,{value:j.reply_to_email||"",onChange:Te=>b({...j,reply_to_email:Te.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(G,{className:"w-full",onClick:()=>ie.mutate(j),disabled:ie.isPending,children:[e.jsx(ql,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(vs,{open:d,onOpenChange:h,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Default Recruiting Email Settings"}),e.jsx(Fr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(gMe,{brokerageId:s})]})})]});function Pe(Te,ye){const ct=iHe[Te.warmth_level]||iHe.cold,ve=ct.icon,rt=K[Te.id]||[],Re=n===Te.id,Qe=!!(Te.sender_name||Te.sender_email||Te.reply_to_email),Ke=T[Te.id];return e.jsxs(Ne,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Ot,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Re?null:Te.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${ct.bg} flex items-center justify-center`,children:e.jsx(ve,{className:`h-5 w-5 ${ct.color}`})}),e.jsxs("div",{children:[e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[Te.name,e.jsx(Ge,{variant:Te.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Te.is_active?"Active":"Draft"}),ye&&e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Qe&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(Qs,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Nr,{className:"text-xs mt-0.5",children:Te.theme||Te.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ce=>{Ce.stopPropagation(),b({...Te})},children:e.jsx(lo,{className:"h-4 w-4 text-muted-foreground"})}),ye&&e.jsx(G,{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.")&&oe.mutate(Te.id)},children:e.jsx(yr,{className:"h-4 w-4"})}),Ke&&Ke.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Qs,{className:"h-2.5 w-2.5"})," ",Ke.sent.toLocaleString()]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Ke.openRate.toFixed(1)}% open rate`,children:[e.jsx(jn,{className:"h-2.5 w-2.5"})," ",Ke.opened.toLocaleString()," (",Ke.openRate.toFixed(0),"%)"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Ke.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Dd,{className:"h-2.5 w-2.5"})," ",Ke.clicked.toLocaleString()," (",Ke.clickRate.toFixed(1),"%)"]})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ce=>{Ce.stopPropagation(),S(Te)},title:"View detailed engagement stats",children:[e.jsx(ao,{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(Qs,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[rt.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Re?e.jsx(xp,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(so,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Re&&e.jsxs(De,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:Te.goal||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Primary CTA"}),e.jsx("p",{className:"mt-0.5",children:Te.primary_cta||"—"})]})]}),Qe&&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(Qs,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Te.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Te.sender_name]}),Te.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Te.sender_email]}),Te.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Te.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:rt.map((Ce,nt)=>{var $t,lt;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ntit.stopPropagation(),onBlur:it=>{const Nt=parseInt(it.target.value)||0;Nt!==Ce.delay_days&&be.mutate({emailId:Ce.id,delay_days:Nt})},onKeyDown:it=>{it.key==="Enter"&&it.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{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: ",F((($t=Ce.subject_line_options)==null?void 0:$t.length)>0&&Ce.subject_line_options[ne[Ce.id]??0]||Ce.subject_line)]})]}),((lt=Ce.subject_line_options)==null?void 0:lt.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(zs,{value:String(ne[Ce.id]??0),onValueChange:it=>de.mutate({campaignEmailId:Ce.id,selectedIndex:parseInt(it)}),children:[e.jsx(Os,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(Us,{placeholder:"Choose subject line"})}),e.jsx(Fs,{children:Ce.subject_line_options.map((it,Nt)=>e.jsxs(mt,{value:String(Nt),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Nt===0?"Primary":`Alt ${Nt}`,":"]}),F(it)]},Nt))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ce),children:e.jsx(jn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ce}),v("editor")},children:e.jsx(Ta,{className:"h-4 w-4"})}),ye&&rt.length>1&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{confirm("Delete this email from the sequence?")&&ge.mutate(Ce.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})]})})]},Ce.id)})}),ye&&e.jsxs(G,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>me.mutate(Te.id),disabled:me.isPending,children:[e.jsx(Ws,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Te.id)}}const oHe={active:{icon:Ho,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:cm,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:mi,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Mc,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},lHe={sent:{icon:Qs,color:"text-blue-500"},opened:{icon:jn,color:"text-amber-500"},clicked:{icon:Dd,color:"text-green-500"},failed:{icon:od,color:"text-destructive"}};function cgt({brokerageId:s}){var Ee,$e,Se,ze,Te;const{user:t}=As(),r=es(),[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(new Set),[d,h]=k.useState("assignments"),[m,x]=k.useState(null),[g,v]=k.useState(""),[j,b]=k.useState("all"),[N,S]=k.useState("all"),{data:T={}}=gt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:ye,error:ct}=await H.from("recruit_campaign_emails").select("*").order("email_number");if(ct)throw ct;const ve={};return(ye??[]).forEach(rt=>{ve[rt.campaign_id]||(ve[rt.campaign_id]=[]),ve[rt.campaign_id].push(rt)}),ve}}),{data:A}=gt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(ct)throw ct;return ye}}),{data:P}=gt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:ye,error:ct}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ct)throw ct;return ye}}),{data:D=[]}=gt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:ye,error:ct}=await H.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ct)throw ct;return ye}}),B={};D.forEach(ye=>{B[ye.campaign_email_id]=ye.selected_subject_index});const z={first_name:((Ee=m==null?void 0:m.prospect)==null?void 0:Ee.first_name)||"Sarah",brokerage_name:(($e=P==null?void 0:P.merge_fields)==null?void 0:$e.brokerage_name)||(A==null?void 0:A.name)||"Your Brokerage",city:((Se=P==null?void 0:P.merge_fields)==null?void 0:Se.city)||(A==null?void 0:A.city)||"Your City",sender_name:((ze=P==null?void 0:P.merge_fields)==null?void 0:ze.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},F=ye=>{const ct=T[ye.campaign_id]||[],ve=ye.current_email_number+1;return ct.find(rt=>rt.email_number===ve)||null},{data:$=[],isLoading:X}=gt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let ct=[],ve=0;for(;;){const{data:rt,error:Re}=await H.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(ve,ve+1e3-1);if(Re)throw Re;if(ct=ct.concat(rt??[]),!rt||rt.length<1e3)break;ve+=1e3}return ct}}),{data:K=[]}=gt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:ye,error:ct}=await H.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(ct)throw ct;return ye}}),{data:Q=[]}=gt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:ye,error:ct}=await H.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(ct)throw ct;return ye}}),{data:Y=[]}=gt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let ct=[],ve=0;for(;;){const{data:rt,error:Re}=await H.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(ve,ve+1e3-1);if(Re)throw Re;if(ct=ct.concat(rt??[]),!rt||rt.length<1e3)break;ve+=1e3}return ct}}),ne=new Set($.map(ye=>`${ye.prospect_id}-${ye.campaign_id}`)),de=Lt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const ye=new Date,ct=Array.from(o).filter(rt=>!ne.has(`${rt}-${i}`)).map(rt=>({prospect_id:rt,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:ye.toISOString(),started_at:ye.toISOString()}));if(ct.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:ve}=await H.from("recruit_campaign_assignments").insert(ct);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ue.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:ye=>ue.error(ye.message)}),ce=Lt({mutationFn:async({id:ye,newStatus:ct})=>{const{error:ve}=await H.from("recruit_campaign_assignments").update({status:ct,updated_at:new Date().toISOString()}).eq("id",ye);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ue.success("Assignment updated")}}),ae=Lt({mutationFn:async()=>{const{data:ye,error:ct}=await H.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(ct)throw ct;return ye},onSuccess:ye=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),r.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ue.success(`Wave sent! ${ye.sent} emails delivered, ${ye.skipped} skipped, ${ye.failed} failed`)},onError:ye=>ue.error(`Send failed: ${ye.message}`)}),ie=$.filter(ye=>ye.status==="active").length;$.filter(ye=>ye.status==="completed").length;const me=$.filter(ye=>ye.status==="active"&&ye.next_send_at&&new Date(ye.next_send_at)<=new Date).length,{data:oe={}}=ogt(s),ge=$.reduce((ye,ct)=>ye+Math.max(0,ct.current_email_number||0),0),be=Object.values(oe).reduce((ye,ct)=>ye+ct.opened,0),Oe=Object.values(oe).reduce((ye,ct)=>ye+ct.clicked,0);Object.values(oe).reduce((ye,ct)=>ye+ct.failed,0);const Me=ge>0?Math.round(be/ge*100):0,Pe=ge>0?Oe/ge*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:[me>0&&e.jsxs(G,{variant:"outline",onClick:()=>ae.mutate(),disabled:ae.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(Xu,{className:"h-4 w-4 mr-1"}),ae.isPending?"Sending...":`Send Next Wave (${me})`]}),e.jsxs(G,{onClick:()=>a(!0),children:[e.jsx(Zr,{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(Ne,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(fr,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:$.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ho,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ie}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Qs,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ge.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(jn,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Me,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",be.toLocaleString(),")"]})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Dd,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Pe.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Oe.toLocaleString(),")"]})]})]})})]}),e.jsxs(Rn,{value:d,onValueChange:h,children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"assignments",children:["Active Drips (",ie,")"]}),e.jsxs(Xt,{value:"history",children:["Send History (",ge.toLocaleString(),")"]})]}),e.jsx(as,{value:"assignments",className:"mt-4",children:X?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"})}):$.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Zr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No 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:$.map(ye=>{var Ke,Ce,nt,$t;const ct=oHe[ye.status]||oHe.active,ve=ct.icon,Re=(T[ye.campaign_id]||[]).length||4,Qe=F(ye);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ge,{className:`text-xs ${ct.color} border-0`,children:[e.jsx(ve,{className:"h-3 w-3 mr-1"}),ct.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Ke=ye.prospect)==null?void 0:Ke.first_name," ",(Ce=ye.prospect)==null?void 0:Ce.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(nt=ye.prospect)==null?void 0:nt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[($t=ye.campaign)==null?void 0:$t.name," · Email ",ye.current_email_number,"/",Re,ye.next_send_at&&ye.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(cn,{className:"h-3 w-3 inline"})," Next: ",Ss(new Date(ye.next_send_at),"MMM d, h:mm a"),new Date(ye.next_send_at)<=new Date&&e.jsx(Ge,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Qe&&e.jsx(G,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>x(ye),children:e.jsx(jn,{className:"h-3.5 w-3.5"})}),ye.status==="active"&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:ye.id,newStatus:"paused"}),children:e.jsx(cm,{className:"h-3.5 w-3.5"})}),ye.status==="paused"&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:ye.id,newStatus:"active"}),children:e.jsx(Ho,{className:"h-3.5 w-3.5"})}),(ye.status==="active"||ye.status==="paused")&&e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ce.mutate({id:ye.id,newStatus:"cancelled"}),children:e.jsx(Mc,{className:"h-3.5 w-3.5"})})]})]},ye.id)})})}),e.jsxs(as,{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(zs,{value:j,onValueChange:b,children:[e.jsx(Os,{className:"w-[220px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All campaigns"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All campaigns"}),Q.map(ye=>e.jsx(mt,{value:ye.id,children:ye.name},ye.id))]})]}),e.jsxs(zs,{value:N,onValueChange:S,children:[e.jsx(Os,{className:"w-[160px] h-8 text-xs",children:e.jsx(Us,{placeholder:"All statuses"})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All statuses"}),e.jsx(mt,{value:"sent",children:"Sent (no engagement)"}),e.jsx(mt,{value:"opened",children:"Opened"}),e.jsx(mt,{value:"clicked",children:"Clicked"})]})]}),(j!=="all"||N!=="all")&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{b("all"),S("all")},children:"Clear"})]}),(()=>{var ct;const ye=K.filter(ve=>{var rt;return!(j!=="all"&&((rt=ve.campaign_email)==null?void 0:rt.campaign_id)!==j||N==="opened"&&!ve.opened_at||N==="clicked"&&!ve.clicked_at||N==="sent"&&(ve.opened_at||ve.clicked_at))});return ye.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Qs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:K.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:K.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",ye.length," of ",K.length," recent sends",j!=="all"&&` · ${(ct=Q.find(ve=>ve.id===j))==null?void 0:ct.name}`]}),e.jsx("div",{className:"space-y-1",children:ye.map(ve=>{var Ke,Ce,nt;const rt=lHe[ve.status]||lHe.sent,Re=rt.icon,Qe=(Ke=Q.find($t=>{var lt;return $t.id===((lt=ve.campaign_email)==null?void 0:lt.campaign_id)}))==null?void 0:Ke.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(Re,{className:`h-4 w-4 flex-shrink-0 ${rt.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Ce=ve.prospect)==null?void 0:Ce.first_name," ",(nt=ve.prospect)==null?void 0:nt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",ve.email_number]}),Qe&&e.jsx(Ge,{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:ve.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[ve.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(jn,{className:"h-3 w-3"})," ",Ss(new Date(ve.opened_at),"MMM d")]}),ve.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Dd,{className:"h-3 w-3"})," ",Ss(new Date(ve.clicked_at),"MMM d")]}),e.jsx("span",{children:Ss(new Date(ve.sent_at),"MMM d, h:mm a")})]})]},ve.id)})})]})})()]})]}),e.jsx(vs,{open:n,onOpenChange:ye=>{a(ye),ye||(v(""),c(new Set),l(""))},children:e.jsxs(ys,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-4",children:[e.jsx(bs,{children:"Assign Campaign to Prospects"}),e.jsx(Fr,{children:"Select a campaign and choose which prospects to enroll. The first email will be sent automatically."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 space-y-4 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(zs,{value:i,onValueChange:l,children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Choose a campaign..."})}),e.jsx(Fs,{children:Q.map(ye=>e.jsx(mt,{value:ye.id,children:ye.name},ye.id))})]})]}),i&&(()=>{const ye=g.toLowerCase(),ct=Y.filter(Re=>`${Re.first_name} ${Re.last_name}`.toLowerCase().includes(ye)||Re.email.toLowerCase().includes(ye)),ve=ct.filter(Re=>!ne.has(`${Re.id}-${i}`)),rt=ve.length>0&&ve.every(Re=>o.has(Re.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-sm font-medium",children:"2. Select Prospects"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.size," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:g,onChange:Re=>v(Re.target.value),className:"pl-9 h-9"})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(rt){const Re=new Set(o);ve.forEach(Qe=>Re.delete(Qe.id)),c(Re)}else{const Re=new Set(o);ve.forEach(Qe=>Re.add(Qe.id)),c(Re)}},children:[e.jsx(eO,{className:"h-3.5 w-3.5 mr-1"}),rt?"Deselect All":`Select All (${ve.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:ct.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:g?"No prospects match your search":"No prospects found for this brokerage"}):ct.map(Re=>{const Qe=ne.has(`${Re.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(Ei,{checked:o.has(Re.id),disabled:Qe,onCheckedChange:Ke=>{const Ce=new Set(o);Ke?Ce.add(Re.id):Ce.delete(Re.id),c(Ce)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Re.first_name," ",Re.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Re.email})]}),Qe&&e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Re.id)})}),ct.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",ct.length," of ",Y.length," prospects",ve.length0&&e.jsx(Ne,{className:"bg-primary/5 border-primary/20",children:e.jsxs(De,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(Te=Q.find(ye=>ye.id===i))==null?void 0:Te.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• First email sends immediately · follow-ups every 7 days"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• You can pause or cancel any assignment at any time"})]})})]}),e.jsxs(on,{className:"px-6 py-4 border-t",children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>de.mutate(),disabled:de.isPending||!i||o.size===0,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),de.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),m&&(()=>{const ye=F(m);return ye?e.jsx(igt,{email:ye,mergeValues:z,selectedSubjectIndex:B[ye.id],onClose:()=>x(null)}):null})()]})}function dgt({brokerageId:s}){const t=es(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=k.useRef(!1),{data:d,isLoading:h}=gt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:b,error:N}=await H.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(N)throw N;return b},enabled:!!s});k.useEffect(()=>{if(d){if(c.current){c.current=!1;return}n(d.map(b=>({id:b.id,name:b.name,color:b.color,sort_order:b.sort_order}))),i([]),o(!1)}},[d]);const m=Lt({mutationFn:async()=>{for(const S of a){const{error:T}=await H.from("recruit_pipeline_stages").delete().eq("id",S);if(T)throw T}const b=r.filter(S=>S.id&&!S.isNew),N=r.filter(S=>!S.id||S.isNew);for(const S of b){const{error:T}=await H.from("recruit_pipeline_stages").update({name:S.name,color:S.color,sort_order:S.sort_order}).eq("id",S.id);if(T)throw T}if(N.length>0){const{error:S}=await H.from("recruit_pipeline_stages").insert(N.map(T=>({brokerage_id:s,name:T.name,color:T.color,sort_order:T.sort_order})));if(S)throw S}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ue.success("Pipeline stages saved!"),o(!1)},onError:b=>ue.error(b.message)}),x=(b,N,S)=>{n(T=>T.map((A,P)=>P===b?{...A,[N]:S}:A)),o(!0)},g=()=>{const b=r.length>0?Math.max(...r.map(N=>N.sort_order)):0;n(N=>[...N,{name:"",color:"#6366f1",sort_order:b+1,isNew:!0}]),o(!0)},v=b=>{const N=r[b];N.id&&!N.isNew&&i(S=>[...S,N.id]),n(S=>S.filter((T,A)=>A!==b)),o(!0)},j=(b,N)=>{const S=b+N;if(S<0||S>=r.length)return;const T=[...r];[T[b],T[S]]=[T[S],T[b]],T.forEach((A,P)=>A.sort_order=P+1),n(T),o(!0)};return h?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:r.map((b,N)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>j(N,-1),disabled:N===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>j(N,1),disabled:N===r.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Su,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:b.color,onChange:S=>x(N,"color",S.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(ke,{value:b.name,onChange:S=>x(N,"name",S.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:N+1}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(N),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id||`new-${N}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:g,className:"gap-1",children:[e.jsx(Ws,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(G,{size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,className:"gap-1",children:[e.jsx(ql,{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 G6s({brokerageId:s}){const{data:t=[],isLoading:r}=gt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:n,error:a}=await H.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(q3,{className:"h-5 w-5 text-muted-foreground"}),"Unsubscribed Prospects"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Prospects who opted out of recruiting emails. They will not receive further outreach."})]}),e.jsxs(Ge,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(q3,{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(Ne,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(zt,{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(Qs,{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(rn,{className:"h-3 w-3"}),n.unsubscribed_at&&Ss(new Date(n.unsubscribed_at),"MMM d, yyyy")]})]})}),n.unsubscribe_reason&&e.jsx(De,{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 W6s({brokerageId:s,trigger:t,initialProspectId:r,open:n,onOpenChange:a}){const[i,l]=k.useState(!1),o=n??i,c=a??l,[d,h]=k.useState("pick-recipients"),[m,x]=k.useState(new Set(r?[r]:[])),[g,v]=k.useState("all"),[j,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(""),[P,D]=k.useState(0),[B,z]=k.useState(0),[F,$]=k.useState(""),[X,K]=k.useState(""),[Q,Y]=k.useState(null),{prospects:ne,stages:de}=zz(s),ce=Hxt(),ae=O_(),{data:ie=[]}=gt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Se,error:ze}=await H.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(ze)throw ze;return Se??[]},enabled:o&&d==="pick-video"}),me=k.useCallback(()=>{h("pick-recipients"),x(new Set(r?[r]:[])),v("all"),b(""),S(null),A(""),D(0),z(0),$(""),K(""),Y(null)},[r]),oe=Se=>{!Se&&(d==="uploading"||d==="processing"||d==="sending")||(c(Se),Se||setTimeout(me,200))},ge=k.useMemo(()=>ne.filter(Se=>{if(!Se.email||g!=="all"&&Se.stage_id!==g)return!1;if(j){const ze=j.toLowerCase();if(!`${Se.first_name} ${Se.last_name??""}`.toLowerCase().includes(ze)&&!Se.email.toLowerCase().includes(ze))return!1}return!0}),[ne,g,j]),be=Se=>{x(ze=>{const Te=new Set(ze);return Te.has(Se)?Te.delete(Se):Te.add(Se),Te})},Oe=()=>{m.size===ge.length?x(new Set):x(new Set(ge.map(Se=>Se.id)))},Me=k.useCallback(async(Se,ze)=>{h("uploading");try{const Te=`Recruiting blast (${m.size} recipients)`,{videoId:ye,libraryId:ct}=await sT(Te),{uploadUrl:ve,apiKey:rt}=await rT(ye),Re=new XMLHttpRequest;Re.upload.onprogress=Nt=>{Nt.lengthComputable&&D(Nt.loaded/Nt.total*100)},await new Promise((Nt,Ft)=>{Re.onload=()=>Re.status>=200&&Re.status<300?Nt():Ft(new Error("Upload failed")),Re.onerror=()=>Ft(new Error("Upload failed")),Re.open("PUT",ve),Re.setRequestHeader("AccessKey",rt),Re.send(Se)}),h("processing");const Qe=`https://iframe.mediadelivery.net/embed/${ct}/${ye}`;let Ke=0;const Ce=Date.now(),nt=9e4;for(;Ke<4&&(await new Promise(Ft=>setTimeout(Ft,3e3)),!(Date.now()-Ce>nt));){const Nt=await u1(ye);if(Ke=Nt.status,z(Nt.encodeProgress||0),Ke===5||Ke===6)throw new Error("Video processing failed")}const $t=await u1(ye),lt=($t.storageSize||Se.size)/(1024*1024),it=await ae.mutateAsync({bunny_video_id:ye,playback_url:$t.directPlayUrl||Qe,thumbnail_url:$t.thumbnailUrl,preview_url:$t.previewUrl||null,duration_seconds:$t.length||ze,file_size_mb:lt,title:Te,status:Ke>=4?"ready":"processing",touch_type:"recruiting"});S(it.id),A(Te),h("compose")}catch(Te){ue.error((Te==null?void 0:Te.message)||"Failed to upload video"),h("pick-video")}},[m.size,ae]),Pe=k.useCallback(async()=>{if(!(!N||m.size===0)){h("sending");try{const Se=[];for(const ye of m){const ct=await ce.mutateAsync({prospect_id:ye,video_id:N,brokerage_id:s,message:X||void 0});Se.push(ct.id)}const{data:ze,error:Te}=await H.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Se,brokerage_id:s,subject_override:F||void 0,message_override:X||void 0}});if(Te)throw new Error(Te.message);Y({sent:(ze==null?void 0:ze.sent)??0,total:(ze==null?void 0:ze.total)??Se.length}),h("done"),ue.success(`Sent ${(ze==null?void 0:ze.sent)??0} of ${(ze==null?void 0:ze.total)??Se.length} videos`)}catch(Se){ue.error((Se==null?void 0:Se.message)||"Failed to send"),h("compose")}}},[N,m,s,X,F,ce]),Ee=m.size,$e=ne.filter(Se=>!Se.email).length;return e.jsxs(vs,{open:o,onOpenChange:oe,children:[t&&e.jsx(Ni,{asChild:!0,children:t}),e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Ee>0&&e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[e.jsx(fr,{className:"h-3 w-3 mr-1"}),Ee," ",Ee===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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search prospects...",value:j,onChange:Se=>b(Se.target.value),className:"pl-9"})]}),e.jsxs(zs,{value:g,onValueChange:v,children:[e.jsx(Os,{className:"w-48",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"all",children:"All stages"}),de.map(Se=>e.jsx(mt,{value:Se.id,children:Se.name},Se.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Oe,className:"hover:underline",children:[m.size===ge.length&&ge.length>0?"Deselect all":"Select all"," ","(",ge.length,")"]}),$e>0&&e.jsxs("span",{children:[$e," prospect(s) hidden — no email on file"]})]}),e.jsx(ti,{className:"flex-1 border rounded-md",children:ge.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:ge.map(Se=>{const ze=m.has(Se.id),Te=de.find(ye=>ye.id===Se.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(Ei,{checked:ze,onCheckedChange:()=>be(Se.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:[Se.first_name," ",Se.last_name]}),Te&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",style:{borderColor:Te.color,color:Te.color},children:Te.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Se.email," ",Se.current_brokerage&&`· ${Se.current_brokerage}`]})]})]},Se.id)})})}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>oe(!1),children:"Cancel"}),e.jsx(G,{disabled:Ee===0,onClick:()=>h("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rn,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Dn,{className:"self-start",children:[e.jsxs(Xt,{value:"record",children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Xt,{value:"library",children:[e.jsx(I3,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(as,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Nh,{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 ",Ee," ",Ee===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(G,{onClick:()=>h("record"),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(as,{value:"library",className:"flex-1 overflow-auto",children:ie.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:ie.map(Se=>e.jsxs("button",{onClick:()=>{S(Se.id),A(Se.title||"Untitled"),h("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:Se.thumbnail_url?e.jsx("img",{src:Se.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sn,{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:Se.title||"Untitled"})})]},Se.id))})})]}),e.jsx(on,{children:e.jsx(G,{variant:"outline",onClick:()=>h("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(xL,{maxDurationSeconds:600,onRecordingComplete:Me}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>h("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(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(ri,{value:d==="uploading"?P:B,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?P:B),"%"]})]}),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(Mn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:T})," selected · sending to ",e.jsx("strong",{children:Ee})," recipient",Ee===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(ke,{value:F,onChange:Se=>$(Se.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(ur,{value:X,onChange:Se=>K(Se.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>h("pick-video"),children:"Back"}),e.jsxs(G,{onClick:Pe,disabled:!N||Ee===0,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send to ",Ee," ",Ee===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 ",Ee," recipient",Ee===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Q&&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 ${Q.sent===Q.total?"bg-primary/10":"bg-muted"}`,children:Q.sent===Q.total?e.jsx(Mn,{className:"h-8 w-8 text-primary"}):e.jsx(Hi,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Q.sent," of ",Q.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(G,{onClick:()=>oe(!1),children:"Done"})]})]})]})}function K6s(){var o;const[s,t]=k.useState(""),[r,n]=k.useState("board"),{data:a=[],isLoading:i}=gt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await H.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(_s,{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(_s,{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(zs,{value:l,onValueChange:t,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:a.map(c=>e.jsx(mt,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(W6s,{brokerageId:l,trigger:e.jsxs(G,{size:"sm",className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(Rn,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Dn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Xt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Xt,{value:"contacts",children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Xt,{value:"video-outreach",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Xt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"interest",children:"Interest Form"}),e.jsx(Xt,{value:"landing-page",children:"Landing Page"}),e.jsx(Xt,{value:"goals",children:"Goals"}),e.jsx(Xt,{value:"metrics",children:"Metrics"}),e.jsx(Xt,{value:"templates",children:"Email Templates"}),e.jsxs(Xt,{value:"campaigns",children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Xt,{value:"drip-assignments",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Xt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Xt,{value:"email-settings",children:[e.jsx(lo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Xt,{value:"pipeline-stages",children:[e.jsx(H3,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Xt,{value:"unsubscribed",children:[e.jsx(q3,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(as,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(G,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("board"),children:[e.jsx(Sf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(G,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("table"),children:[e.jsx(pM,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(Zxt,{brokerageId:l}):e.jsx(hfe,{brokerageId:l})]}),e.jsx(as,{value:"contacts",children:e.jsx(hfe,{brokerageId:l})}),e.jsx(as,{value:"video-outreach",children:e.jsx(ngt,{brokerageId:l})}),e.jsx(as,{value:"follow-ups",children:e.jsx(sgt,{brokerageId:l})}),e.jsx(as,{value:"referrals",children:e.jsx(egt,{brokerageId:l})}),e.jsx(as,{value:"interest",children:e.jsx(tgt,{brokerageId:l})}),e.jsx(as,{value:"landing-page",children:e.jsx(rgt,{brokerageId:l})}),e.jsx(as,{value:"goals",children:e.jsx(agt,{brokerageId:l})}),e.jsx(as,{value:"metrics",children:e.jsx(Xxt,{brokerageId:l})}),e.jsx(as,{value:"templates",children:e.jsx(Qxt,{brokerageId:l})}),e.jsx(as,{value:"campaigns",children:e.jsx(lgt,{brokerageId:l})}),e.jsx(as,{value:"drip-assignments",children:e.jsx(cgt,{brokerageId:l})}),e.jsx(as,{value:"activity",children:e.jsx(Jxt,{brokerageId:l})}),e.jsx(as,{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(gMe,{brokerageId:l})]})}),e.jsx(as,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(dgt,{brokerageId:l})})}),e.jsx(as,{value:"unsubscribed",children:e.jsx(G6s,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function Y6s(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:r}=As(),[n,a]=k.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(_s,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(_s,{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(zs,{value:i,onValueChange:r,children:[e.jsxs(Os,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Us,{placeholder:"Select brokerage"})]}),e.jsx(Fs,{children:s.map(o=>e.jsx(mt,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(Rn,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Dn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Xt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Xt,{value:"contacts",children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Xt,{value:"video-outreach",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Xt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"interest",children:"Interest Form"}),e.jsx(Xt,{value:"landing-page",children:"Landing Page"}),e.jsx(Xt,{value:"goals",children:"Goals"}),e.jsx(Xt,{value:"metrics",children:"Metrics"}),e.jsx(Xt,{value:"templates",children:"Email Templates"}),e.jsxs(Xt,{value:"campaigns",children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Xt,{value:"drip-assignments",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Xt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Xt,{value:"email-settings",children:[e.jsx(lo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Xt,{value:"pipeline-stages",children:[e.jsx(H3,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(as,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(G,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(Sf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(G,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(pM,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(Zxt,{brokerageId:i}):e.jsx(hfe,{brokerageId:i})]}),e.jsx(as,{value:"contacts",children:e.jsx(hfe,{brokerageId:i})}),e.jsx(as,{value:"video-outreach",children:e.jsx(ngt,{brokerageId:i})}),e.jsx(as,{value:"follow-ups",children:e.jsx(sgt,{brokerageId:i})}),e.jsx(as,{value:"referrals",children:e.jsx(egt,{brokerageId:i})}),e.jsx(as,{value:"interest",children:e.jsx(tgt,{brokerageId:i})}),e.jsx(as,{value:"landing-page",children:e.jsx(rgt,{brokerageId:i})}),e.jsx(as,{value:"goals",children:e.jsx(agt,{brokerageId:i})}),e.jsx(as,{value:"metrics",children:e.jsx(Xxt,{brokerageId:i})}),e.jsx(as,{value:"templates",children:e.jsx(Qxt,{brokerageId:i})}),e.jsx(as,{value:"campaigns",children:e.jsx(lgt,{brokerageId:i})}),e.jsx(as,{value:"drip-assignments",children:e.jsx(cgt,{brokerageId:i})}),e.jsx(as,{value:"activity",children:e.jsx(Jxt,{brokerageId:i})}),e.jsx(as,{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(gMe,{brokerageId:i})]})}),e.jsx(as,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(dgt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function Z6s(){const[s,t]=k.useState(""),{data:r,isLoading:n}=gt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await H.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await H.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await H.from("brokerage_content_categories").select("id, brokerage_id"),h=c||[],m=d||[],x=o.map(g=>{const v=h.filter(N=>N.brokerage_id===g.id),j=m.filter(N=>N.brokerage_id===g.id),b=v.length>0?v.reduce((N,S)=>S.created_at>N?S.created_at:N,v[0].created_at):null;return{brokerage_id:g.id,brokerage_name:g.name,total_items:v.length,videos:v.filter(N=>N.content_type==="video").length,pdfs:v.filter(N=>N.content_type==="pdf").length,links:v.filter(N=>N.content_type==="link"||N.content_type==="canva_link").length,events:v.filter(N=>N.content_type==="event").length,graphics:v.filter(N=>N.content_type==="graphic").length,latest_item_date:b,categories:j.length}});return x.sort((g,v)=>v.total_items-g.total_items),x}}),a=(r||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(_s,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rh,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(De,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(De,{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(Ne,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(zt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(De,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(Ne,{children:e.jsx(De,{className:"p-0",children:e.jsxs(On,{children:[e.jsx(Fn,{children:e.jsxs(qs,{children:[e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{className:"text-center",children:"Total"}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(sn,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(rl,{className:"h-3 w-3"})," Links"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pd,{className:"h-3 w-3"})," Events"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(fl,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Tt,{className:"text-center",children:"Categories"}),e.jsx(Tt,{children:"Last Upload"})]})}),e.jsx(Bn,{children:n?e.jsx(qs,{children:e.jsx(ft,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(qs,{children:e.jsx(ft,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(qs,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(ft,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(ft,{className:"text-center",children:o.total_items>0?e.jsx(Ge,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ft,{className:"text-center",children:o.videos||"–"}),e.jsx(ft,{className:"text-center",children:o.pdfs||"–"}),e.jsx(ft,{className:"text-center",children:o.links||"–"}),e.jsx(ft,{className:"text-center",children:o.events||"–"}),e.jsx(ft,{className:"text-center",children:o.graphics||"–"}),e.jsx(ft,{className:"text-center",children:o.categories||"–"}),e.jsx(ft,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}function X6s(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 Q6s=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function f2(s){const t=[];for(let r=0,n=s.length;rWp||s.height>Wp)&&(s.width>Wp&&s.height>Wp?s.width>s.height?(s.height*=Wp/s.width,s.width=Wp):(s.width*=Wp/s.height,s.height=Wp):s.width>Wp?(s.height*=Wp/s.width,s.width=Wp):(s.width*=Wp/s.height,s.height=Wp))}function ffe(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 rDs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function nDs(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),rDs(a)}const vp=(s,t)=>{if(s instanceof t)return!0;const r=Object.getPrototypeOf(s);return r===null?!1:r.constructor.name===t.name||vp(r,t)};function aDs(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function iDs(s,t){return ugt(t).map(r=>{const n=s.getPropertyValue(r),a=s.getPropertyPriority(r);return`${r}: ${n}${a?" !important":""};`}).join(" ")}function oDs(s,t,r,n){const a=`.${s}:${t}`,i=r.cssText?aDs(r):iDs(r,n);return document.createTextNode(`${a}{${i}}`)}function cHe(s,t,r,n){const a=window.getComputedStyle(s,r),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Q6s();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(oDs(l,r,a,n)),t.appendChild(o)}function lDs(s,t,r){cHe(s,t,":before",r),cHe(s,t,":after",r)}const dHe="application/font-woff",uHe="image/jpeg",cDs={woff:dHe,woff2:dHe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:uHe,jpeg:uHe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function dDs(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function yMe(s){const t=dDs(s).toLowerCase();return cDs[t]||""}function uDs(s){return s.split(/,/)[1]}function VSe(s){return s.search(/^(data:)/)!==-1}function hDs(s,t){return`data:${t};base64,${s}`}async function mgt(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 L_e={};function mDs(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 vMe(s,t,r){const n=mDs(s,t,r.includeQueryParams);if(L_e[n]!=null)return L_e[n];r.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await mgt(s,r.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),uDs(o)));a=hDs(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 L_e[n]=a,a}async function fDs(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):ffe(t)}async function pDs(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 ffe(o)}const r=s.poster,n=yMe(r),a=await vMe(r,n,t);return ffe(a)}async function xDs(s,t){var r;try{if(!((r=s==null?void 0:s.contentDocument)===null||r===void 0)&&r.body)return await sye(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function gDs(s,t){return vp(s,HTMLCanvasElement)?fDs(s):vp(s,HTMLVideoElement)?pDs(s,t):vp(s,HTMLIFrameElement)?xDs(s,t):s.cloneNode(fgt(s))}const yDs=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",fgt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function vDs(s,t,r){var n,a;if(fgt(t))return t;let i=[];return yDs(s)&&s.assignedNodes?i=f2(s.assignedNodes()):vp(s,HTMLIFrameElement)&&(!((n=s.contentDocument)===null||n===void 0)&&n.body)?i=f2(s.contentDocument.body.childNodes):i=f2(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||vp(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>sye(o,r)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function bDs(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):ugt(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`),vp(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 _Ds(s,t){vp(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),vp(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function wDs(s,t){if(vp(s,HTMLSelectElement)){const r=t,n=Array.from(r.children).find(a=>s.value===a.getAttribute("value"));n&&n.setAttribute("selected","")}}function jDs(s,t,r){return vp(t,Element)&&(bDs(s,t,r),lDs(s,t,r),_Ds(s,t),wDs(s,t)),t}async function NDs(s,t){const r=s.querySelectorAll?s.querySelectorAll("use"):[];if(r.length===0)return s;const n={};for(let i=0;igDs(n,t)).then(n=>vDs(s,n,t)).then(n=>jDs(s,n,t)).then(n=>NDs(n,t))}const pgt=/url\((['"]?)([^'"]+?)\1\)/g,kDs=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,SDs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function CDs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function TDs(s){const t=[];return s.replace(pgt,(r,n,a)=>(t.push(a),r)),t.filter(r=>!VSe(r))}async function EDs(s,t,r,n,a){try{const i=r?X6s(t,r):t,l=yMe(t);let o;return a||(o=await vMe(i,l,n)),s.replace(CDs(t),`$1${o}$3`)}catch{}return s}function ADs(s,{preferredFontFormat:t}){return t?s.replace(SDs,r=>{for(;;){const[n,,a]=kDs.exec(r)||[];if(!a)return"";if(a===t)return`src: ${n};`}}):s}function xgt(s){return s.search(pgt)!==-1}async function ggt(s,t,r){if(!xgt(s))return s;const n=ADs(s,r);return TDs(n).reduce((i,l)=>i.then(o=>EDs(o,l,t,r)),Promise.resolve(n))}async function JE(s,t,r){var n;const a=(n=t.style)===null||n===void 0?void 0:n.getPropertyValue(s);if(a){const i=await ggt(a,null,r);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function MDs(s,t){await JE("background",s,t)||await JE("background-image",s,t),await JE("mask",s,t)||await JE("-webkit-mask",s,t)||await JE("mask-image",s,t)||await JE("-webkit-mask-image",s,t)}async function IDs(s,t){const r=vp(s,HTMLImageElement);if(!(r&&!VSe(s.src))&&!(vp(s,SVGImageElement)&&!VSe(s.href.baseVal)))return;const n=r?s.src:s.href.baseVal,a=await vMe(n,yMe(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 PDs(s,t){const n=f2(s.childNodes).map(a=>ygt(a,t));await Promise.all(n).then(()=>s)}async function ygt(s,t){vp(s,Element)&&(await MDs(s,t),await IDs(s,t),await PDs(s,t))}function LDs(s,t){const{style:r}=s;t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.width&&(r.width=`${t.width}px`),t.height&&(r.height=`${t.height}px`);const n=t.style;return n!=null&&Object.keys(n).forEach(a=>{r[a]=n[a]}),s}const hHe={};async function mHe(s){let t=hHe[s];if(t!=null)return t;const n=await(await fetch(s)).text();return t={url:s,cssText:n},hHe[s]=t,t}async function fHe(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),mgt(o,t.fetchRequestInit,({result:c})=>(r=r.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>r)}function pHe(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 DDs(s,t){const r=[],n=[];return s.forEach(a=>{if("cssRules"in a)try{f2(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=mHe(c).then(h=>fHe(h,t)).then(h=>pHe(h).forEach(m=>{try{a.insertRule(m,m.startsWith("@import")?o+=1:a.cssRules.length)}catch(x){console.error("Error inserting rule from remote css",{rule:m,error:x})}})).catch(h=>{console.error("Error loading remote css",h.toString())});n.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&n.push(mHe(a.href).then(o=>fHe(o,t)).then(o=>pHe(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{f2(a.cssRules||[]).forEach(i=>{r.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),r))}function RDs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>xgt(t.style.getPropertyValue("src")))}async function ODs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const r=f2(s.ownerDocument.styleSheets),n=await DDs(r,t);return RDs(n)}function vgt(s){return s.trim().replace(/["']/g,"")}function FDs(s){const t=new Set;function r(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(i=>{t.add(vgt(i))}),Array.from(n.children).forEach(i=>{i instanceof HTMLElement&&r(i)})}return r(s),t}async function BDs(s,t){const r=await ODs(s,t),n=FDs(s);return(await Promise.all(r.filter(i=>n.has(vgt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return ggt(i.cssText,l,t)}))).join(` `)}async function zDs(s,t){const r=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await BDs(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 $Ds(s,t={}){const{width:r,height:n}=hgt(s,t),a=await sye(s,t,!0);return await zDs(a,t),await ygt(a,t),LDs(a,t),await nDs(a,r,n)}async function UDs(s,t={}){const{width:r,height:n}=hgt(s,t),a=await $Ds(s,t),i=await ffe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||tDs(),d=t.canvasWidth||r,h=t.canvasHeight||n;return l.width=d*c,l.height=h*c,t.skipAutoScale||sDs(l),l.style.width=`${d}`,l.style.height=`${h}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,l.width,l.height)),o.drawImage(i,0,0,l.width,l.height),l}async function qDs(s,t={}){return(await UDs(s,t)).toDataURL()}const dP=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),rye={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},aq={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},VDs=({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})]})]}),bgt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=rye[t],h=[s.bedrooms?`${s.bedrooms} Bed`:null,s.bathrooms?`${s.bathrooms} Bath`:null,s.sqft?`${s.sqft.toLocaleString()} Sq Ft`:null].filter(Boolean).join(" • ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(10,10,30,0.3) 0%, rgba(10,10,30,0.85) 100%)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",padding:l.w*.06},children:[e.jsx("div",{children:e.jsx("div",{style:{display:"inline-block",background:"linear-gradient(135deg, #C9A84C, #E8D48B)",color:"#1A1A2E",padding:`${l.w*.012}px ${l.w*.035}px`,fontSize:l.w*.032,fontWeight:700,letterSpacing:"0.25em",textTransform:"uppercase"},children:d})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:l.w*.07,fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,textShadow:"0 2px 12px rgba(0,0,0,0.5)"},children:dP(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",dP(s.soldPrice)]}),e.jsx("div",{style:{fontSize:l.w*.028,opacity:.9,marginBottom:l.w*.008},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.7,marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"flex",gap:l.w*.015,fontSize:l.w*.022,letterSpacing:"0.05em",borderTop:"1px solid rgba(201,168,76,0.4)",paddingTop:l.w*.02},children:e.jsx("span",{children:h})}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.02,background:"rgba(201,168,76,0.15)",border:"1px solid rgba(201,168,76,0.4)",padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.024,letterSpacing:"0.1em",display:"inline-block"},children:"SAT & SUN • 1–4 PM"}),e.jsx(VDs,{branding:n,dim:l})]})]})]})});bgt.displayName="LuxuryDarkTemplate";const HDs=({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})]})]}),_gt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var g;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=(g=s.photos)==null?void 0:g[a],d=rye[t],h=r==="instagram-story",m=r==="facebook-post",x=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:m?"row":"column"},children:[e.jsxs("div",{style:{width:m?"55%":"100%",height:m?"100%":h?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:x,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(m?.055:.065),fontWeight:800,lineHeight:1.1,color:x,marginBottom:l.w*.012},children:dP(s.price)}),e.jsx("div",{style:{fontSize:l.w*.026,fontWeight:600,marginBottom:l.w*.006},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.02,color:"#6B7280",marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.03,marginBottom:l.w*.02},children:[s.bedrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bedrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Beds"})]}),s.bathrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bathrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Baths"})]}),s.sqft>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.sqft.toLocaleString()}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Sq Ft"})]})]}),t==="open-house"&&e.jsx("div",{style:{background:`${x}10`,border:`2px solid ${x}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:x,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(HDs,{branding:n,dim:l,accentColor:x})]})]})});_gt.displayName="ModernCleanTemplate";const GDs=({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})]})]}),wgt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var x;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(x=s.photos)==null?void 0:x[a],d=rye[t],h={"just-listed":"linear-gradient(135deg, #059669, #10B981)","just-sold":"linear-gradient(135deg, #7C3AED, #A855F7)","open-house":"linear-gradient(135deg, #2563EB, #3B82F6)","price-drop":"linear-gradient(135deg, #DC2626, #F43F5E)"},m=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background:h[t],padding:`${l.w*.025}px ${l.w*.04}px`,fontSize:l.w*.055,fontWeight:900,letterSpacing:"0.08em",alignSelf:"flex-start",borderRadius:l.w*.01,boxShadow:"0 8px 32px rgba(0,0,0,0.3)",transform:"rotate(-2deg)",marginBottom:l.w*.03},children:d}),e.jsx("div",{style:{flex:1}}),e.jsxs("div",{style:{background:"rgba(0,0,0,0.65)",backdropFilter:"blur(10px)",borderRadius:l.w*.015,padding:l.w*.04},children:[e.jsx("div",{style:{fontSize:l.w*.08,fontWeight:900,lineHeight:1,marginBottom:l.w*.01},children:dP(s.price)}),e.jsx("div",{style:{fontSize:l.w*.028,fontWeight:700,marginBottom:l.w*.005},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.8,marginBottom:l.w*.015},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"inline-block",background:"rgba(255,255,255,0.15)",borderRadius:l.w*.008,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,letterSpacing:"0.08em"},children:m}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:h["open-house"],borderRadius:l.w*.008,padding:`${l.w*.012}px ${l.w*.025}px`,fontSize:l.w*.024,fontWeight:800,display:"inline-block",marginLeft:l.w*.01},children:"SAT & SUN 1–4 PM"}),e.jsx(GDs,{branding:n,dim:l})]})]})]})});wgt.displayName="BoldColorfulTemplate";const WDs=({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})]})]}),jgt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=rye[t],h=r==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection:h?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:h?"100%":"42%",height:h?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:h?2:1},children:[e.jsx("div",{style:{fontSize:l.w*.016,letterSpacing:"0.3em",textTransform:"uppercase",color:"#8B7355",borderBottom:"2px solid #8B7355",paddingBottom:l.w*.01,marginBottom:l.w*.025,display:"inline-block",alignSelf:"flex-start"},children:d}),e.jsx("div",{style:{fontSize:l.w*(h?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:dP(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",dP(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(WDs,{branding:n,dim:l})]}),e.jsxs("div",{style:{width:h?"100%":"58%",height:h?"60%":"100%",position:"relative",overflow:"hidden",order:h?1:2},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:l.w*.02,border:"1px solid rgba(255,255,255,0.4)",pointerEvents:"none"}})]})]})})});jgt.displayName="EditorialTemplate";const KDs=[{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:"📉"}],xHe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(au,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(au,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(ku,{className:"h-4 w-4"})}],YDs=[{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:"📰"}],gHe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),yHe={"luxury-dark":bgt,"modern-clean":_gt,"bold-colorful":wgt,editorial:jgt};function ZDs(){const[s,t]=k.useState(""),[r,n]=k.useState("address"),[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(null),[h,m]=k.useState(0),[x,g]=k.useState("just-listed"),[v,j]=k.useState(["instagram-square"]),[b,N]=k.useState("luxury-dark"),[S,T]=k.useState(!1),[A,P]=k.useState(""),[D,B]=k.useState(""),[z,F]=k.useState(""),[$,X]=k.useState(!1),[K,Q]=k.useState(!1),[Y,ne]=k.useState([]),[de,ce]=k.useState("search"),ae=k.useRef({});k.useEffect(()=>{(async()=>{const{data:{user:$e}}=await H.auth.getUser();if(!$e)return;const{data:Se}=await H.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",$e.id).single();if(Se){P(Se.name||""),F(Se.avatar_url||"");const ze=Se.brokerages;B((ze==null?void 0:ze.name)||"")}})()},[]);const ie=async()=>{var Ee;if(s.trim()){i(!0),o([]);try{const{data:$e,error:Se}=await H.functions.invoke("repliers-mls-search",{body:{searchType:r,query:s.trim()}});if(Se)throw Se;if($e.error)throw new Error($e.error);o($e.listings||[]),((Ee=$e.listings)==null?void 0:Ee.length)===0&&ue.info("No listings found. Try a different search.")}catch($e){ue.error($e.message||"Search failed")}finally{i(!1)}}},me=Ee=>{var $e;d(Ee),m(0),ce("customize"),Ee.soldDate||($e=Ee.status)!=null&&$e.toLowerCase().includes("sold")?g("just-sold"):g("just-listed")},oe=Ee=>{j($e=>$e.includes(Ee)?$e.filter(Se=>Se!==Ee):[...$e,Ee])},ge=k.useCallback(async()=>{if(!(!c||v.length===0)){X(!0),ne([]),ce("generate");try{await new Promise($e=>setTimeout($e,500));const Ee=[];for(const $e of v){const Se=`${b}-${$e}`,ze=ae.current[Se];if(!ze)continue;const Te=aq[$e],ye=await qDs(ze,{width:Te.width,height:Te.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:$e,imageUrl:ye})}ne(Ee),ue.success(`Generated ${Ee.length} social post${Ee.length>1?"s":""}!`)}catch(Ee){ue.error(Ee.message||"Generation failed")}finally{X(!1)}}},[c,v,b,h,S,A,D,z,x]),be=async()=>{if(!(!c||v.length===0)){X(!0),ne([]),ce("generate");try{const Ee={...c,photos:c.photos.length>0?[c.photos[h]]:[]},$e=[];for(const Se of v){const{data:ze,error:Te}=await H.functions.invoke("generate-listing-social-post",{body:{listing:Ee,postType:x,format:Se,branding:S?{enabled:!0,agentName:A,brokerage:D}:{enabled:!1}}});if(Te)throw Te;if(ze.error)throw new Error(ze.error);$e.push({format:Se,imageUrl:ze.imageUrl})}ne($e),ue.success(`Generated ${$e.length} AI post${$e.length>1?"s":""}!`)}catch(Ee){ue.error(Ee.message||"AI generation failed")}finally{X(!1)}}},Oe=()=>K?be():ge(),Me=(Ee,$e)=>{var ze;const Se=document.createElement("a");Se.href=Ee,Se.download=`${((ze=c==null?void 0:c.address)==null?void 0:ze.replace(/\s+/g,"-"))||"listing"}-${x}-${$e}.png`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se)},Pe=c?{listing:c,postType:x,format:"instagram-square",branding:S?{enabled:!0,agentName:A,brokerage:D,agentPhotoUrl:z||void 0}:{enabled:!1},selectedPhotoIndex:h}:null;return e.jsx(_s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(rh,{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:()=>ce("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${de==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(fn,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ce("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${de==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(jr,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(ya,{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 ${de==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(fl,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),de==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(fn,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(sat,{})]}),e.jsx(Nr,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Rn,{value:r,onValueChange:Ee=>n(Ee),children:e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"address",children:[e.jsx(ja,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Xt,{value:"mls",children:[e.jsx(Ah,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:s,onChange:Ee=>t(Ee.target.value),placeholder:r==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&ie()}),e.jsxs(G,{onClick:ie,disabled:a||!s.trim(),children:[a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(fn,{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((Ee,$e)=>{var Se;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>me(Ee),children:e.jsx(De,{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:(Se=Ee.photos)!=null&&Se[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Cn,{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:gHe(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ee.city,", ",Ee.state," ",Ee.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(b3,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(fp,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(pO,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||$e)})})]})]}),de==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(Ne,{className:"lg:col-span-1",children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(zt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(De,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[h],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(G,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ee=>Math.max(0,Ee-1)),disabled:h===0,children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h+1," of ",c.photos.length]}),e.jsx(G,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ee=>Math.min(c.photos.length-1,Ee+1)),disabled:h===c.photos.length-1,children:e.jsx(ya,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:gHe(c.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.city,", ",c.state," ",c.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[c.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),c.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),c.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ce("search"),d(null)},children:[e.jsx(Wv,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(Ne,{className:"lg:col-span-2",children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Nr,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:K?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:K?"Uses AI credits for unique designs":"Instant, no credits used"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Use AI"}),e.jsx(br,{checked:K,onCheckedChange:Q}),K&&e.jsx(Ag,{className:"h-4 w-4 text-purple-500"})]})]}),!K&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:YDs.map(Ee=>e.jsxs("button",{onClick:()=>N(Ee.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${b===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ee.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ee.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ee.description})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:KDs.map(Ee=>e.jsxs("button",{onClick:()=>g(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${x===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",Ee.label]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:xHe.map(Ee=>e.jsxs("button",{onClick:()=>oe(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${v.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Bi,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(br,{checked:S,onCheckedChange:T})]}),S&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[z&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:z,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(ke,{value:A,onChange:Ee=>P(Ee.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(ke,{value:D,onChange:Ee=>B(Ee.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!K&&Pe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:400,height:400*(aq[v[0]||"instagram-square"].height/aq[v[0]||"instagram-square"].width)},children:(()=>{const Ee=yHe[b],$e=v[0]||"instagram-square";return e.jsx(Ee,{...Pe,format:$e})})()})})]}),e.jsx(G,{onClick:Oe,disabled:v.length===0||$,size:"lg",className:"w-full gap-2",children:$?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-5 w-5 animate-spin"})," Generating ",v.length," post",v.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[K?e.jsx(Ag,{className:"h-5 w-5"}):e.jsx(jr,{className:"h-5 w-5"}),"Generate ",v.length," Social Post",v.length>1?"s":"",K&&e.jsx(Ge,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),de==="generate"&&e.jsxs("div",{className:"space-y-4",children:[$&&e.jsx(Ne,{children:e.jsxs(De,{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:K?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),Y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Generated Posts"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>ce("customize"),children:[e.jsx(Wv,{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:Y.map((Ee,$e)=>{const Se=xHe.find(ze=>ze.value===Ee.format);return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.imageUrl,alt:`${Ee.format} social post`,className:"w-full rounded"})}),e.jsxs(De,{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:[Se==null?void 0:Se.icon,e.jsx("span",{className:"text-sm font-medium",children:Se==null?void 0:Se.label})]}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Se==null?void 0:Se.dimensions})]}),e.jsxs(G,{size:"sm",className:"w-full gap-1.5",onClick:()=>Me(Ee.imageUrl,Ee.format),children:[e.jsx(Xa,{className:"h-3.5 w-3.5"})," Download"]})]})]},$e)})})]})]}),de==="generate"&&!K&&c&&Pe&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:v.map(Ee=>{const $e=yHe[b],Se=aq[Ee];return e.jsx("div",{style:{width:Se.width,height:Se.height},children:e.jsx($e,{ref:ze=>{ae.current[`${b}-${Ee}`]=ze},...Pe,format:Ee})},`${b}-${Ee}`)})})]})})}function XDs(){return gt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await H.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function QDs(s){return gt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 JDs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.from("lms_courses").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Ngt(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 eRs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("lms_courses").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function tRs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 sRs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.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 rRs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("lms_modules").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function nRs(){const s=es();return Lt({mutationFn:async t=>{const{data:r,error:n}=await H.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 aRs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.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 iRs(){const s=es();return Lt({mutationFn:async({courseId:t,accessRules:r})=>{const{error:n}=await H.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 H.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function oRs(){return gt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await H.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function lRs(s){return gt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.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 kgt(s){return gt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("lms_progress").select("*").eq("course_id",s);if(r)throw r;return t},enabled:!!s})}function cRs(){const s=es();return Lt({mutationFn:async({courseId:t,moduleId:r,userId:n})=>{const{data:a,error:i}=await H.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 dRs(){const{user:s}=As(),t=vr(),{data:r,isLoading:n}=XDs(),a=JDs(),i=Ngt(),l=eRs(),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[g,v]=k.useState(!0),j=async()=>{if(!(!d.trim()||!s))try{const S=await a.mutateAsync({title:d.trim(),description:m.trim()||void 0,is_sequential:g,created_by:s.id});ue.success("Course created"),c(!1),h(""),x(""),v(!0),t(`/admin/lms/${S.id}`)}catch{ue.error("Failed to create course")}},b=async S=>{try{await i.mutateAsync({id:S.id,is_published:!S.is_published}),ue.success(S.is_published?"Course unpublished":"Course published")}catch{ue.error("Failed to update course")}},N=async S=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(S),ue.success("Course deleted")}catch{ue.error("Failed to delete")}};return e.jsxs(_s,{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(Od,{className:"h-7 w-7 text-primary"}),"LevelUp U — Course Manager"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create and manage training courses for your agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(ao,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(G,{onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsx(Ne,{className:"animate-pulse",children:e.jsxs(Ot,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},S))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(S=>{var D,B;const T=((B=(D=S.modules)==null?void 0:D[0])==null?void 0:B.count)??0,A=S.access||[],P=A.length===0?"No access set":A.some(z=>z.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(Ne,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${S.id}`),children:[e.jsx(Ot,{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(zt,{className:"text-base truncate",children:S.title}),S.description&&e.jsx(Nr,{className:"mt-1 line-clamp-2",children:S.description})]}),e.jsx(Ge,{variant:S.is_published?"default":"secondary",className:"ml-2 shrink-0",children:S.is_published?"Published":"Draft"})]})}),e.jsxs(De,{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(Th,{className:"h-3.5 w-3.5"}),T," module",T!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[S.is_sequential?e.jsx(r0,{className:"h-3.5 w-3.5"}):e.jsx(V3,{className:"h-3.5 w-3.5"}),S.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),P]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(G,{size:"sm",variant:"ghost",onClick:z=>{z.stopPropagation(),b(S)},children:[S.is_published?e.jsx(am,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(jn,{className:"h-3.5 w-3.5 mr-1"}),S.is_published?"Unpublish":"Publish"]}),e.jsx(G,{size:"sm",variant:"ghost",className:"text-destructive",onClick:z=>{z.stopPropagation(),N(S.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]})]})]},S.id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Th,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs(G,{onClick:()=>c(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Create New Course"}),e.jsx(Fr,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Course Title"}),e.jsx(ke,{value:d,onChange:S=>h(S.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:m,onChange:S=>x(S.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(br,{checked:g,onCheckedChange:v})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:j,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function uRs(){const{courseId:s}=Xi(),t=vr(),{data:r,isLoading:n}=QDs(s),a=Ngt(),i=tRs(),l=sRs(),o=rRs(),c=nRs(),d=aRs(),h=iRs(),{data:m}=gt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:lt}=await H.from("brokerages").select("id, name").order("name");return lt||[]}}),[x,g]=k.useState(null),[v,j]=k.useState(!1),[b,N]=k.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[S,T]=k.useState(null),[A,P]=k.useState({title:"",resource_type:"link",url:""}),[D,B]=k.useState(new Set),[z,F]=k.useState(null),[$,X]=k.useState(0),[K,Q]=k.useState(!1),Y=k.useRef(null),ne=k.useRef(null),[de,ce]=k.useState(!1),[ae,ie]=k.useState(""),[me,oe]=k.useState(""),[ge,be]=k.useState(""),[Oe,Me]=k.useState(!1);if(n)return e.jsx(_s,{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(_s,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(G,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Pe=r.modules||[],Ee=r.access||[],$e=Ee.some(lt=>lt.access_type==="all"),Se=Ee.filter(lt=>lt.access_type==="brokerage").map(lt=>lt.brokerage_id),ze=(m||[]).filter(lt=>lt.name.toLowerCase().includes(ae.toLowerCase())),Te=lt=>{const it=new Set(D);it.has(lt)?it.delete(lt):it.add(lt),B(it)},ye=async()=>{if(!z)return null;Q(!0),X(0);try{const{data:lt,error:it}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:z.name}});if(it)throw new Error(it.message);const{videoId:Nt,libraryId:Ft}=lt,{data:at,error:Ie}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Nt,libraryId:Ft}});if(Ie)throw new Error(Ie.message);const et=new XMLHttpRequest;return await new Promise((Dt,Jt)=>{et.upload.onprogress=cs=>{cs.lengthComputable&&X(Math.round(cs.loaded/cs.total*100))},et.onload=()=>et.status>=200&&et.status<300?Dt():Jt(new Error(`Upload failed: ${et.status}`)),et.onerror=()=>Jt(new Error("Upload failed")),et.open("PUT",at.uploadUrl),et.setRequestHeader("AccessKey",at.apiKey),et.send(z)}),`https://iframe.mediadelivery.net/embed/${Ft}/${Nt}`}catch(lt){return console.error("Bunny upload error:",lt),ue.error("Video upload failed"),null}finally{Q(!1),X(0)}},ct=async()=>{if(b.title.trim())try{let lt=b.video_url.trim()||void 0;if(z){const it=await ye();if(!it)return;lt=it}await i.mutateAsync({course_id:r.id,title:b.title.trim(),description:b.description.trim()||void 0,video_url:lt,text_content:b.text_content.trim()||void 0,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):void 0,sort_order:Pe.length}),ue.success("Module added"),j(!1),N({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),F(null)}catch{ue.error("Failed to add module")}},ve=async()=>{if(x)try{let lt=b.video_url.trim()||null;if(z){const it=await ye();if(!it)return;lt=it}await l.mutateAsync({id:x.id,title:b.title.trim(),description:b.description.trim()||null,video_url:lt,text_content:b.text_content.trim()||null,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):null}),ue.success("Module updated"),g(null),F(null)}catch{ue.error("Failed to update")}},rt=async lt=>{if(confirm("Delete this module?"))try{await o.mutateAsync(lt),ue.success("Module deleted")}catch{ue.error("Failed to delete")}},Re=async lt=>{if(A.title.trim())try{await c.mutateAsync({module_id:lt,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ue.success("Resource added"),T(null),P({title:"",resource_type:"link",url:""})}catch{ue.error("Failed to add resource")}},Qe=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[{access_type:"all"}]}),ue.success("Access updated: All brokerages / all agents")}catch{ue.error("Failed to update access")}},Ke=async lt=>{const it=Ee.filter(Ie=>Ie.access_type==="brokerage").map(Ie=>Ie.brokerage_id),Nt=it.includes(lt);let Ft;Nt?Ft=it.filter(Ie=>Ie!==lt):Ft=[...it,lt];const at=Ft.map(Ie=>({access_type:"brokerage",brokerage_id:Ie}));try{await h.mutateAsync({courseId:r.id,accessRules:at}),ue.success(Nt?"Brokerage removed":"Brokerage added")}catch{ue.error("Failed to update access")}},Ce=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[]}),ue.success("Access cleared")}catch{ue.error("Failed")}},nt=async(lt,it)=>{const Nt=it==="up"?lt-1:lt+1;if(!(Nt<0||Nt>=Pe.length))try{await Promise.all([l.mutateAsync({id:Pe[lt].id,sort_order:Nt}),l.mutateAsync({id:Pe[Nt].id,sort_order:lt})])}catch{ue.error("Failed to reorder")}},$t=async()=>{try{await a.mutateAsync({id:r.id,title:me,description:ge||null}),ue.success("Course updated"),Me(!1)}catch{ue.error("Failed to update")}};return e.jsxs(_s,{title:r.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:r.title}),e.jsx(Ge,{variant:r.is_published?"default":"secondary",children:r.is_published?"Published":"Draft"})]}),r.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:r.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[r.is_sequential?e.jsx(r0,{className:"h-3.5 w-3.5"}):e.jsx(V3,{className:"h-3.5 w-3.5"}),r.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Pe.length," module",Pe.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{oe(r.title),be(r.description||""),Me(!0)},children:[e.jsx(Ta,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(G,{variant:r.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:r.id,is_published:!r.is_published}).then(()=>ue.success(r.is_published?"Unpublished":"Published")),children:[r.is_published?e.jsx(am,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(jn,{className:"h-3.5 w-3.5 mr-1"}),r.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(Rn,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"modules",children:"Modules"}),e.jsx(Xt,{value:"access",children:"Access & Permissions"}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(as,{value:"modules",className:"mt-6 space-y-4",children:[Pe.map((lt,it)=>e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Te(lt.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:Nt=>{Nt.stopPropagation(),nt(it,"up")},disabled:it===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(xp,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Nt=>{Nt.stopPropagation(),nt(it,"down")},disabled:it===Pe.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(so,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Ge,{variant:"outline",className:"shrink-0 font-mono text-xs",children:it+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:lt.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[lt.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(sn,{className:"h-3 w-3"})," Video"]}),lt.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ln,{className:"h-3 w-3"})," Text"]}),lt.duration_minutes&&e.jsxs("span",{children:[lt.duration_minutes," min"]}),lt.resources&<.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(rl,{className:"h-3 w-3"})," ",lt.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:Nt=>{var Ft;Nt.stopPropagation(),g(lt),N({title:lt.title,description:lt.description||"",video_url:lt.video_url||"",text_content:lt.text_content||"",duration_minutes:((Ft=lt.duration_minutes)==null?void 0:Ft.toString())||""})},children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Nt=>{Nt.stopPropagation(),rt(lt.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]}),D.has(lt.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[lt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:lt.description}),lt.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:lt.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:lt.video_url})]}),lt.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:lt.text_content}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resources"}),e.jsxs(G,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{T(lt.id),P({title:"",resource_type:"link",url:""})},children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),lt.resources&<.resources.length>0?e.jsx("div",{className:"space-y-1",children:lt.resources.map(Nt=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Nt.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Nt.title}),Nt.url&&e.jsx("a",{href:Nt.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(G,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Nt.id),children:e.jsx(_r,{className:"h-3 w-3"})})]},Nt.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},lt.id)),e.jsxs(G,{variant:"outline",className:"w-full border-dashed",onClick:()=>{j(!0),N({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(as,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:Bt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",$e?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Qe,children:[e.jsx("div",{className:Bt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",$e?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(gc,{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(br,{checked:$e,onCheckedChange:Qe})]}),!$e&&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:Se.length===0?"No brokerages selected — agents won't see this course":`${Se.length} brokerage${Se.length!==1?"s":""} selected`})]}),Se.length>0&&e.jsx(G,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ce,children:"Clear all"})]}),e.jsx(ke,{placeholder:"Search brokerages...",value:ae,onChange:lt=>ie(lt.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:ze.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):ze.map(lt=>{const it=Se.includes(lt.id);return e.jsxs("div",{className:Bt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",it?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Ke(lt.id),children:[e.jsx("div",{className:Bt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",it?"bg-primary border-primary":"border-muted-foreground/30"),children:it&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:lt.name}),it&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},lt.id)})})]})]})]})}),e.jsxs(as,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[r.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:r.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:r.id,thumbnail_url:null}).then(()=>ue.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(_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($v,{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:ne,type:"file",accept:"image/*",className:"hidden",onChange:async lt=>{var Nt;const it=(Nt=lt.target.files)==null?void 0:Nt[0];if(!(!it||!r)){ce(!0);try{const Ft=it.name.split(".").pop(),at=`${r.id}/thumbnail.${Ft}`,{error:Ie}=await H.storage.from("lms-thumbnails").upload(at,it,{upsert:!0});if(Ie)throw Ie;const{data:et}=H.storage.from("lms-thumbnails").getPublicUrl(at),Dt=`${et.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:r.id,thumbnail_url:Dt}),ue.success("Thumbnail uploaded")}catch{ue.error("Failed to upload thumbnail")}finally{ce(!1),ne.current&&(ne.current.value="")}}}}),e.jsxs(G,{variant:"outline",size:"sm",disabled:de,onClick:()=>{var lt;return(lt=ne.current)==null?void 0:lt.click()},children:[de?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-2"}),de?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Course Settings"})}),e.jsxs(De,{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(br,{checked:r.is_sequential,onCheckedChange:lt=>a.mutateAsync({id:r.id,is_sequential:lt}).then(()=>ue.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(br,{checked:r.is_published,onCheckedChange:lt=>a.mutateAsync({id:r.id,is_published:lt}).then(()=>ue.success("Updated"))})]})]})]})]})]})]}),e.jsx(vs,{open:v||!!x,onOpenChange:lt=>{lt||(j(!1),g(null))},children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(bs,{children:x?"Edit Module":"Add Module"}),e.jsx(Fr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:b.title,onChange:lt=>N(it=>({...it,title:lt.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:b.description,onChange:lt=>N(it=>({...it,description:lt.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Bt("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",z?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var lt;return(lt=Y.current)==null?void 0:lt.click()},children:[e.jsx("input",{ref:Y,type:"file",accept:"video/*",className:"hidden",onChange:lt=>{var Nt;const it=(Nt=lt.target.files)==null?void 0:Nt[0];it&&(F(it),N(Ft=>({...Ft,video_url:""})))}}),z?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(sn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:z.name}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:lt=>{lt.stopPropagation(),F(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(oa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),K&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",$,"%"]})]}),e.jsx(ri,{value:$,className:"h-1.5"})]}),!z&&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(ke,{value:b.video_url,onChange:lt=>N(it=>({...it,video_url:lt.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Text Content"}),e.jsx(ur,{value:b.text_content,onChange:lt=>N(it=>({...it,text_content:lt.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Duration (minutes)"}),e.jsx(ke,{type:"number",value:b.duration_minutes,onChange:lt=>N(it=>({...it,duration_minutes:lt.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>{j(!1),g(null),F(null)},children:"Cancel"}),e.jsxs(G,{onClick:x?ve:ct,disabled:!b.title.trim()||K,children:[K?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ql,{className:"h-4 w-4 mr-2"}),K?"Uploading...":x?"Save Changes":"Add Module"]})]})]})}),e.jsx(vs,{open:!!S,onOpenChange:lt=>{lt||T(null)},children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Add Resource"}),e.jsx(Fr,{children:"Add a link, document, or other resource to this module"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:A.title,onChange:lt=>P(it=>({...it,title:lt.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Type"}),e.jsxs(zs,{value:A.resource_type,onValueChange:lt=>P(it=>({...it,resource_type:lt})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"link",children:"Link"}),e.jsx(mt,{value:"pdf",children:"PDF"}),e.jsx(mt,{value:"template",children:"Template"}),e.jsx(mt,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"URL"}),e.jsx(ke,{value:A.url,onChange:lt=>P(it=>({...it,url:lt.target.value})),placeholder:"https://..."})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>T(null),children:"Cancel"}),e.jsx(G,{onClick:()=>S&&Re(S),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(vs,{open:Oe,onOpenChange:Me,children:e.jsxs(ys,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Edit Course"}),e.jsx(Fr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(ke,{value:me,onChange:lt=>oe(lt.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:ge,onChange:lt=>be(lt.target.value),rows:3})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>Me(!1),children:"Cancel"}),e.jsx(G,{onClick:$t,disabled:!me.trim(),children:"Save"})]})]})})]})}function hRs(){return gt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await H.rpc("get_lms_stats");if(t)throw t;return s}})}function mRs(){return gt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await H.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function fRs(s){return gt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.rpc("get_lms_agent_progress",{p_course_id:s});if(r)throw r;return t||[]},enabled:!!s})}function pRs(){const s=vr(),{data:t,isLoading:r}=hRs(),{data:n,isLoading:a}=mRs(),[i,l]=k.useState(null),{data:o,isLoading:c}=fRs(i),[d,h]=k.useState(""),m=n==null?void 0:n.find(v=>v.course_id===i),x=o==null?void 0:o.filter(v=>{var j,b;return!d||((j=v.agent_name)==null?void 0:j.toLowerCase().includes(d.toLowerCase()))||((b=v.email)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))}),g=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Th,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Mn,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:fr,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:Zi,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:_o,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:ao,color:"text-rose-500"}];return e.jsx(_s,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(wa,{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(Od,{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:g.map(v=>e.jsx(Ne,{className:Bt("transition-all",r&&"animate-pulse"),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(v.icon,{className:Bt("h-4 w-4",v.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:r?"—":v.value})]})},v.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(ao,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(v=>e.jsx(Ne,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},v))}):n!=null&&n.length?e.jsx("div",{className:"space-y-2",children:n.map(v=>{const j=i===v.course_id;return e.jsx(Ne,{className:Bt("cursor-pointer transition-all hover:shadow-md",j?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(j?null:v.course_id),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:v.course_title}),e.jsx(Ge,{variant:v.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:v.is_published?"Live":"Draft"})]})}),e.jsx(ya,{className:Bt("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",j&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:v.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:v.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:v.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[v.avg_completion_pct,"%"]})]}),e.jsx(ri,{value:v.avg_completion_pct,className:"h-2"})]})]})},v.course_id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(De,{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(Yv,{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(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{value:d,onChange:v=>h(v.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(v=>e.jsx(Ne,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},v))}):x!=null&&x.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:x.map((v,j)=>{const b=v.completion_pct>=100;return e.jsx(Ne,{className:Bt("transition-all",b&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Bt("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",j===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":j===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":j===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:j+1}),e.jsxs(vn,{className:"h-9 w-9 shrink-0",children:[e.jsx(ga,{src:v.avatar_url||void 0}),e.jsx(bn,{className:"text-xs bg-primary/10 text-primary",children:(v.agent_name||v.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:v.agent_name||v.email}),b&&e.jsxs(Ge,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Mn,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[v.modules_completed,"/",v.total_modules," modules"]}),v.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Ss(new Date(v.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Bt("text-sm font-bold",b?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[v.completion_pct,"%"]}),e.jsx(ri,{value:v.completion_pct,className:"h-1.5 mt-1"})]})]})})},v.user_id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(De,{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(Ne,{className:"border-dashed",children:e.jsxs(De,{className:"py-16 text-center",children:[e.jsx(fr,{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 xRs(){const{user:s}=As(),t=vr(),{data:r,isLoading:n}=oRs();return e.jsx(_s,{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(Od,{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(Ne,{className:"animate-pulse",children:e.jsxs(De,{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(gRs,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Th,{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 gRs({course:s,userId:t,onClick:r}){var o;const n=((o=s.modules)==null?void 0:o.length)??0,{data:a}=kgt(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(Ne,{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(Od,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(De,{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(Th,{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(r0,{className:"h-3.5 w-3.5"}):e.jsx(V3,{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(ri,{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(ya,{className:"h-3.5 w-3.5"})]})})]})]})}function yRs(){const{courseId:s}=Xi(),t=vr(),{user:r}=As(),{data:n,isLoading:a}=lRs(s),{data:i}=kgt(s),l=cRs(),[o,c]=k.useState(null),d=(n==null?void 0:n.modules)||[],h=new Set((i==null?void 0:i.filter(S=>S.completed).map(S=>S.module_id))||[]),m=h.size,x=d.length>0?Math.round(m/d.length*100):0;k.useEffect(()=>{if(d.length>0&&!o){const S=d.find(T=>!h.has(T.id));c((S==null?void 0:S.id)||d[0].id)}},[d,o,h]);const g=d.find(S=>S.id===o),v=d.findIndex(S=>S.id===o),j=(S,T)=>{if(!(n!=null&&n.is_sequential)||T===0)return!1;for(let A=0;A{if(!(!g||!r||!s))try{await l.mutateAsync({courseId:s,moduleId:g.id,userId:r.id}),ue.success("Module completed! 🎉"),v{const T=S.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(T)return`https://www.youtube.com/embed/${T[1]}`;const A=S.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const P=S.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return P?`https://iframe.mediadelivery.net/embed/${P[1]}/${P[2]}?responsive=true`:S};return a?e.jsx(_s,{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(_s,{title:n.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(wa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:n.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[m,"/",d.length," completed"]}),e.jsxs("span",{children:[x,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(ri,{value:x,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(Ne,{className:"lg:sticky lg:top-4",children:e.jsxs(De,{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(ti,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((S,T)=>{const A=j(S,T),P=h.has(S.id),D=S.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(S.id),className:Bt("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(Kc,{className:"h-4 w-4 text-muted-foreground"}):P?e.jsx(Mn,{className:"h-4 w-4 text-green-500"}):e.jsx(Bd,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Bt("font-medium truncate",D&&"text-primary"),children:[T+1,". ",S.title]}),S.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(cn,{className:"h-3 w-3"})," ",S.duration_minutes," min"]})]})]},S.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:g?e.jsxs(e.Fragment,{children:[g.video_url&&e.jsx(Ne,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:N(g.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(Ne,{children:e.jsxs(De,{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:g.title}),g.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:g.description})]}),h.has(g.id)?e.jsxs(Ge,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Mn,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(G,{size:"sm",onClick:b,disabled:l.isPending,children:[e.jsx(Mn,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),g.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:g.text_content}),g.resources&&g.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:g.resources.map(S=>e.jsxs("a",{href:S.url||S.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[S.resource_type==="pdf"?e.jsx(ln,{className:"h-4 w-4 text-red-500 shrink-0"}):S.resource_type==="template"?e.jsx(Od,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(rl,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:S.title}),e.jsx(Yr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},S.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(G,{variant:"outline",size:"sm",disabled:v===0,onClick:()=>v>0&&c(d[v-1].id),children:[e.jsx(wa,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),vc(d[v+1].id),children:["Next ",e.jsx(ya,{className:"h-3.5 w-3.5 ml-1"})]}):x===100&&e.jsx(Ge,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(Ne,{children:e.jsx(De,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(_s,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(G,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function vRs({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(Cr.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(Cr.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(Cr.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(Cr.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(Cr.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(Ga,{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(Cr.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 zx({children:s,className:t="",delay:r=0,direction:n="up"}){const a=k.useRef(null),i=sBt(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(Cr.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 bRs({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(zx,{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(zx,{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 _Rs({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(zx,{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(fr,{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(zx,{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 wRs({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(zx,{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(zx,{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(z3,{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 jRs({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(zx,{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(zx,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),r()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ke,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ke,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ke,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(ke,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ke,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(ke,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ke,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ke,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(ur,{value:s.why_interested,onChange:l=>t(o=>({...o,why_interested:l.target.value})),rows:3,className:"rounded-lg border-gray-200 focus:border-gray-400 transition-colors resize-none",placeholder:"Tell us about your goals and what you're looking for..."})]}),e.jsx(G,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:n,children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(Ga,{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(Zu,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function NRs({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=k.useState(1),[d,h]=k.useState(""),m=3,x=!!s.first_name&&!!s.email,g=v=>{h(v),t(j=>({...j,why_interested:v})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(zx,{children:e.jsxs("div",{className:"text-center mb-8",children:[l&&e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold bg-white/15 text-white backdrop-blur mb-4",children:[e.jsx(Kc,{className:"h-2.5 w-2.5"})," 100% Confidential"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-3 tracking-tight",children:"Start a Confidential Conversation"}),e.jsx("p",{className:"text-white/70 text-lg font-light",children:"No high-pressure sales calls. Ever."})]})}),e.jsx(zx,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(v=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:v<=o?a:"#e5e7eb"}},v)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",m]})]}),e.jsxs(i5e,{mode:"wait",children:[o===1&&e.jsxs(Cr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(v=>e.jsxs("button",{type:"button",onClick:()=>g(v.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:v.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:v.label}),e.jsx(Ga,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},v.val))]},"step1"),o===2&&e.jsxs(Cr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ke,{required:!0,value:s.first_name,onChange:v=>t(j=>({...j,first_name:v.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ke,{value:s.last_name,onChange:v=>t(j=>({...j,last_name:v.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ke,{type:"email",required:!0,value:s.email,onChange:v=>t(j=>({...j,email:v.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(ke,{value:s.phone,onChange:v=>t(j=>({...j,phone:v.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(G,{type:"button",disabled:!x,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(Ga,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Cr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ke,{value:s.current_brokerage,onChange:v=>t(j=>({...j,current_brokerage:v.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ke,{type:"number",min:"0",value:s.experience_years,onChange:v=>t(j=>({...j,experience_years:v.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ke,{value:s.annual_production,onChange:v=>t(j=>({...j,annual_production:v.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(ur,{value:s.why_interested,onChange:v=>t(j=>({...j,why_interested:v.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(G,{type:"button",onClick:r,disabled:n,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Hn,{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(Zu,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(bi,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Nn,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function kRs({config:s,primaryColor:t,accentColor:r,brokerageId:n,brokerageName:a}){const{toast:i}=Ea(),[l,o]=k.useState("250000"),[c,d]=k.useState("12"),[h,m]=k.useState("70"),[x,g]=k.useState("150"),[v,j]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=s.commission_split_pct??80,P=s.cap_amount??16e3,D=s.post_cap_split_pct??100,B=s.monthly_fee??99,z=s.transaction_fee??0,F=k.useMemo(()=>{const K=parseFloat(l)||0,Q=Math.max(0,parseInt(c,10)||0),Y=parseFloat(h)||0,ne=parseFloat(x)||0,de=K*(Y/100)-ne*12-z*Q,ce=1-A/100,ae=ce>0?P/ce:K,ie=Math.min(K,ae),me=Math.max(0,K-ae),oe=ie*ce+me*(1-D/100),ge=K-oe-B*12-z*Q,be=ge-de;return{currentNet:de,newNet:ge,diff:be}},[l,c,h,x,A,P,D,B,z]),$=K=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(K),X=async K=>{if(K.preventDefault(),!!v){T(!0);try{const{error:Q}=await H.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:v,source:"calculator"});if(Q)throw Q;const{error:Y}=await H.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:n,brokerage_name:a,email:v,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(h)||0,current_monthly_fee:parseFloat(x)||0},plan:{commission_split_pct:A,cap_amount:P,post_cap_split_pct:D,monthly_fee:B,transaction_fee:z},result:F,primary_color:t,accent_color:r}});Y&&console.error("Breakdown email failed:",Y),N(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(Q){i({title:"Error",description:Q.message,variant:"destructive"})}finally{T(!1)}}};return e.jsx("section",{className:"py-20 md:py-28 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(zx,{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(Kc,{className:"h-3 w-3"})," 100% Confidential — No Signup Required"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight mb-3",style:{color: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(zx,{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(QA,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:r},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ke,{type:"number",value:l,onChange:K=>o(K.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(ke,{type:"number",min:"0",value:c,onChange:K=>d(K.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(ke,{type:"number",value:h,onChange:K=>m(K.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ke,{type:"number",value:x,onChange:K=>g(K.target.value),className:"pl-7 h-11 text-base",placeholder:"150"})]})]})]})]}),e.jsxs("div",{className:"p-8 md:p-10 text-white",style:{background:`linear-gradient(160deg, ${r}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(_o,{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:$(F.currentNet)})]}),e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"With us"}),e.jsx("span",{className:"text-xl font-semibold",children:$(F.newNet)})]})]}),e.jsxs(Cr.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:F.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[F.diff>=0?"+":"",$(F.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:F.diff>=0?"more per year":"per year"})]},F.diff),s.show_email_capture&&!b&&e.jsxs("form",{onSubmit:X,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(ke,{type:"email",required:!0,value:v,onChange:K=>j(K.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(G,{type:"submit",disabled:S,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),b&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(Hn,{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 SRs({config:s,primaryColor:t,accentColor:r,brokerageId:n}){const{toast:a}=Ea(),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(!1),g=async v=>{v.preventDefault(),x(!0);try{const{error:j}=await H.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(j)throw j;h(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(j){a({title:"Error",description:j.message,variant:"destructive"})}finally{x(!1)}};return e.jsx("section",{className:"py-20 md:py-24 px-6 bg-white",children:e.jsx("div",{className:"max-w-3xl mx-auto",children:e.jsx(zx,{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(S3,{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(Kc,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color: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(Hn,{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:g,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(ke,{value:o,onChange:v=>c(v.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(ke,{type:"email",required:!0,value:i,onChange:v=>l(v.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(G,{type:"submit",disabled:m,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:[e.jsx(S3,{className:"h-4 w-4 mr-2"}),m?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function CRs(){const{slug:s}=Xi(),{toast:t}=Ea(),[r,n]=k.useState(!1),[a,i]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});k.useEffect(()=>{document.body.classList.add("recruit-landing-page");const F=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(Q=>document.querySelectorAll(Q).forEach(Y=>Y.style.display="none"))};F();const $=[setTimeout(F,500),setTimeout(F,1500),setTimeout(F,3e3)],X=new MutationObserver(F);return X.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),$.forEach(clearTimeout),X.disconnect()}},[]);const{data:l,isLoading:o,error:c}=gt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:F,error:$}=await H.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if($)throw $;return F},enabled:!!s}),{data:d}=gt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:$}=await H.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if($&&$.code!=="PGRST116")throw $;return F},enabled:!!(l!=null&&l.id)}),h=Lt({mutationFn:async()=>{const F={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:$}=await H.from("recruit_interest_submissions").insert(F);if($)throw $;H.functions.invoke("recruit-lead-notify",{body:{lead:F,brokerage_id:l.id}}).catch(X=>console.error("Lead notification error:",X))},onSuccess:()=>n(!0),onError:F=>t({title:"Error",description:F.message,variant:"destructive"})});if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-3 border-gray-200 border-t-gray-800"}),e.jsx("span",{className:"text-sm text-gray-400 tracking-wide",children:"Loading..."})]})});if(c||!l||!l.recruit_form_enabled)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"max-w-md w-full mx-4 text-center",children:[e.jsx(Sa,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const m=d,x=(m==null?void 0:m.primary_color)||"#406E71",g=(m==null?void 0:m.accent_color)||"#2a4c64",v=(m==null?void 0:m.benefits)||[],j=(m==null?void 0:m.testimonials)||[],b=(m==null?void 0:m.gallery_images)||[],N=(m==null?void 0:m.hero_headline)||`Join ${l.name}`,S=(m==null?void 0:m.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",T=(m==null?void 0:m.calculator_enabled)===!0,A=(m==null?void 0:m.calculator_config)||{},P=(m==null?void 0:m.lead_magnet_enabled)===!0,D=(m==null?void 0:m.lead_magnet_config)||{},B=(m==null?void 0:m.form_style)||"classic",z=(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(Cr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${x}, ${g})`},children:e.jsx(Hn,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:g},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:g},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:x}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":x,"--recruit-accent":g},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:g},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${x}, ${g})`},children:["Apply Now ",e.jsx(Ga,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(vRs,{headline:N,subtext:S,primaryColor:x,accentColor:g,heroImageUrl:m==null?void 0:m.hero_image_url,logoUrl:m==null?void 0:m.logo_url,brokerageName:l.name}),e.jsx(bRs,{benefits:v,accentColor:g,primaryColor:x}),e.jsx(_Rs,{images:b,primaryColor:x,accentColor:g}),e.jsx(wRs,{testimonials:j,primaryColor:x,accentColor:g}),T&&e.jsx(kRs,{config:A,primaryColor:x,accentColor:g,brokerageId:l.id,brokerageName:l.name}),P&&e.jsx(SRs,{config:D,primaryColor:x,accentColor:g,brokerageId:l.id}),B==="multi_step"?e.jsx(NRs,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:x,accentColor:g,showConfidentialBadges:z}):e.jsx(jRs,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:x,accentColor:g}),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 TRs(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 ERs(){var x,g,v,j;const{shareToken:s}=Xi(),t=k.useRef(!1),{data:r,isLoading:n,error:a}=gt({queryKey:["public-recruit-video",s],queryFn:async()=>{var P;if(!s)throw new Error("No token");const{data:b,error:N}=await H.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(N)throw N;const{data:S}=await H.from("profiles").select("name, avatar_url, title").eq("id",(P=b.video)==null?void 0:P.owner_user_id).single(),{data:T}=await H.from("brokerages").select("name").eq("id",b.brokerage_id).single(),{data:A}=await H.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",b.brokerage_id).maybeSingle();return{rv:b,profile:S,brokerage:T,settings:A}},enabled:!!s});if(k.useEffect(()=>{var b;!((b=r==null?void 0:r.rv)!=null&&b.id)||t.current||(t.current=!0,H.rpc("log_recruit_video_view",{p_recruit_video_id:r.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(x=r==null?void 0:r.rv)==null?void 0:x.id]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=r,d=(c==null?void 0:c.primary_color)||"#3b82f6",h=((g=i.prospect)==null?void 0:g.first_name)||"there",m=(v=i.video)!=null&&v.playback_url?TRs(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(il,{children:e.jsx("title",{children:o!=null&&o.name?`${o.name} — A Message For You`:"Personal Video Message"})}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:[e.jsx("header",{className:"border-b bg-white/80 backdrop-blur-sm",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center gap-3",children:[(c==null?void 0:c.logo_url)&&e.jsx("img",{src:c.logo_url,alt:"",className:"h-8 object-contain"}),e.jsx("span",{className:"font-semibold text-sm",style:{color:d},children:(o==null?void 0:o.name)||"Recruiting"})]})}),e.jsxs("main",{className:"max-w-3xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Hey ",h,", ",l==null?void 0:l.name," has a message for you"]}),i.message&&e.jsx("p",{className:"text-muted-foreground max-w-xl mx-auto",children:i.message})]}),m&&e.jsx("div",{className:"rounded-xl overflow-hidden shadow-xl bg-black",children:e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:m,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}),e.jsxs("div",{className:"bg-white rounded-xl shadow-sm border p-6 flex items-center gap-4",children:[l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"",className:"h-14 w-14 rounded-full object-cover"}):e.jsx("div",{className:"h-14 w-14 rounded-full flex items-center justify-center text-white text-lg font-bold",style:{backgroundColor:d},children:((j=l==null?void 0:l.name)==null?void 0:j.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),e.jsx("div",{className:"text-center",children:e.jsxs(G,{size:"lg",className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{H.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:[e.jsx(rn,{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 ARs="relzejiswnotikjgvjhz",vHe=`https://${ARs}.supabase.co/functions/v1/recruit-unsubscribe`;function MRs(){const[s]=Lc(),t=s.get("token")||"",[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState({});k.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const g=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(N=>document.querySelectorAll(N).forEach(S=>S.style.display="none"))};g();const v=[setTimeout(g,500),setTimeout(g,1500),setTimeout(g,3e3)],j=new MutationObserver(g);return j.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),v.forEach(clearTimeout),j.disconnect()}},[]),k.useEffect(()=>{if(!t){m({error:"Missing unsubscribe token in link."}),n(!1);return}fetch(`${vHe}?token=${encodeURIComponent(t)}`).then(async g=>{const v=await g.json();if(!g.ok)throw new Error(v.error||"Lookup failed");m(v),v.already_unsubscribed&&o(!0)}).catch(g=>m({error:g.message||"Could not load status"})).finally(()=>n(!1))},[t]);const x=async()=>{i(!0);try{const g=await fetch(vHe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),v=await g.json();if(!g.ok)throw new Error(v.error||"Failed");o(!0)}catch(g){m({...h,error:g.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…"})]}):h.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Hi,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:h.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(Mn,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",h.first_name?`, ${h.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",h.brokerage_name||"this brokerage",". Your conversation remains 100% confidential."]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(a0,{className:"h-3.5 w-3.5"}),"Confidential opt-out · Confirmed"]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(a0,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",h.first_name?`, ${h.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",h.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),h.email&&e.jsx("p",{className:"text-xs text-slate-400",children:h.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(ur,{id:"reason",value:c,onChange:g=>d(g.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(G,{onClick:x,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(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 IRs(){const s=vr(),t=es(),{isAdmin:r}=As(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(null),{data:d,isLoading:h}=gt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:P},error:D}=await H.auth.getUser();if(D)throw D;if(!P)return[];const{data:B,error:z}=await H.from("social_accounts").select("*").eq("user_id",P.id).order("created_at",{ascending:!1});if(z)throw z;return B}}),m=Lt({mutationFn:async P=>{const{data:{user:D},error:B}=await H.auth.getUser();if(B)throw B;if(!D)throw new Error("Not authenticated");const{error:z}=await H.from("social_accounts").delete().eq("id",P).eq("user_id",D.id);if(z)throw z},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ue.success("Account disconnected successfully")},onError:()=>{ue.error("Failed to disconnect account")}}),x=async P=>{a(!0);try{const{data:D,error:B}=await H.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:P}});if(B)throw B;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),ue.error("Failed to start connection. Please try again."),a(!1)}},g=async()=>{a(!0);try{const{data:P,error:D}=await H.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;if(P!=null&&P.authUrl)window.location.href=P.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(P){console.error("LinkedIn OAuth error:",P),ue.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},v=async()=>{a(!0);try{const{data:P,error:D}=await H.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(D)throw D;if(P!=null&&P.authUrl)window.location.href=P.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(P){console.error("Google OAuth error:",P),ue.error("Failed to start Google connection. Please try again."),a(!1)}},j=(d==null?void 0:d.filter(P=>P.platform==="facebook"))||[],b=(d==null?void 0:d.filter(P=>P.platform==="instagram"))||[],N=(d==null?void 0:d.filter(P=>P.platform==="linkedin"))||[],S=(d==null?void 0:d.filter(P=>P.platform==="google_business"))||[],T=((d==null?void 0:d.length)||0)>0,A=async(P,D)=>{l(P),c(null);try{const{data:B,error:z}=await H.functions.invoke("meta-api-test",{body:{testType:"all",accountId:P}});if(z)throw z;c(B.results||[]),ue.success(B.summary||"API tests completed")}catch(B){console.error("Meta API test error:",B),ue.error("Failed to run API tests")}finally{l(null)}};return e.jsx(_s,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(G,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back to Social Swag"]}),T&&e.jsx(Ne,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(De,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(mi,{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(Ne,{children:[e.jsx(Ot,{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(ku,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Facebook"}),e.jsx(Nr,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Di,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length>0?e.jsx("div",{className:"space-y-3",children:j.map(P=>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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:P.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(ku,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:P.page_name||P.platform_username||"Facebook Page"}),e.jsx(Ge,{variant:P.is_active?"default":"secondary",className:"text-xs",children:P.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Facebook?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m.mutate(P.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},P.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(G,{onClick:()=>x("facebook"),disabled:n,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[n?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),j.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{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(au,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Instagram"}),e.jsx(Nr,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Di,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(P=>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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:P.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(au,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",P.platform_username||"Instagram Account"]}),e.jsx(Ge,{variant:P.is_active?"default":"secondary",className:"text-xs",children:P.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Instagram?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m.mutate(P.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},P.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(G,{onClick:()=>x("instagram"),disabled:n,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[n?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{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(Ne,{children:[e.jsx(Ot,{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(om,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Nr,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Di,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N.length>0?e.jsx("div",{className:"space-y-3",children:N.map(P=>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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:P.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(om,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:P.platform_username||"LinkedIn Account"}),e.jsx(Ge,{variant:P.is_active?"default":"secondary",className:"text-xs",children:P.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect LinkedIn?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m.mutate(P.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},P.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(G,{onClick:g,disabled:n,className:"w-full gap-2",variant:N.length>0?"outline":"default",children:[n?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),N.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(Ne,{className:`relative overflow-hidden ${r?"":"opacity-75"}`,children:[!r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ge,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ge,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Ot,{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(ja,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Google Business"}),e.jsx(Nr,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Di,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length>0?e.jsx("div",{className:"space-y-3",children:S.map(P=>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(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:P.profile_picture_url||""}),e.jsx(bn,{children:e.jsx(ja,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:P.page_name||P.platform_username||"Google Business"}),e.jsx(Ge,{variant:P.is_active?"default":"secondary",className:"text-xs",children:P.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Yo,{children:[e.jsx(Lm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Disconnect Google Business?"}),e.jsx(Uo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>m.mutate(P.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},P.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:r?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(G,{onClick:r?v:void 0,disabled:!r||n,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[n?e.jsx(Di,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),S.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),r&&(j.length>0||b.length>0)&&e.jsxs(Ne,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Ot,{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(Hj,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Nr,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(De,{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:[j.map(P=>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(ku,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:P.page_name||"Facebook Page"})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(P.id),disabled:i===P.id,children:i===P.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(Hj,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${P.id}`)),b.map(P=>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(au,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",P.platform_username||"Instagram"]})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(P.id),disabled:i===P.id,children:i===P.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(Hj,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${P.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((P,D)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[P.status==="success"?e.jsx(Mn,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):P.status==="pending"?e.jsx(ls,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Mc,{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:P.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:P.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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-lg",children:"How it works"})}),e.jsx(De,{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 PRs(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:g}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/social-connections/callback"}});if(g)throw g;if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||0} account(s)!`),ue.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect accounts"),ue.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(mi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Mc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function LRs(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Google Business Profile...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:m,error:x}=await H.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:h}});if(x)throw x;if(m!=null&&m.success)n("success"),i(m.message||"Successfully connected Google Business Profile!"),ue.success("Google Business Profile connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Google OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Google Business Profile"),ue.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(mi,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Mc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(zt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/social-connections"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function DRs(){const[s]=Lc(),t=vr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your LinkedIn account...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("state"),d=s.get("error"),h=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,h),n("error"),i(h||"Failed to connect LinkedIn account"),ue.error(h||"Failed to connect LinkedIn");return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:g}=await H.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(g)throw g;if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||1} LinkedIn account`),ue.success("LinkedIn connected successfully!");else throw new Error((x==null?void 0:x.error)||"Failed to connect LinkedIn account")}catch(x){console.error("LinkedIn callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect LinkedIn account"),ue.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ot,{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(mi,{className:"h-8 w-8 text-green-600"}),r==="error"&&e.jsx(Mc,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(zt,{className:"flex items-center justify-center gap-2",children:[e.jsx(om,{className:"h-5 w-5 text-blue-600"}),r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/mission-control/integrations"),disabled:r==="loading",children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function RRs(){const s=vr(),[t,r]=k.useState(null),{data:n,isLoading:a}=$xt(t||void 0,!0),{data:i,isLoading:l}=xMe(!0),{cartItems:o}=Xpe(),c=o.reduce((h,m)=>h+m.quantity,0),d=h=>{s(`/marketplace/${h.id}`)};return a||l?e.jsx(_s,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(h=>e.jsx(Vs,{className:"h-10 w-24 flex-shrink-0"},h))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(h=>e.jsx(Vs,{className:"h-72 w-full"},h))})]})}):e.jsx(_s,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(G,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(lp,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Ge,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx(G,{variant:t===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),i.map(h=>e.jsx(G,{variant:t===h.id?"default":"outline",size:"sm",onClick:()=>r(h.id),children:h.name},h.id))]}),n&&n.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(h=>{var m;return e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(h),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[h.images&&h.images.length>0?e.jsx("img",{src:((m=h.images.find(x=>x.is_primary))==null?void 0:m.image_url)||h.images[0].image_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Pl,{className:"h-12 w-12 text-muted-foreground"})}),h.category&&e.jsx(Ge,{className:"absolute top-2 left-2",variant:"secondary",children:h.category.name})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:h.name}),h.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:h.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(h.base_price).toFixed(2)]}),h.variants&&h.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.variants.length," options"]})]})]})]},h.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pl,{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 Sgt=k.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Sgt.displayName="Breadcrumb";const Cgt=k.forwardRef(({className:s,...t},r)=>e.jsx("ol",{ref:r,className:Bt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));Cgt.displayName="BreadcrumbList";const Fde=k.forwardRef(({className:s,...t},r)=>e.jsx("li",{ref:r,className:Bt("inline-flex items-center gap-1.5",s),...t}));Fde.displayName="BreadcrumbItem";const HSe=k.forwardRef(({asChild:s,className:t,...r},n)=>{const a=s?c4e:"a";return e.jsx(a,{ref:n,className:Bt("transition-colors hover:text-foreground",t),...r})});HSe.displayName="BreadcrumbLink";const Tgt=k.forwardRef(({className:s,...t},r)=>e.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Bt("font-normal text-foreground",s),...t}));Tgt.displayName="BreadcrumbPage";const GSe=({children:s,className:t,...r})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Bt("[&>svg]:size-3.5",t),...r,children:s??e.jsx(ya,{})});GSe.displayName="BreadcrumbSeparator";function ORs(){var Q,Y;const{productId:s}=Xi(),t=vr(),{data:r,isLoading:n}=OLs(s||""),{addToCart:a,cartItems:i}=Xpe(),[l,o]=k.useState(null),[c,d]=k.useState(1),[h,m]=k.useState(0),[x,g]=k.useState(null),[v,j]=k.useState(!1),[b,N]=k.useState(!1),S=(Q=r==null?void 0:r.variants)==null?void 0:Q.find(ne=>ne.id===l),T=((Y=r==null?void 0:r.variants)==null?void 0:Y.filter(ne=>ne.is_active))||[],A=Number((r==null?void 0:r.base_price)||0),P=S?Number(S.price_adjustment):0,D=A+P,B=Number((r==null?void 0:r.shipping_fee)||0),z=i.reduce((ne,de)=>ne+de.quantity,0),F=async ne=>{if(!ne.target.files||ne.target.files.length===0)return;j(!0);const de=ne.target.files[0],ce=de.name.split(".").pop(),ae=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ce}`;try{const{error:ie}=await H.storage.from("marketplace").upload(ae,de);if(ie)throw ie;const{data:{publicUrl:me}}=H.storage.from("marketplace").getPublicUrl(ae);g(me),ue.success("Artwork uploaded successfully")}catch(ie){ue.error("Failed to upload artwork: "+ie.message)}finally{j(!1)}},$=()=>{if(r){if(T.length>0&&!l){ue.error("Please select an option");return}a(r,S||void 0,c,x||void 0),N(!0),ue.success("Added to cart!"),setTimeout(()=>N(!1),2e3)}},X=()=>{r!=null&&r.images&&m(ne=>(ne+1)%r.images.length)},K=()=>{r!=null&&r.images&&m(ne=>(ne-1+r.images.length)%r.images.length)};return n?e.jsx(_s,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Vs,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{className:"h-8 w-3/4"}),e.jsx(Vs,{className:"h-6 w-1/4"}),e.jsx(Vs,{className:"h-24 w-full"}),e.jsx(Vs,{className:"h-12 w-full"})]})]})}):r?e.jsxs(_s,{title:r.name,children:[e.jsx(Sgt,{className:"mb-6",children:e.jsxs(Cgt,{children:[e.jsx(Fde,{children:e.jsx(HSe,{asChild:!0,children:e.jsx(Kn,{to:"/marketplace",children:"Marketplace"})})}),r.category&&e.jsxs(e.Fragment,{children:[e.jsx(GSe,{}),e.jsx(Fde,{children:e.jsx(HSe,{asChild:!0,children:e.jsx(Kn,{to:`/marketplace?category=${r.category.id}`,children:r.category.name})})})]}),e.jsx(GSe,{}),e.jsx(Fde,{children:e.jsx(Tgt,{children:r.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:r.images&&r.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r.images[h].image_url,alt:r.name,className:"max-w-full max-h-full object-contain"}),r.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:K,children:e.jsx(Vo,{className:"h-6 w-6"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:X,children:e.jsx(ya,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Pl,{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((ne,de)=>e.jsx("button",{onClick:()=>m(de),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${de===h?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:ne.image_url,alt:"",className:"w-full h-full object-cover"})},ne.id))}),r.video&&e.jsx(Ne,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:r.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[r.category&&e.jsx(Ge,{variant:"secondary",className:"mb-2",children:r.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:r.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",D.toFixed(2)]}),B>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",B.toFixed(2)," shipping"]})]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})}),T.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(ne=>e.jsxs(G,{variant:l===ne.id?"default":"outline",onClick:()=>o(ne.id),children:[ne.name,Number(ne.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(ne.price_adjustment)>0?"+":"","$",Number(ne.price_adjustment).toFixed(2),")"]})]},ne.id))})]}),r.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Upload Your Artwork (Optional)"}),x?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:x,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(G,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>g(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:F,className:"hidden",id:"artwork-upload",disabled:v}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(oa,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:v?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(ne=>Math.max(1,ne-1)),children:"-"}),e.jsx(ke,{type:"number",value:c,onChange:ne=>d(Math.max(1,parseInt(ne.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(ne=>ne+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(G,{size:"lg",className:"flex-1",onClick:$,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(lp,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(G,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(lp,{className:"h-5 w-5"}),z>0&&e.jsx(Ge,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:z})]})]}),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(_s,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pl,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Product not found"}),e.jsx(G,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function FRs(){const s=vr(),{cartItems:t,removeFromCart:r,updateQuantity:n,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Xpe(),[d,h]=k.useState(!1),[m,x]=k.useState(""),g=async()=>{if(t.length===0){ue.error("Your cart is empty");return}h(!0);try{const{data:v,error:j}=await H.functions.invoke("marketplace-checkout",{body:{items:t.map(b=>{var N;return{product_id:b.product.id,variant_id:((N=b.variant)==null?void 0:N.id)||null,quantity:b.quantity,artwork_url:b.artworkUrl||null}}),notes:m.trim()||null}});if(j)throw j;if(v!=null&&v.url)c(),window.open(v.url,"_blank");else throw new Error("No checkout URL received")}catch(v){ue.error("Checkout failed: "+v.message)}finally{h(!1)}};return t.length===0?e.jsx(_s,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Kv,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx(G,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(_s,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(v=>{var j,b;return e.jsx(Ne,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:v.product.images&&v.product.images.length>0?e.jsx("img",{src:((j=v.product.images.find(N=>N.is_primary))==null?void 0:j.image_url)||v.product.images[0].image_url,alt:v.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Kv,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:v.product.name}),v.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(v).toFixed(2),Number(v.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(v.product.shipping_fee).toFixed(2)," shipping"]})]}),v.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return r(v.product.id,(N=v.variant)==null?void 0:N.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return n(v.product.id,(N=v.variant)==null?void 0:N.id,v.quantity-1)},disabled:v.quantity<=1,children:e.jsx(qv,{className:"h-3 w-3"})}),e.jsx(ke,{type:"number",value:v.quantity,onChange:N=>{var S;return n(v.product.id,(S=v.variant)==null?void 0:S.id,parseInt(N.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return n(v.product.id,(N=v.variant)==null?void 0:N.id,v.quantity+1)},children:e.jsx(Ws,{className:"h-3 w-3"})})]})]})]})})},`${v.product.id}-${((b=v.variant)==null?void 0:b.id)||"base"}`)}),e.jsx(G,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(Ne,{className:"sticky top-4",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Order Summary"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((v,j)=>v+j.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(po,{}),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(po,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(ur,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:m,onChange:v=>x(v.target.value),rows:3,className:"resize-none"})]}),e.jsx(G,{className:"w-full",size:"lg",onClick:g,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(Ga,{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 BRs(){const s=vr(),{data:t,isLoading:r}=KLs();return r?e.jsx(_s,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(n=>e.jsx(Vs,{className:"h-32 w-full"},n))})}):!t||t.length===0?e.jsx(_s,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pl,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Start shopping to see your orders here!"}),e.jsx(G,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(_s,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(n=>{var a,i,l;return e.jsx(Ne,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${n.id}`),children:e.jsxs(De,{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:Ss(new Date(n.created_at),"MMM d, yyyy")})]}),e.jsx(Ge,{className:pMe[n.status],children:OM[n.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=n.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),n.items&&n.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",n.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=n.items)==null?void 0:i.length)===1?n.items[0].product_name:`${(l=n.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(n.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n.tracking_url&&e.jsxs(G,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(n.tracking_url,"_blank")},children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(ya,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},n.id)})})})}const bHe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function zRs({currentStatus:s,statusHistory:t}){const r=bHe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:bHe.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(Mn,{className:"h-4 w-4"}):o?e.jsx(cn,{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:OM[n]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ss(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},n)})})}function $Rs(){var N;const{orderId:s}=Xi(),t=vr(),{data:r,isLoading:n,refetch:a}=YLs(s||""),i=QLs(),l=JLs(),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(""),[g,v]=k.useState(null),j=async S=>{v(S);try{await i.mutateAsync({orderId:s,itemId:S}),ue.success("Proof approved!"),a()}catch{ue.error("Failed to approve proof")}finally{v(null)}},b=async()=>{if(d){v(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:m}),ue.success("Revision requested"),c(!1),x(""),h(null),a()}catch{ue.error("Failed to request revision")}finally{v(null)}}};return n?e.jsx(_s,{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(Vs,{className:"h-64 w-full"}),e.jsx(Vs,{className:"h-48 w-full"})]}),e.jsx(Vs,{className:"h-96 w-full"})]})}):r?e.jsxs(_s,{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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsx(zt,{children:"Order Status"}),e.jsx(Ge,{className:pMe[r.status],children:OM[r.status]})]}),e.jsx(De,{children:e.jsx(zRs,{currentStatus:r.status,statusHistory:r.status_history})})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Items"})}),e.jsx(De,{className:"space-y-4",children:(N=r.items)==null?void 0:N.map(S=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:S.product_name}),S.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",S.quantity," × $",Number(S.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(S.unit_price)*S.quantity).toFixed(2)]})]}),S.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:S.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Qb,{className:"h-4 w-4"}),"View Artwork",e.jsx(Yr,{className:"h-3 w-3"})]})]}),S.proof_url&&e.jsxs("div",{className:"bg-muted rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Proof Ready for Review"}),e.jsxs("a",{href:S.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(Qb,{className:"h-4 w-4"}),"View Proof",e.jsx(Yr,{className:"h-3 w-3"})]}),S.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(G,{size:"sm",onClick:()=>j(S.id),disabled:g===S.id,children:[g===S.id?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Mh,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{h(S.id),c(!0)},disabled:g===S.id,children:[e.jsx(PO,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),S.proof_status==="approved"&&e.jsxs(Ge,{className:"bg-green-100 text-green-800",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),S.proof_status==="rejected"&&S.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Ge,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.proof_notes})]})]})]},S.id))})]}),r.shipping_name&&e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(DO,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"font-medium",children:r.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[r.shipping_address,e.jsx("br",{}),r.shipping_city,", ",r.shipping_state," ",r.shipping_zip]}),r.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:r.tracking_number}),r.tracking_url&&e.jsxs(G,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(r.tracking_url,"_blank"),children:["Track Package",e.jsx(Yr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(Ne,{className:"sticky top-4",children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Order Summary"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Ss(new Date(r.created_at),"MMMM d, yyyy")]}),e.jsx(po,{}),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(po,{}),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(po,{}),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(js,{children:[e.jsx(bs,{children:"Request Changes"}),e.jsx(Fr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(ur,{placeholder:"Describe the changes needed...",value:m,onChange:S=>x(S.target.value),rows:4}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{onClick:b,disabled:!m.trim()||g!==null,children:[g?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(_s,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pl,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Order not found"}),e.jsx(G,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function URs(){const s=vr(),[t]=Lc();return t.get("session_id"),k.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(_s,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(Ne,{children:e.jsxs(De,{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(Mn,{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(Pl,{className:"h-4 w-4"}),"What happens next?"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("li",{children:"• We'll review your order and prepare it for production"}),e.jsx("li",{children:"• If your order requires a proof, you'll receive it for approval"}),e.jsx("li",{children:"• Once approved, we'll begin production and ship when ready"}),e.jsx("li",{children:"• You'll receive tracking info when your order ships"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(G,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(Ga,{className:"h-4 w-4 ml-2"})]}),e.jsx(G,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function qRs(){const{user:s}=As(),[t,r]=k.useState("store"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,h]=k.useState(5),[m,x]=k.useState(""),[g,v]=k.useState(!1),[j,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(null),[P,D]=k.useState(!1),{hasSubmittedReview:B,submitReview:z,markPostedToGoogle:F}=xnt(),{data:$}=qxt(),{data:X,isLoading:K}=Uxt(),{data:Q,isLoading:Y}=i6s(n),{data:ne,isLoading:de}=o6s(s==null?void 0:s.id),{data:ce=0}=c6s(s==null?void 0:s.id),ae=d6s(),ie=new Set((ne==null?void 0:ne.map(Pe=>Pe.item_id))||[]),me=async()=>{if(i)try{const Pe=await ae.mutateAsync(i.id);i.item_type==="reelflow_credits"?ue.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ue.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Pe){ue.error(Pe.message||"Failed to purchase item")}},oe=async()=>{if(!m.trim()){ue.error("Please write a review");return}v(!0);const Pe=await z(d,m);v(!1),Pe.success?(ue.success("Thank you for your review! You earned 25 points!"),S(m),b(!0),x(""),h(5)):ue.error(Pe.error||"Failed to submit review")},ge=()=>{navigator.clipboard.writeText(N),ue.success("Review copied to clipboard!")},be=()=>{F(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Oe=()=>{b(!1),c(!1),S("")};return K||Y||de?e.jsx(_s,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vs,{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(Pe=>e.jsx(Vs,{className:"h-64"},Pe))})]})}):e.jsxs(_s,{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(Ne,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(De,{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(Qn,{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:ce.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(Zi,{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(xc,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(bx,{open:P,onOpenChange:D,children:e.jsxs(Ne,{className:"border-primary/20",children:[e.jsx(_x,{asChild:!0,children:e.jsx(Ot,{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(Zi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Nr,{children:"See all the ways you can earn spendable points"})]})]}),P?e.jsx(xp,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(so,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(wx,{children:e.jsx(De,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[$==null?void 0:$.filter(Pe=>Pe.is_active).map(Pe=>{const Ee=$e=>{switch($e){case"event_attendance":return e.jsx(rn,{className:"h-5 w-5"});case"leave_review":return e.jsx(Qn,{className:"h-5 w-5"});case"add_listing":return e.jsx(Cn,{className:"h-5 w-5"});case"first_contact":return e.jsx(fr,{className:"h-5 w-5"});case"first_video":return e.jsx(sn,{className:"h-5 w-5"});case"first_community_post":return e.jsx(bi,{className:"h-5 w-5"});default:return e.jsx(li,{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:Ee(Pe.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Pe.action_name}),Pe.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Pe.description})]}),e.jsxs(Ge,{variant:"secondary",className:"font-bold shrink-0",children:["+",Pe.points]})]},Pe.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(xc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Streak Bonuses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Attend consecutive weeks for bonus points!"})]}),e.jsx(Ge,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!B&&e.jsx(Ne,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(De,{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(bi,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs(G,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(Rn,{value:t,onValueChange:r,children:[e.jsxs(Dn,{children:[e.jsxs(Xt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(Kv,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Xt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4"}),"My Rewards",ne&&ne.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:ne.length})]})]}),e.jsxs(as,{value:"store",className:"mt-6",children:[X&&X.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(G,{variant:n===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),X.map(Pe=>e.jsxs(G,{variant:n===Pe.id?"default":"outline",size:"sm",onClick:()=>a(Pe.id),children:[Pe.icon&&`${Pe.icon} `,Pe.name]},Pe.id))]}),!Q||Q.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(li,{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(Pe=>{const Ee=Pe.item_type==="reelflow_credits",$e=!Ee&&ie.has(Pe.id),Se=!Ee&&Pe.max_quantity!==null&&Pe.current_quantity===0,ze=ce>=Pe.points_cost;return e.jsxs(Ne,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${$e?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(Pe),children:[Pe.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Pe.preview_image_url,alt:Pe.name,className:"w-full h-full object-cover"}),$e&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Se&&!$e&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ge,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(li,{className:"h-12 w-12 text-muted-foreground/50"}),$e&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Ot,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(zt,{className:"text-lg",children:Pe.name}),e.jsxs(Ge,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),Pe.points_cost]})]}),Pe.category&&e.jsxs(Ge,{variant:"outline",className:"w-fit",children:[Pe.category.icon&&`${Pe.category.icon} `,Pe.category.name]})]}),e.jsxs(De,{children:[e.jsx(Nr,{className:"mb-4 line-clamp-2",children:Pe.description||"No description available"}),Pe.max_quantity!==null&&!$e&&!Ee&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Pe.current_quantity," of ",Pe.max_quantity," remaining"]}),Ee&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Pe.max_quantity," ReelFlow credits per purchase"]}),$e?e.jsx(G,{className:"w-full",onClick:Te=>{Te.stopPropagation(),Pe.file_url&&P_e(Pe.file_url,Pe.name)},disabled:!Pe.file_url,children:Pe.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(G,{className:"w-full",onClick:Te=>{Te.stopPropagation(),l(Pe)},disabled:Se||!ze,children:Se?"Sold Out":ze?e.jsxs(e.Fragment,{children:[e.jsx(Kv,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Pe.points_cost-ce} more pts`})]})]},Pe.id)})})]}),e.jsx(as,{value:"my-rewards",className:"mt-6",children:!ne||ne.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Pl,{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:ne.map(Pe=>{var Ee,$e,Se,ze,Te,ye,ct;return e.jsxs(Ne,{className:"overflow-hidden",children:[(Ee=Pe.item)!=null&&Ee.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Pe.item.preview_image_url,alt:(($e=Pe.item)==null?void 0:$e.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(li,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Ot,{className:"pb-2",children:[e.jsx(zt,{className:"text-lg",children:((Se=Pe.item)==null?void 0:Se.name)||"Unknown Item"}),e.jsxs(Nr,{className:"text-xs",children:["Purchased for ",Pe.points_spent," points • ",new Date(Pe.purchased_at).toLocaleDateString()]})]}),e.jsx(De,{children:((ze=Pe.item)==null?void 0:ze.item_type)==="reelflow_credits"?e.jsxs(G,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Mn,{className:"h-4 w-4 mr-2 text-green-500"}),(Te=Pe.item)==null?void 0:Te.max_quantity," Credits Applied"]}):e.jsx(G,{className:"w-full",onClick:()=>{var ve,rt;(ve=Pe.item)!=null&&ve.file_url&&P_e(Pe.item.file_url,(rt=Pe.item)==null?void 0:rt.name)},disabled:!((ye=Pe.item)!=null&&ye.file_url),children:((ct=Pe.item)==null?void 0:ct.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Pe.id)})})})]})]}),e.jsx(Yo,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Confirm Purchase"}),e.jsxs(Uo,{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:[ce," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ce-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:me,disabled:ae.isPending,children:ae.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(vs,{open:o,onOpenChange:Pe=>{!Pe&&j?Oe():c(Pe)},children:e.jsx(ys,{children:j?e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Fr,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',N,'"']})]}),e.jsxs(G,{variant:"outline",className:"w-full",onClick:ge,children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(on,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(G,{variant:"outline",onClick:Oe,children:"Maybe Later"}),e.jsxs(G,{onClick:be,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(bs,{children:"Leave a Review"}),e.jsx(Fr,{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(Pe=>e.jsx("button",{type:"button",onClick:()=>h(Pe),className:"focus:outline-none",children:e.jsx(Qn,{className:`h-8 w-8 transition-colors ${d>=Pe?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Pe))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(ur,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:m,onChange:Pe=>x(Pe.target.value),rows:4})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:oe,disabled:g,className:"bg-yellow-600 hover:bg-yellow-700",children:g?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(vs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[T==null?void 0:T.name,e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),T==null?void 0:T.points_cost]})]}),(T==null?void 0:T.category)&&e.jsxs(Ge,{variant:"outline",className:"w-fit",children:[T.category.icon&&`${T.category.icon} `,T.category.name]})]}),(T==null?void 0:T.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:T.preview_image_url,alt:T.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(T==null?void 0:T.description)||"No description available"}),(T==null?void 0:T.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",T==null?void 0:T.max_quantity," ReelFlow credits per purchase"]}),(T==null?void 0:T.item_type)!=="reelflow_credits"&&(T==null?void 0:T.max_quantity)!==null&&!ie.has((T==null?void 0:T.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T==null?void 0:T.current_quantity," of ",T==null?void 0:T.max_quantity," remaining"]})]}),e.jsx(on,{children:T&&T.item_type!=="reelflow_credits"&&ie.has(T.id)?e.jsx(G,{className:"w-full",onClick:()=>{T.file_url&&P_e(T.file_url,T.name)},disabled:!T.file_url,children:T.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Access"]})}):T&&e.jsx(G,{className:"w-full",onClick:()=>{A(null),l(T)},disabled:T.item_type!=="reelflow_credits"&&T.max_quantity!==null&&T.current_quantity===0||ce{s&&de()},[s==null?void 0:s.id]);const de=async()=>{if(!s)return;o(!0),N(!1),j(!0);const{data:Te}=await H.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Te==null||Te.forEach(rt=>{rt.action_key==="referral_signup"&&m(rt.points),rt.action_key==="referral_paid"&&g(rt.points)});const{data:ye}=await H.from("profiles").select("name").eq("id",s.id).maybeSingle();ye!=null&&ye.name&&T(ye.name);let{data:ct}=await H.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!ct){const{data:rt}=await H.rpc("generate_agent_referral_code",{_user_id:s.id}),Re=rt||`agent${s.id.slice(0,6)}`,{data:Qe,error:Ke}=await H.from("agent_referral_codes").insert({user_id:s.id,code:Re}).select("code").maybeSingle();!Ke&&Qe&&(ct=Qe)}i((ct==null?void 0:ct.code)??null);const{data:ve}=await H.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(ve&&ve.length>0){const rt=ve.map(Ke=>Ke.referred_user_id),{data:Re}=await H.from("profiles").select("id, name, email").in("id",rt),Qe=new Map((Re==null?void 0:Re.map(Ke=>[Ke.id,Ke]))??[]);d(ve.map(Ke=>({...Ke,referred_profile:Qe.get(Ke.referred_user_id)??null})))}else d([]);o(!1)},ce=k.useMemo(()=>a?`${VRs}/trial?ref=${a}`:"",[a]),ae=c.length,ie=c.filter(Te=>Te.status==="qualified").length,me=c.filter(Te=>Te.signup_points_awarded).length*h+c.filter(Te=>Te.paid_points_awarded).length*x,oe=async()=>{ce&&(await navigator.clipboard.writeText(ce),ue.success("Referral link copied!"))},ge=()=>{const Te=encodeURIComponent("Join me on LevelUp"),ye=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: ${ce} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Te}&body=${ye}`},be=()=>{const Te=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ce}`);window.location.href=`sms:?&body=${Te}`},Oe=async()=>{if(navigator.share&&ce)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:ce})}catch{}else oe()},Me=Te=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Te.trim()),Pe=Te=>{const ye=(Te??D).trim().replace(/,$/,"");if(!ye)return;const ct=ye.split(/[\s,;]+/).filter(Boolean),ve=[...z];let rt=0;for(const Re of ct){if(!Me(Re)){ue.error(`Invalid email: ${Re}`);continue}ve.includes(Re)||(ve.push(Re),rt++)}F(ve),rt>0&&B("")},Ee=Te=>F(z.filter(ye=>ye!==Te)),$e=()=>{Q(`${S?S.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),X("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."),P(!0)},Se=Te=>{const ye=Te.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),ct=S||"A fellow agent",ve="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",rt=ce;return`
LevelUp
You're Invited

${ct} thinks you'd love LevelUp 🎉

${ye}

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

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

`.trim()},ze=async()=>{if(z.length===0&&(D.trim()&&Pe(),z.length===0)){ue.error("Add at least one recipient");return}if(!K.trim()){ue.error("Subject is required");return}ne(!0);const Te=Se($);let ye=0,ct=0;for(const ve of z)try{const{data:rt,error:Re}=await H.functions.invoke("gmail-send",{body:{to:ve,subject:K,body:Te,source:"referral_invite"}});if(Re||rt!=null&&rt.error)throw new Error((Re==null?void 0:Re.message)||(rt==null?void 0:rt.error));ye++}catch(rt){console.error("Gmail send failed for",ve,rt),ct++}ne(!1),ye>0?(ue.success(`Invite sent to ${ye} ${ye===1?"person":"people"}`+(ct>0?` (${ct} failed)`:"")),F([]),B(""),P(!1)):ue.error("Failed to send invites")};return!b&&!v?e.jsx(_s,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(il,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(Ne,{className:"border-2 border-dashed",children:[e.jsxs(Ot,{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-muted flex items-center justify-center mb-3",children:e.jsx(Kc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(zt,{children:"Refer & Earn is for active members"}),e.jsx(Nr,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(_s,{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(il,{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(li,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[h," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[x," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(fr,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ae}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Mn,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(Ne,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Zi,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:me.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Nr,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ke,{readOnly:!0,value:l?"Loading…":ce,className:"font-mono text-sm",onFocus:Te=>Te.currentTarget.select()}),e.jsxs(G,{onClick:oe,disabled:!ce,children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[r&&e.jsxs(G,{size:"sm",onClick:$e,disabled:!ce,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ge,disabled:!ce,children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:be,disabled:!ce,children:[e.jsx(bi,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:Oe,disabled:!ce,children:[e.jsx(Pc,{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(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Your Referrals"}),e.jsx(Nr,{children:"Track who joined and when they upgrade."})]}),e.jsx(De,{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(fr,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(Te=>{var ve,rt;const ye=((ve=Te.referred_profile)==null?void 0:ve.name)||((rt=Te.referred_profile)==null?void 0:rt.email)||"New agent",ct=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Te.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:ye}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",ct]})]}),Te.status==="qualified"?e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Mn,{className:"h-3 w-3 mr-1"})," Paid · +",h+x," pts"]}):e.jsxs(Ge,{variant:"secondary",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Signed up · +",h," pts"]})]},Te.id)})})})]}),e.jsx(Ne,{className:"bg-muted/30",children:e.jsxs(De,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[h," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[x," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(po,{className:"opacity-0"})]}),e.jsx(vs,{open:A,onOpenChange:P,children:e.jsxs(ys,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Fr,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:n}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[z.map(Te=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[Te,e.jsx("button",{type:"button",onClick:()=>Ee(Te),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Te}`,children:e.jsx(_r,{className:"h-3 w-3"})})]},Te)),e.jsx("input",{type:"email",value:D,onChange:Te=>B(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"||Te.key===","||Te.key===" "?(Te.preventDefault(),Pe()):Te.key==="Backspace"&&!D&&z.length>0&&F(z.slice(0,-1))},onBlur:()=>D.trim()&&Pe(),onPaste:Te=>{const ye=Te.clipboardData.getData("text");/[\s,;]/.test(ye)&&(Te.preventDefault(),Pe(ye))},placeholder:z.length===0?"name@example.com, another@example.com":"Add another…",className:"flex-1 min-w-[160px] bg-transparent outline-none text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press Enter, comma, or space to add. You can paste multiple emails at once."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email-subject",children:"Subject"}),e.jsx(ke,{id:"email-subject",value:K,onChange:Te=>Q(Te.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(ur,{id:"personal-note",value:$,onChange:Te=>X(Te.target.value),rows:4,placeholder:"Write a quick note explaining why they'd love LevelUp…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",n]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",K||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Se($),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>P(!1),disabled:Y,children:"Cancel"}),e.jsxs(G,{onClick:ze,disabled:Y,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),Y?"Sending…":`Send${z.length>0?` to ${z.length}`:""}`]})]})]})})]})}const Egt=()=>{const{user:s}=As(),t=es(),r=gt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await H.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(h)throw h;return d||[]},enabled:!!s}),n=gt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await H.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(h)throw h;return d||[]},enabled:!!s}),a=Lt({mutationFn:async d=>{const{data:h,error:m}=await H.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=Lt({mutationFn:async({id:d,...h})=>{const{data:m,error:x}=await H.from("smart_presentations").update(h).eq("id",d).select().single();if(x)throw x;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=Lt({mutationFn:async d=>{const{data:h,error:m}=await H.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ue.success("Presentation published!")}}),o=Lt({mutationFn:async d=>{const{error:h}=await H.from("smart_presentations").update({status:"archived"}).eq("id",d);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ue.success("Presentation archived")}}),c=Lt({mutationFn:async d=>{const{error:h}=await H.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ue.success("Saved as template!")}});return{presentations:r.data||[],templates:n.data||[],isLoading:r.isLoading,templatesLoading:n.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},GRs=()=>{const s=vr(),{presentations:t,isLoading:r,archivePresentation:n,saveAsTemplate:a}=Egt(),i=o=>o.status==="draft"?e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Ge,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Ge,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ue.success("Link copied!")};return e.jsx(_s,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(G,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Create Presentation"]})]}),r?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Vs,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(Ne,{children:e.jsxs(De,{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(n0,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs(G,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(Ne,{className:"hover:shadow-sm transition-shadow",children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(ln,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",Ss(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Eg,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Da,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Da,{onClick:()=>a.mutate(o),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Da,{onClick:()=>n.mutate(o.id),className:"text-destructive",children:[e.jsx(Uj,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},_He={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."}]},WRs=[{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 KRs(s){const t=_He[s];if(t)return t;const r=s.toLowerCase();for(const[n,a]of Object.entries(_He))if(r.includes(n.toLowerCase())||n.toLowerCase().includes(r))return a;return WRs}function YRs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState("script"),[o,c]=k.useState(0),[d,h]=k.useState(0),{canRecord:m}=Bmt(),x=O_(),[g,v]=k.useState(""),[j,b]=k.useState(!1),[N,S]=k.useState(!0),[T,A]=k.useState(!1),[P,D]=k.useState(null),B=KRs(s),z=()=>{l("script"),c(0),h(0),v(""),b(!1),S(!0),A(!1),D(null)},F=Y=>{!Y&&(i==="uploading"||i==="processing")||(a(Y),Y||z())},$=Y=>{D(Y),v(B[Y].text),b(!1)},X=()=>{l("record"),S(g.trim().length>0)},K=()=>{v(""),S(!1),l("record")},Q=k.useCallback(async(Y,ne)=>{l("uploading");try{const de=s||"Presentation Video",{videoId:ce,uploadUrl:ae,libraryId:ie}=await sT(de),{apiKey:me}=await rT(ce),oe=new XMLHttpRequest;oe.upload.onprogress=Pe=>{Pe.lengthComputable&&c(Pe.loaded/Pe.total*100)},await new Promise((Pe,Ee)=>{oe.onload=()=>oe.status>=200&&oe.status<300?Pe():Ee(new Error("Upload failed")),oe.onerror=()=>Ee(new Error("Upload failed")),oe.open("PUT",ae),oe.setRequestHeader("AccessKey",me),oe.send(Y)}),l("processing");let ge=0;const be=Date.now(),Oe=9e4;let Me=null;for(;ge<4;){if(await new Promise(Ee=>setTimeout(Ee,3e3)),Date.now()-be>Oe){const Ee=Y.size/1048576,$e=`https://iframe.mediadelivery.net/embed/${ie}/${ce}?responsive=true`;await x.mutateAsync({bunny_video_id:ce,playback_url:$e,file_size_mb:Ee,title:de,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r($e),ue.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Pe=await u1(ce);if(ge=Pe.status,h(Pe.encodeProgress||0),ge===4)Me={playbackUrl:Pe.directPlayUrl,thumbnailUrl:Pe.thumbnailUrl,previewUrl:Pe.previewUrl||null,duration:Pe.length||ne,fileSizeMb:(Pe.storageSize||Y.size)/(1024*1024)};else if(ge===5||ge===6)throw new Error("Video processing failed")}if(!Me)throw new Error("No video data");await x.mutateAsync({bunny_video_id:ce,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:de,status:"ready",touch_type:"presentation"}),r(Me.playbackUrl),ue.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(de){console.error("Recording upload error:",de),ue.error("Failed to process video. Please try again."),l("record")}},[s,t,r,x]);return e.jsxs(vs,{open:n,onOpenChange:F,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(sn,{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(js,{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:B.map((Y,ne)=>e.jsxs("button",{onClick:()=>$(ne),className:Bt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",P===ne?"border-primary bg-primary/5 ring-1 ring-primary":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ln,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:Y.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:Y.text})]},ne))})]}),g&&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"}),!j&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>b(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),"Edit"]})]}),j?e.jsx(ur,{value:g,onChange:Y=>v(Y.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:g})]}),!g&&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(ur,{value:g,onChange:Y=>{v(Y.target.value),D(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:K,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(G,{onClick:X,disabled:!1,children:g.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(od,{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."}),g.trim()&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>S(!N),className:"h-7 text-xs gap-1",children:[N?e.jsx(am,{className:"h-3 w-3"}):e.jsx(jn,{className:"h-3 w-3"}),N?"Hide Script":"Show Script"]})]}),e.jsx(xL,{maxDurationSeconds:600,onRecordingComplete:Q,onRecordingStateChange:A,onError:Y=>ue.error(Y),teleprompterContent:g.trim()?e.jsx(cMe,{text:g,isVisible:N,onToggleVisibility:()=>S(!N),isRecording:T,startCountdown:!1}):void 0}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(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(ri,{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(ri,{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(mi,{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 ZRs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState("idle"),[d,h]=k.useState(0),m=k.useRef(null),x=O_(),{data:g}=Age(),v=(g==null?void 0:g.total_storage_mb)||0,b=((g==null?void 0:g.max_storage_mb)||1024)-v,N=()=>{l(null),c("idle"),h(0)},S=B=>{!B&&o!=="idle"&&o!=="done"||(a(B),B||N())},T=B=>{var $;const z=($=B.target.files)==null?void 0:$[0];if(!z)return;if(!z.type.startsWith("video/")){ue.error("Please select a video file");return}const F=z.size/(1024*1024);if(F>500){ue.error("Video file must be less than 500MB");return}if(F>b){ue.error(`Not enough storage. You have ${b.toFixed(1)} MB remaining.`);return}l(z)},A=k.useCallback(async()=>{if(i){c("creating"),h(0);try{const B=s||i.name,{data:z,error:F}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:B,isAgentVideo:!0}});if(F)throw new Error(F.message);const{videoId:$,libraryId:X}=z;c("uploading");const{data:K,error:Q}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$,isAgentVideo:!0}});if(Q)throw new Error(Q.message);await new Promise((de,ce)=>{const ae=new XMLHttpRequest;ae.upload.addEventListener("progress",ie=>{ie.lengthComputable&&h(Math.round(ie.loaded/ie.total*100))}),ae.addEventListener("load",()=>ae.status>=200&&ae.status<300?de():ce(new Error(`Upload failed (${ae.status})`))),ae.addEventListener("error",()=>ce(new Error("Upload failed"))),ae.open("PUT",K.uploadUrl),ae.setRequestHeader("AccessKey",K.apiKey),ae.send(i)}),c("processing");const Y=i.size/(1024*1024),ne=`https://iframe.mediadelivery.net/embed/${X}/${$}`;await x.mutateAsync({bunny_video_id:$,playback_url:ne,file_size_mb:Y,title:B,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(ne),c("done"),ue.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(B){console.error("Upload error:",B),ue.error(B instanceof Error?B.message:"Failed to upload video"),c("idle")}}},[i,s,t,r,x]),P=()=>{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:S,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(oa,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(js,{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(sn,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!D&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(_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 B;return(B=m.current)==null?void 0:B.click()},children:[e.jsx(oa,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:m,type:"file",accept:"video/*",className:"hidden",onChange:T,disabled:D}),D&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:P()})]}),e.jsx(ri,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),disabled:D,children:"Cancel"}),e.jsx(G,{onClick:A,disabled:!i||D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const wHe=[{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"}],jHe=()=>{const s=vr(),{id:t}=Xi(),{user:r}=As(),{templates:n,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Egt(),{isGmailConnected:c,gmailEmail:d}=Oh(),[h,m]=k.useState(!1),[x,g]=k.useState("client"),[v,j]=k.useState(!1),[b,N]=k.useState(""),[S,T]=k.useState([]),[A,P]=k.useState(!1),[D,B]=k.useState(null),[z,F]=k.useState(!1),[$,X]=k.useState(""),[K,Q]=k.useState(""),[Y,ne]=k.useState(""),[de,ce]=k.useState("buyer"),[ae,ie]=k.useState(""),[me,oe]=k.useState(null),[ge,be]=k.useState(""),[Oe,Me]=k.useState([]),[Pe,Ee]=k.useState("schedule_call"),[$e,Se]=k.useState("Schedule a Call"),[ze,Te]=k.useState(""),[ye,ct]=k.useState(""),[ve,rt]=k.useState(null),[Re,Qe]=k.useState(t||null),[Ke,Ce]=k.useState(null),[nt,$t]=k.useState(!1),lt=async(yt,ss)=>{if(!r)return;const Is=5*1024*1024;if(yt.size>Is){ue.error("Image must be under 5MB");return}if(!yt.type.startsWith("image/")){ue.error("Please upload an image file");return}rt(ss);try{const fs=yt.name.split(".").pop()||"jpg",ar=`${r.id}/${Date.now()}.${fs}`,{error:Er}=await H.storage.from("listing-photos").upload(ar,yt);if(Er)throw Er;const{data:{publicUrl:Tr}}=H.storage.from("listing-photos").getPublicUrl(ar);et(ss,{image_url:Tr}),ue.success("Image uploaded")}catch{ue.error("Failed to upload image")}finally{rt(null)}};k.useEffect(()=>{t&&it(t)},[t]);const it=async yt=>{const{data:ss,error:Is}=await H.from("smart_presentations").select("*").eq("id",yt).single();if(Is||!ss)return;const fs=ss;if(j(!0),be(fs.title),X(fs.client_name||""),ie(fs.property_address||""),Me(fs.sections||[]),Ee(fs.cta_type||"schedule_call"),Se(fs.cta_label||"Schedule a Call"),Te(fs.cta_url||""),ct(fs.heading||""),Ce(fs.share_token),$t(fs.status==="published"),Qe(fs.id),g("builder"),fs.contact_id){const{data:ar}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",fs.contact_id).maybeSingle();ar&&(B(ar),Q(ar.email||""),ne(ar.phone||""))}};k.useEffect(()=>{if(!r||b.length<1){T([]);return}const yt=setTimeout(async()=>{P(!0);const{data:ss}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",r.id).or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%`).limit(10);T(ss||[]),P(!1)},300);return()=>clearTimeout(yt)},[b,r]);const Nt=yt=>{B(yt),X(`${yt.first_name} ${yt.last_name||""}`.trim()),Q(yt.email||""),ne(yt.phone||""),F(!1)},Ft=async()=>{if(!$.trim()){ue.error("Client name is required");return}const yt=$.trim().split(" "),ss=yt[0],Is=yt.slice(1).join(" ")||null,{data:fs,error:ar}=await H.from("innercircle_contacts").insert({owner_user_id:r.id,first_name:ss,last_name:Is,email:K||null,phone:Y||null,lead_source:"Smart Presentation"}).select().single();if(ar){ue.error("Failed to create client");return}B(fs),ue.success("Client created & saved to Agent OS"),g("template")},at=yt=>{oe(yt);const ss=(yt.sections||[]).map(Is=>({...Is,is_visible:!0,video_url:"",text:""}));if(Me(ss),be(yt.name+($?` for ${$}`:"")),yt.cta_config){const Is=yt.cta_config;Ee(Is.type||"schedule_call"),Se(Is.label||"Schedule a Call")}g("builder")},Ie=()=>{Me([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),be($?`Presentation for ${$}`:"New Presentation"),g("builder")},et=(yt,ss)=>{Me(Is=>Is.map((fs,ar)=>ar===yt?{...fs,...ss}:fs))},Dt=yt=>{et(yt,{is_visible:!Oe[yt].is_visible})},Jt=()=>{Me(yt=>[...yt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},cs=yt=>{Me(ss=>ss.filter((Is,fs)=>fs!==yt))},Ht=async()=>{if(!ge.trim()){ue.error("Title is required");return}try{if(Re){const yt=await l.mutateAsync({id:Re,title:ge,sections:Oe,client_name:$,property_address:ae||null,cta_type:Pe,cta_label:$e,cta_url:ze||null,heading:ye||null});ue.success("Saved")}else{const yt=await i.mutateAsync({title:ge,contact_id:(D==null?void 0:D.id)||void 0,client_name:$,property_address:ae||void 0,template_id:(me==null?void 0:me.id)||void 0,sections:Oe,cta_type:Pe,cta_label:$e,cta_url:ze||void 0,heading:ye||void 0});Qe(yt.id),Ce(yt.share_token),ue.success("Presentation created!")}}catch(yt){console.error("Failed to save presentation:",yt);const ss=(yt==null?void 0:yt.message)||(yt==null?void 0:yt.toString())||"Unknown error";ue.error(`Failed to save: ${ss}`)}},dt=async()=>{try{await Ht();const yt=Re;if(yt){const ss=await o.mutateAsync(yt);Ce(ss.share_token),$t(!0),g("share")}}catch(yt){console.error("Failed to publish presentation:",yt),ue.error(`Failed to publish: ${(yt==null?void 0:yt.message)||"Unknown error"}`)}},Qt=Ke?`https://presentations.relevelup.com/${Ke}`:"";return e.jsx(_s,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(wa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:v?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x==="client"&&"Who is this presentation for?",x==="template"&&"Choose a starting template",x==="builder"&&"Customize your presentation",x==="share"&&"Share with your client"]})]})]}),!v&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((yt,ss)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Bt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",x===yt?"bg-primary text-primary-foreground":ss<["client","template","builder","share"].indexOf(x)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:ss<["client","template","builder","share"].indexOf(x)?e.jsx(Hn,{className:"h-4 w-4"}):ss+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:yt}),ss<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},yt))}),x==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{B(null),X(""),Q(""),ne(""),F(!1),g("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(Zr,{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(Ga,{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(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(fn,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search by name or email...",value:b,onChange:yt=>N(yt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(Vs,{className:"h-12 w-full"}),S.map(yt=>e.jsxs("button",{onClick:()=>Nt(yt),className:Bt("w-full text-left p-3 rounded-lg border transition-colors",(D==null?void 0:D.id)===yt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[yt.first_name," ",yt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:yt.email||yt.phone||"No contact info"})]},yt.id)),!b&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),b&&S.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),D&&e.jsxs(G,{onClick:()=>g("template"),className:"w-full gap-2",children:["Continue with ",D.first_name,e.jsx(Ga,{className:"h-4 w-4"})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(he,{className:"text-xs",children:"Name *"}),e.jsx(ke,{value:$,onChange:yt=>{X(yt.target.value),F(!0),B(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Email"}),e.jsx(ke,{value:K,onChange:yt=>Q(yt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Phone"}),e.jsx(ke,{value:Y,onChange:yt=>ne(yt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Client Type"}),e.jsxs(zs,{value:de,onValueChange:ce,children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"buyer",children:"Buyer"}),e.jsx(mt,{value:"seller",children:"Seller"}),e.jsx(mt,{value:"recruit",children:"Recruit"}),e.jsx(mt,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Property Address"}),e.jsx(ke,{value:ae,onChange:yt=>ie(yt.target.value),placeholder:"Optional"})]})]}),z&&$&&e.jsxs(G,{onClick:Ft,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Ga,{className:"h-4 w-4"})]})]})]})]})]}),x==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Rn,{defaultValue:"system",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"mine",children:"My Core Templates"}),e.jsx(Xt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Xt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(as,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(yt=>e.jsx(Vs,{className:"h-32"},yt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(yt=>!yt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):n.filter(yt=>!yt.is_system).map(yt=>e.jsx(NHe,{template:yt,onSelect:at},yt.id))})}),e.jsx(as,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(yt=>yt.is_system).map(yt=>e.jsx(NHe,{template:yt,onSelect:at},yt.id))})}),e.jsx(as,{value:"blank",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx(G,{onClick:Ie,children:"Start from Scratch"})]})})})]}),e.jsxs(G,{variant:"outline",onClick:()=>g("client"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back"]})]}),x==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(De,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Presentation Title"}),e.jsx(ke,{value:ge,onChange:yt=>be(yt.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Page Heading"}),e.jsx(ke,{value:ye,onChange:yt=>ct(yt.target.value),placeholder:$?`Welcome, ${$}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Client Name"}),e.jsx(ke,{value:$,onChange:yt=>X(yt.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Property Address"}),e.jsx(ke,{value:ae,onChange:yt=>ie(yt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx(G,{variant:"outline",size:"sm",onClick:Jt,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Oe.map((yt,ss)=>e.jsx(Ne,{className:Bt(!yt.is_visible&&"opacity-50"),children:e.jsx(De,{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(Su,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:yt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ke,{value:yt.title,onChange:Is=>et(ss,{title:Is.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Dt(ss),children:yt.is_visible?e.jsx(jn,{className:"h-4 w-4"}):e.jsx(am,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>cs(ss),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]}),e.jsx(ke,{value:yt.description||"",onChange:Is=>et(ss,{description:Is.target.value}),placeholder:"Section description...",className:"text-sm"}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs",children:"Video URL"}),e.jsx(ke,{value:yt.video_url||"",onChange:Is=>et(ss,{video_url:Is.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(YRs,{sectionTitle:yt.title,contactId:D==null?void 0:D.id,onVideoReady:Is=>et(ss,{video_url:Is})}),e.jsx(ZRs,{sectionTitle:yt.title,contactId:D==null?void 0:D.id,onVideoReady:Is=>et(ss,{video_url:Is})}),e.jsx(sL,{userId:r==null?void 0:r.id,onSelect:Is=>et(ss,{video_url:Is})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),yt.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:yt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>et(ss,{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:[ve===ss?e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx($v,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:ve===ss?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:ve===ss,onChange:Is=>{var ar;const fs=(ar=Is.target.files)==null?void 0:ar[0];fs&<(fs,ss),Is.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Text (optional)"}),e.jsx(y0,{content:yt.text||"",onChange:Is=>et(ss,{text:Is}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},ss))})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Call to Action"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"CTA Type"}),e.jsxs(zs,{value:Pe,onValueChange:yt=>{Ee(yt);const ss=wHe.find(Is=>Is.value===yt);ss&&Se(ss.label)},children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:wHe.map(yt=>e.jsx(mt,{value:yt.value,children:yt.label},yt.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Button Label"}),e.jsx(ke,{value:$e,onChange:yt=>Se(yt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(he,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(ke,{value:ze,onChange:yt=>Te(yt.target.value),placeholder:"https://calendly.com/..."}),!ze&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!v&&e.jsxs(G,{variant:"outline",onClick:()=>g("template"),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(G,{variant:"outline",onClick:Ht,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(G,{onClick:dt,disabled:o.isPending,className:"gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),nt?"Update & Reshare":"Publish & Share"]})]})]})]}),x==="share"&&Ke&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(De,{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(Hn,{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 ",$||"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(ke,{value:Qt,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(G,{onClick:()=>{navigator.clipboard.writeText(Qt),ue.success("Link copied!")},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(G,{variant:"outline",className:"gap-2",onClick:()=>{const yt=`Hi ${$||""}! I put together something for you — check it out: ${Qt}`;navigator.clipboard.writeText(yt),ue.success("Message copied!")},children:[e.jsx(bi,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(G,{variant:"outline",className:"gap-2",onClick:()=>{c?m(!0):window.open(`mailto:${K||""}?subject=${encodeURIComponent(ge)}&body=${encodeURIComponent(`Hi ${(D==null?void 0:D.first_name)||($==null?void 0:$.split(" ")[0])||""}, I put together a personalized presentation for you: ${Qt} Looking forward to connecting!`)}`)},children:[e.jsx(Qs,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(j1,{open:h,onOpenChange:m,contact:D?{id:D.id,first_name:D.first_name,last_name:D.last_name,email:K||D.email||""}:K?{id:"",first_name:($==null?void 0:$.split(" ")[0])||"",last_name:($==null?void 0:$.split(" ").slice(1).join(" "))||"",email:K}:void 0,defaultSubject:ge,defaultBody:`Hi ${(D==null?void 0:D.first_name)||($==null?void 0:$.split(" ")[0])||""}, I put together a personalized presentation for you: ${Qt} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(G,{variant:"outline",onClick:()=>g("builder"),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(G,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},NHe=({template:s,onSelect:t})=>e.jsx(Ne,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(De,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx(G,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),XRs=()=>{var j;const{shareToken:s}=Xi(),[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),k.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:b,error:N}=await H.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(N||!b){c(!0),a(!1);return}const{data:S}=await H.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",b.owner_user_id).single();let T;if(S!=null&&S.brokerage_id){const{data:P}=await H.from("brokerages").select("name").eq("id",S.brokerage_id).single();T=(P==null?void 0:P.name)||void 0}let A=null;if(b.contact_id){const{data:P}=await H.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",b.contact_id).single();A=P}r({...b,owner_name:S==null?void 0:S.name,owner_email:S==null?void 0:S.email,owner_phone:S==null?void 0:S.phone,owner_avatar:S==null?void 0:S.avatar_url,owner_title:(S==null?void 0:S.title)||void 0,brokerage_name:T,contact_name:A?[A.first_name,A.last_name].filter(Boolean).join(" "):void 0,contact_email:(A==null?void 0:A.email)||void 0,contact_phone:(A==null?void 0:A.phone)||void 0}),a(!1);try{await H.rpc("log_presentation_view",{p_presentation_id:b.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await H.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(Vs,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Vs,{className:"h-64 w-full"}),e.jsx(Vs,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(b=>b.is_visible!==!1),x=m[i],g=b=>{const N=b.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(N)return`https://www.youtube.com/embed/${N[1]}?rel=0`;if(b.includes("iframe.mediadelivery.net/play/")){const A=b.replace("/play/","/embed/"),P=A.includes("?")?"&":"?";return`${A}${P}responsive=true`}if(b.includes("iframe.mediadelivery.net")){if(b.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const P=b.includes("?")?"&":"?";return`${b}${P}responsive=true`}return""}const S=b.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(S)return`https://www.loom.com/embed/${S[1]}`;const T=b.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:b},v=!!((j=t.cta_url)!=null&&j.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[x!=null&&x.video_url&&g(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:g(x.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):x!=null&&x.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:x.image_url,alt:x.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:x==null?void 0:x.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:x==null?void 0:x.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:x==null?void 0:x.description})]}),(x==null?void 0:x.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:x.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((b,N)=>e.jsx("button",{onClick:()=>l(N),className:Bt("w-full text-left p-4 rounded-xl border transition-all",i===N?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(N+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:b.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:b.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.description})]})]})},N))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),v?e.jsxs(G,{size:"lg",onClick:h,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Yr,{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(Eet,{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 QRs({openHouseId:s,enableSurvey:t,onToggleSurvey:r}){const{data:n,isLoading:a}=aIt(s),i=cIt(),l=dIt(),o=uIt(),c=hIt(),[d,h]=k.useState(""),[m,x]=k.useState("rating"),g=async N=>{r(N),N&&(!n||n.length===0)&&await c.mutateAsync(s)},v=async()=>{if(!d.trim())return;const N=(n==null?void 0:n.reduce((S,T)=>Math.max(S,T.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:m,question_text:d.trim(),sort_order:N+1}),h("")},j=async N=>{await l.mutateAsync({id:N.id,open_house_id:s,is_active:!N.is_active})},b=async N=>{await o.mutateAsync({id:N.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Vj,{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(br,{checked:t,onCheckedChange:g})]}),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(N=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Su,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:N.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:N.question_type.replace("_"," ")})]}),e.jsx(br,{checked:N.is_active,onCheckedChange:()=>j(N),className:"scale-75"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>b(N),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]},N.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(ke,{value:d,onChange:N=>h(N.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:N=>N.key==="Enter"&&v()})]}),e.jsxs(zs,{value:m,onValueChange:x,children:[e.jsx(Os,{className:"w-28 h-9 text-xs",children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"rating",children:"Rating"}),e.jsx(mt,{value:"open_text",children:"Text"})]})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:v,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Ws,{className:"h-3.5 w-3.5"})})]})]})})]})}function JRs({openHouseId:s}){const{user:t}=As(),{data:r=[],isLoading:n}=xIt(s),a=yIt(),[i,l]=k.useState(""),[o,c]=k.useState(!1),d=async()=>{const h=i.trim();if(h){c(!0);try{await a.mutateAsync({open_house_id:s,name:h,sort_order:r.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),n?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(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((h,m)=>e.jsx(eOs,{room:h,index:m,total:r.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},h.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ke,{value:i,onChange:h=>l(h.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())}}),e.jsx(G,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function eOs({room:s,index:t,total:r,userId:n,openHouseId:a}){const i=vIt(),l=bIt(),o=_It(),c=wIt(),d=k.useRef(null),[h,m]=k.useState(!0),[x,g]=k.useState(s.name),[v,j]=k.useState(s.description||""),[b,N]=k.useState(!1),S=k.useMemo(()=>s.media.filter(F=>F.kind==="video"&&F.agent_video_id).map(F=>F.agent_video_id),[s.media]),{data:T={}}=gt({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:F,error:$}=await H.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if($)throw $;const X=F||[],K=X.filter(Y=>Y.status==="processing"&&Y.bunny_video_id);await Promise.all(K.map(async Y=>{try{const{data:ne}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:Y.bunny_video_id,isAgentVideo:!0}});ne&&ne.status===4&&(await H.from("agent_videos").update({status:"ready",playback_url:ne.directPlayUrl,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl,duration_seconds:ne.length||void 0,updated_at:new Date().toISOString()}).eq("id",Y.id),Y.status="ready",Y.thumbnail_url=ne.thumbnailUrl,Y.preview_url=ne.previewUrl)}catch{}}));const Q={};return X.forEach(Y=>{Q[Y.id]={status:Y.status,thumbnail_url:Y.thumbnail_url,preview_url:Y.preview_url}}),Q},refetchInterval:F=>{const $=F.state.data;return $?Object.values($).some(X=>X.status!=="ready"&&X.status!=="failed")?5e3:!1:5e3}}),A=()=>{x.trim()&&x!==s.name&&i.mutate({id:s.id,open_house_id:a,name:x.trim()})},P=()=>{v!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:v.trim()||null})},D=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},B=F=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+F})},z=async F=>{const $=Array.from(F.target.files||[]);if(!(!$.length||!n)){N(!0);try{for(const X of $){const K=X.type.startsWith("video/"),Q=K?500*1024*1024:15*1024*1024;if(X.size>Q){nn({title:`${X.name} is too large`,description:K?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(K){try{const ae=`${s.name} – ${X.name.replace(/\.[^/.]+$/,"")}`,{data:ie,error:me}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:ae,isAgentVideo:!0}});if(me||!ie)throw new Error((me==null?void 0:me.message)||"Could not start upload");const{videoId:oe,libraryId:ge}=ie,{data:be,error:Oe}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:oe,isAgentVideo:!0}});if(Oe||!be)throw new Error((Oe==null?void 0:Oe.message)||"Could not get upload URL");await new Promise((Se,ze)=>{const Te=new XMLHttpRequest;Te.addEventListener("load",()=>{Te.status>=200&&Te.status<300?Se():ze(new Error(`Upload failed (${Te.status})`))}),Te.addEventListener("error",()=>ze(new Error("Upload failed"))),Te.open("PUT",be.uploadUrl),Te.setRequestHeader("AccessKey",be.apiKey),Te.send(X)});const Me=`https://iframe.mediadelivery.net/embed/${ge}/${oe}`,Pe=X.size/(1024*1024),{data:Ee,error:$e}=await H.from("agent_videos").insert({owner_user_id:n,bunny_video_id:oe,playback_url:Me,file_size_mb:Pe,title:ae,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if($e)throw $e;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Me,sort_order:s.media.length,agent_video_id:Ee.id}),nn({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ae){nn({title:"Video upload failed",description:(ae==null?void 0:ae.message)||"Try again",variant:"destructive"})}continue}const Y=X.name.split(".").pop()||"jpg",ne=`${n}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Y}`,{error:de}=await H.storage.from("open-house-tour-media").upload(ne,X,{upsert:!1,contentType:X.type});if(de){nn({title:"Upload failed",description:de.message,variant:"destructive"});continue}const{data:ce}=H.storage.from("open-house-tour-media").getPublicUrl(ne);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ce.publicUrl,sort_order:s.media.length})}}finally{N(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>m(F=>!F),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>B(-1),disabled:t===0,children:e.jsx(xp,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>B(1),disabled:t===r-1,children:e.jsx(so,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:D,children:e.jsx(yr,{className:"h-4 w-4"})})]}),h&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(ke,{value:x,onChange:F=>g(F.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(ur,{value:v,onChange:F=>j(F.target.value),onBlur:P,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map(F=>{const $=F.agent_video_id?T[F.agent_video_id]:void 0,X=$==null?void 0:$.status,K=F.kind==="video"&&X&&X!=="ready"&&X!=="failed",Q=F.kind==="video"&&X==="failed",Y=($==null?void 0:$.thumbnail_url)||($==null?void 0:$.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[F.kind==="video"?e.jsxs(e.Fragment,{children:[Y?e.jsx("img",{src:Y,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(F.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:F.url,className:"w-full h-full object-cover"}),!K&&!Q&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(sn,{className:"h-6 w-6 text-white"})}),K&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(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:F.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:F.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]},F.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:z,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>{var F;return(F=d.current)==null?void 0:F.click()},disabled:b,className:"flex-1",children:b?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(sL,{userId:n,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async F=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:F.playback_url||"",sort_order:s.media.length,agent_video_id:F.id}),nn({title:"Video added to room"})}catch($){nn({title:"Failed to add video",description:$==null?void 0:$.message,variant:"destructive"})}}})]})]})]})}function tOs({open:s,onOpenChange:t,openHouse:r}){const n=Met(),{user:a}=As(),i=k.useRef(null),l=k.useRef(null),o=k.useRef(null),c=r.kind==="virtual",[d,h]=k.useState(r.auto_forward_to_card??!1),[m,x]=k.useState(r.disclosure_pdf_url??""),[g,v]=k.useState(r.enable_survey??!1),[j,b]=k.useState(r.ask_visitor_intent??!0),[N,S]=k.useState(r.photo_url??""),[T,A]=k.useState(!1),[P,D]=k.useState(!1),[B,z]=k.useState(!1),[F,$]=k.useState(r.hero_video_url??""),[X,K]=k.useState(!1),[Q,Y]=k.useState(r.price!=null?String(r.price):""),[ne,de]=k.useState(r.beds!=null?String(r.beds):""),[ce,ae]=k.useState(r.baths!=null?String(r.baths):""),[ie,me]=k.useState(r.sqft!=null?String(r.sqft):""),[oe,ge]=k.useState(r.enable_question??!0),[be,Oe]=k.useState(r.enable_showing??!0),[Me,Pe]=k.useState(r.enable_disclosures??!0),[Ee,$e]=k.useState(r.enable_offer??!0),[Se,ze]=k.useState(r.brand_color_override??""),[Te,ye]=k.useState(r.property_description??""),ct=async Ce=>{var Ft;const nt=(Ft=Ce.target.files)==null?void 0:Ft[0];if(!nt||!a)return;if(nt.size>200*1024*1024){nn({title:"Video must be under 200MB",variant:"destructive"});return}if(!nt.type.startsWith("video/")){nn({title:"Please upload a video file",variant:"destructive"});return}K(!0);const $t=nt.name.split(".").pop()||"mp4",lt=`${a.id}/${r.id}/hero-${Date.now()}.${$t}`,{error:it}=await H.storage.from("open-house-tour-media").upload(lt,nt,{upsert:!0,contentType:nt.type});if(it){nn({title:"Upload failed",description:it.message,variant:"destructive"}),K(!1);return}const{data:Nt}=H.storage.from("open-house-tour-media").getPublicUrl(lt);$(Nt.publicUrl),K(!1),nn({title:"Video uploaded!"})},ve=async Ce=>{var Ft;const nt=(Ft=Ce.target.files)==null?void 0:Ft[0];if(!nt||!a)return;if(nt.size>10*1024*1024){nn({title:"Image must be under 10MB",variant:"destructive"});return}if(!nt.type.startsWith("image/")){nn({title:"Please upload an image file",variant:"destructive"});return}D(!0);const $t=nt.name.split(".").pop()||"jpg",lt=`${a.id}/${r.id}-${Date.now()}.${$t}`,{error:it}=await H.storage.from("open-house-photos").upload(lt,nt,{upsert:!0});if(it){nn({title:"Upload failed",description:it.message,variant:"destructive"}),D(!1);return}const{data:Nt}=H.storage.from("open-house-photos").getPublicUrl(lt);S(Nt.publicUrl),D(!1),nn({title:"Photo updated!"})},rt=()=>{S(""),l.current&&(l.current.value="")},Re=async Ce=>{var Nt;const nt=(Nt=Ce.target.files)==null?void 0:Nt[0];if(!nt||!a)return;if(nt.size>20*1024*1024){nn({title:"File must be under 20MB",variant:"destructive"});return}if(nt.type!=="application/pdf"){nn({title:"Only PDF files are accepted",variant:"destructive"});return}A(!0);const $t=`${a.id}/disclosures/${r.id}-${Date.now()}.pdf`,{error:lt}=await H.storage.from("open-house-photos").upload($t,nt,{upsert:!0});if(lt){nn({title:"Upload failed",description:lt.message,variant:"destructive"}),A(!1);return}const{data:it}=H.storage.from("open-house-photos").getPublicUrl($t);x(it.publicUrl),A(!1),nn({title:"PDF uploaded!"})},Qe=()=>{x(""),i.current&&(i.current.value="")},Ke=async()=>{z(!0);try{const Ce={id:r.id,auto_forward_to_card:d,disclosure_pdf_url:m||null,enable_survey:g,ask_visitor_intent:j,photo_url:N||null};c&&(Ce.hero_video_url=F||null,Ce.price=Q.trim()?Number(Q):null,Ce.beds=ne.trim()?parseInt(ne,10):null,Ce.baths=ce.trim()?Number(ce):null,Ce.sqft=ie.trim()?parseInt(ie,10):null,Ce.enable_question=oe,Ce.enable_showing=be,Ce.enable_disclosures=Me,Ce.enable_offer=Ee,Ce.brand_color_override=Se.trim()||null,Ce.property_description=Te.trim()||null),await n.mutateAsync(Ce),nn({title:"Settings saved!"}),t(!1)}catch{nn({title:"Failed to save",variant:"destructive"})}finally{z(!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(js,{children:[e.jsx(bs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Fr,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[r.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sn,{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:ct,className:"hidden"}),F?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:F,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(G,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ce;return(Ce=o.current)==null?void 0:Ce.click()},disabled:X,children:X?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>$(""),children:e.jsx(_r,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ce;return(Ce=o.current)==null?void 0:Ce.click()},disabled:X,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:X?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(JRs,{openHouseId:r.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ke,{type:"number",value:Q,onChange:Ce=>Y(Ce.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(ke,{type:"number",value:ie,onChange:Ce=>me(Ce.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(ke,{type:"number",value:ne,onChange:Ce=>de(Ce.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(ke,{type:"number",step:"0.5",value:ce,onChange:Ce=>ae(Ce.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Property Description"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Showcase the home — features, finishes, location highlights. Shown on the virtual tour page below the headline."}),e.jsx(ur,{value:Te,onChange:Ce=>ye(Ce.target.value),placeholder:"Stunning 4-bedroom in the heart of River Oaks. Chef's kitchen, oversized primary suite, and a backyard oasis perfect for entertaining…",rows:5,className:"w-full resize-y"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-sm font-medium",children:"Visitor Actions"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Choose what visitors can do during the tour."}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Ask a question"}),e.jsx(br,{checked:oe,onCheckedChange:ge})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(br,{checked:be,onCheckedChange:Oe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(br,{checked:Me,onCheckedChange:Pe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(br,{checked:Ee,onCheckedChange:$e})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Brand Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Used for highlights and CTA buttons on your virtual tour page. Leave blank to use the default."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:Se||"#0f172a",onChange:Ce=>ze(Ce.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(ke,{value:Se,onChange:Ce=>ze(Ce.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Se&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ze(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(Ce=>e.jsx("button",{type:"button",onClick:()=>ze(Ce),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:Ce},"aria-label":Ce},Ce))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Property Photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown on the sign-in screen and printable QR sheet"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:ve,className:"hidden"}),N?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:N,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(G,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ce;return(Ce=l.current)==null?void 0:Ce.click()},disabled:P,children:[P?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),P?"":"Replace"]}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:rt,children:e.jsx(_r,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ce;return(Ce=l.current)==null?void 0:Ce.click()},disabled:P,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:P?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(fl,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Auto-forward to Digital Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After check-in, redirect visitors to your digital business card"})]}),e.jsx(br,{checked:d,onCheckedChange:h})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Seller's Disclosures (PDF)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors can view or download this on the thank you screen after check-in"}),e.jsx("input",{ref:i,type:"file",accept:"application/pdf",onChange:Re,className:"hidden"}),m?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(ln,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Qe,children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var Ce;return(Ce=i.current)==null?void 0:Ce.click()},disabled:T,className:"w-full h-24 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:T?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload PDF (max 20MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(he,{className:"text-sm font-medium",children:'Ask "What brings you here?"'}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show the buying / selling / browsing question after sign-in. Turn off to let visitors check in without picking an option."})]}),e.jsx(br,{checked:j,onCheckedChange:b})]})}),e.jsx(QRs,{openHouseId:r.id,enableSurvey:g,onToggleSurvey:v}),e.jsx(G,{onClick:Ke,disabled:B,className:"w-full",children:B?"Saving...":"Save Settings"})]})]})})}const Agt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function sOs({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:Agt[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 rOs({openHouseId:s}){const{data:t,isLoading:r}=lIt(s),{data:n}=Aet(s),a=k.useMemo(()=>{const m={};return n==null||n.forEach(x=>{m[x.id]=x}),m},[n]);if(r||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(m=>m.question_type==="rating"),c=i.filter(m=>m.question_type!=="rating"),d=[...new Set(l.map(m=>m.visitor_id))],h=d.length;return h===0?e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Vj,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(De,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(Ne,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Vj,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[h," respondent",h!==1?"s":""]})]})}),e.jsx(De,{children:e.jsxs(Rn,{defaultValue:"summary",children:[e.jsxs(Dn,{className:"mb-4",children:[e.jsxs(Xt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(ao,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Xt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Bi,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(as,{value:"summary",className:"space-y-6",children:[o.map(m=>e.jsx(sOs,{question:m,responses:l},m.id)),c.map(m=>{const x=l.filter(g=>g.question_id===m.id&&g.text_value);return x.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:x.map(g=>{const v=a[g.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[v?`${v.first_name} ${v.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:g.text_value})]},g.id)})})]},m.id)})]}),e.jsx(as,{value:"individual",className:"space-y-4",children:d.map(m=>{const x=a[m],g=l.filter(v=>v.visitor_id===m);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[x?`${x.first_name} ${x.last_name||""}`.trim():"Unknown Visitor",(x==null?void 0:x.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:x.email})]}),e.jsx("div",{className:"space-y-1",children:g.map(v=>{const j=i.find(b=>b.id===v.question_id);return j?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:j.question_text}),e.jsx("span",{className:"font-medium",children:v.rating_value!=null?Agt[v.rating_value]||v.rating_value:v.text_value})]},v.id):null})})]},m)})})]})})]})}const nOs={question:{label:"Question",icon:bi,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:rn,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:ln,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:_l,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},kHe={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 aOs({openHouseId:s}){const{data:t=[],isLoading:r}=jIt(s),n=NIt(),[a,i]=k.useState(null),[l,o]=k.useState("all"),c=t.filter(m=>l==="all"?!0:l==="new"?m.status==="new":m.action_type===l),d={all:t.length,new:t.filter(m=>m.status==="new").length,question:t.filter(m=>m.action_type==="question").length,showing:t.filter(m=>m.action_type==="showing").length,disclosure:t.filter(m=>m.action_type==="disclosure").length,offer:t.filter(m=>m.action_type==="offer").length},h=(m,x)=>{n.mutate({id:m,status:x,open_house_id:s})};return r?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(iM,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Ge,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Ge,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([m,x,g])=>e.jsxs("button",{onClick:()=>o(m),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===m?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[x," ",e.jsx("span",{className:"opacity-60",children:g})]},m))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(m=>{const x=nOs[m.action_type],g=x.icon,v=m.payload||{},j=a===m.id,b=m.status==="contacted",N=m.status==="archived";return e.jsxs("li",{className:`transition-colors ${N?"opacity-60":""} ${m.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(j?null:m.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${x.bg}`,children:e.jsx(g,{className:`h-4 w-4 ${x.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:v.visitor_name||"Visitor"}),e.jsx(Ge,{variant:"outline",className:`text-[10px] ${x.color}`,children:x.label}),m.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),b&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),"Contacted"]})]}),v.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',v.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),Ss(new Date(m.created_at),"MMM d, h:mm a")]}),v.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Qs,{className:"h-3 w-3"}),v.email]}),v.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),v.phone]})]})]}),j?e.jsx(so,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(ya,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),j&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[v.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',v.message,'"']}),Object.keys(kHe).some(S=>v[S]!=null&&v[S]!==""&&!(Array.isArray(v[S])&&v[S].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(kHe).map(([S,T])=>{const A=v[S];return A==null||A===""||Array.isArray(A)&&A.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:T}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},S)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[v.email&&e.jsx("a",{href:`mailto:${v.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(G,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Reply"]})}),v.phone&&e.jsx("a",{href:`tel:${String(v.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Call"]})}),!b&&e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>h(m.id,"contacted"),children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),N?e.jsx(G,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"new"),children:"Restore"}):e.jsxs(G,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"archived"),children:[e.jsx(Uj,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},m.id)})})]})}function iOs({open:s,onOpenChange:t,openHouse:r}){const{isGmailConnected:n,gmailEmail:a}=Oh(),i=na(),[l,o]=k.useState([]),[c,d]=k.useState([]),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,P]=k.useState(!1),[D,B]=k.useState(!1),[z,F]=k.useState(!1),$=`https://guestbook.relevelup.com/${r.slug}`;k.useEffect(()=>{s&&(N(`Take a virtual tour of ${r.property_address}`),T(`I wanted to share an immersive virtual tour of ${r.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),j(""),P(n),l.length===0&&X())},[s,r.id,n]);const X=async()=>{if(i){g(!0);try{const{data:ie,error:me}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(me)throw me;o(ie||[])}catch{ue.error("Failed to load contacts")}finally{g(!1)}}},K=ie=>`${ie.first_name} ${ie.last_name||""}`.trim(),Q=ie=>{d(me=>me.find(oe=>oe.id===ie.id)?me.filter(oe=>oe.id!==ie.id):[...me,ie])},Y=()=>{const ie=v.trim();if(!ie)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ie)){ue.error("Invalid email");return}d(oe=>[...oe,{id:`manual-${ie}`,first_name:ie.split("@")[0],last_name:null,email:ie}]),j("")},ne=k.useMemo(()=>c.filter(ie=>!!ie.email).map(ie=>({email:ie.email,name:K(ie)})),[c]),de=ie=>{const me=ie?`Hi ${ie},`:"Hi there,",oe=S.split(/\n\n+/).map(ge=>`

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

`).join("");return`

${me}

${oe}

▶ Start Virtual Tour

Or copy this link: ${$}

`},ce=async()=>{var ie;if(ne.length===0){ue.error("Add at least one recipient");return}B(!0);try{if(A&&n){let me=0;for(const oe of ne){const{data:ge,error:be}=await H.functions.invoke("gmail-send",{body:{to:oe.email,subject:b,body:de((ie=oe.name)==null?void 0:ie.split(" ")[0])}});!be&&(ge!=null&&ge.success)?me+=1:console.warn("gmail-send error",be,ge)}if(me===0)throw new Error("Gmail send failed");ue.success(`Sent to ${me} of ${ne.length} via Gmail`)}else{const{data:me,error:oe}=await H.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:r.id,recipients:ne,subject:b,personalMessage:S}});if(oe)throw oe;if(!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Send failed");ue.success(`Sent to ${me.sent} of ${me.total} recipient${me.total===1?"":"s"}`)}t(!1)}catch(me){ue.error((me==null?void 0:me.message)||"Failed to send")}finally{B(!1)}},ae=async()=>{await navigator.clipboard.writeText($),F(!0),setTimeout(()=>F(!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(js,{className:"min-w-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Fr,{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(xo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:$}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:ae,className:"shrink-0 h-7 gap-1",children:[z?e.jsx(Hn,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ra,{className:"h-3.5 w-3.5"}),z?"Copied":"Copy"]})]}),n&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>P(!0),className:"gap-1.5",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(G,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>P(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),A&&a&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Sending as ",e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{className:"flex items-center gap-1.5",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(Ao,{open:h,onOpenChange:m,modal:!0,children:[e.jsx(Mo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:c.length?`${c.length} selected`:"Select contacts..."}),e.jsx(xx,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(wo,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(Ix,{children:[e.jsx(Px,{placeholder:"Search contacts..."}),e.jsxs(Lx,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(Dx,{children:x?"Loading...":"No contacts found."}),e.jsx(Rx,{children:l.map(ie=>{const me=!!c.find(be=>be.id===ie.id),oe=K(ie).slice(0,80),ge=(ie.email||"").slice(0,80);return e.jsxs(vf,{value:`${oe} ${ge}`,onSelect:()=>Q(ie),className:"py-2",children:[e.jsx(Hn,{className:Bt("mr-2 h-4 w-4 shrink-0",me?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:oe||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ge})]})]},ie.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ie=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:K(ie)}),e.jsx("button",{onClick:()=>Q(ie),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(_r,{className:"h-3 w-3"})})]},ie.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ke,{value:v,onChange:ie=>j(ie.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),Y())}}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:Y,children:"Add"})]})]}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(ke,{id:"vt-subject",value:b,onChange:ie=>N(ie.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(ur,{id:"vt-message",value:S,onChange:ie=>T(ie.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsxs(G,{onClick:ce,disabled:D||ne.length===0||!b.trim(),className:"gap-2",children:[D?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),D?"Sending...":`Send${ne.length?` to ${ne.length}`:""}`]})]})]})]})})}const WSe="guestbook.relevelup.com";function oOs(){const{data:s,isLoading:t}=tIt(),r=sIt(),n=Met(),a=rIt(),[i,l]=k.useState(!1),[o,c]=k.useState(null),{user:d}=As(),h=na(),[m,x]=k.useState(null),[g,v]=k.useState(null),[j,b]=k.useState(!1),N=k.useRef(null),[S,T]=k.useState({property_address:"",city:"",state:"",zip:"",event_date:Ss(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A=z=>{var $;const F=($=z.target.files)==null?void 0:$[0];if(F){if(F.size>5*1024*1024){nn({title:"Photo must be under 5MB",variant:"destructive"});return}x(F),v(URL.createObjectURL(F))}},P=()=>{x(null),v(null),N.current&&(N.current.value="")},D=async()=>{if(!S.property_address){nn({title:S.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let z;if(m&&d){b(!0);const $=m.name.split(".").pop(),X=`${h}/${Date.now()}.${$}`,{error:K}=await H.storage.from("open-house-photos").upload(X,m,{upsert:!0});if(K){nn({title:"Photo upload failed",description:K.message,variant:"destructive"}),b(!1);return}const{data:Q}=H.storage.from("open-house-photos").getPublicUrl(X);z=Q.publicUrl,b(!1)}const F=S.kind==="virtual"?{...S,start_time:void 0,end_time:void 0,photo_url:z}:{...S,photo_url:z};await r.mutateAsync(F),l(!1),T({property_address:"",city:"",state:"",zip:"",event_date:Ss(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),P()},B=z=>{navigator.clipboard.writeText(`https://${WSe}/${z}`),nn({title:"Link copied!"})};return e.jsxs(_s,{title:"Guest Book",children:[e.jsx(il,{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(Ni,{asChild:!0,children:e.jsxs(G,{children:[e.jsx(Ws,{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(js,{children:[e.jsx(bs,{children:"Create Open House"}),e.jsx(Fr,{children:"Set up a new open house sign-in page"})]}),e.jsxs("div",{className:"space-y-4 pt-2 overflow-y-auto flex-1 pr-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Open House Type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${S.kind==="physical"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Physical Open House"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"In-person sign-in at the property"})]}),e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${S.kind==="virtual"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("div",{className:"text-sm font-semibold flex items-center gap-1.5",children:["Virtual Open House ",e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-primary/10 text-primary uppercase tracking-wide",children:"New"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Always-on branded tour via link or QR"})]})]})]}),S.kind==="physical"&&e.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:e.jsxs("div",{className:"flex gap-1 flex-1",children:[e.jsx("button",{type:"button",onClick:()=>T(z=>({...z,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${S.event_type==="property"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Single Property"}),e.jsx("button",{type:"button",onClick:()=>T(z=>({...z,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${S.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),S.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tour Format"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${S.tour_mode==="rooms"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Room-by-room"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Photos & videos per room"})]}),e.jsxs("button",{type:"button",onClick:()=>T(z=>({...z,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${S.tour_mode==="single_video"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Single video"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"One walkthrough video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can add the video or room media in settings after creating."})]}),e.jsxs("div",{children:[e.jsx(he,{children:S.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(ke,{value:S.property_address,onChange:z=>T(F=>({...F,property_address:z.target.value})),placeholder:S.event_type==="community"?"Spring Festival at Riverside Estates":"123 Main Street"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"City"}),e.jsx(ke,{value:S.city,onChange:z=>T(F=>({...F,city:z.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"State"}),e.jsx(ke,{value:S.state,onChange:z=>T(F=>({...F,state:z.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"ZIP"}),e.jsx(ke,{value:S.zip,onChange:z=>T(F=>({...F,zip:z.target.value})),placeholder:"78701"})]})]}),S.kind==="virtual"?e.jsxs("div",{className:"rounded-lg border border-dashed border-muted-foreground/30 bg-muted/20 p-3 text-xs text-muted-foreground",children:["🕒 Virtual open houses are ",e.jsx("span",{className:"font-medium text-foreground",children:"always on"})," — no date or time needed. Visitors can tour any time via your link or QR code."]}):e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Date"}),e.jsx(ke,{type:"date",value:S.event_date,onChange:z=>T(F=>({...F,event_date:z.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Start Time"}),e.jsx(ke,{type:"time",value:S.start_time,onChange:z=>T(F=>({...F,start_time:z.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"End Time"}),e.jsx(ke,{type:"time",value:S.end_time,onChange:z=>T(F=>({...F,end_time:z.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Welcome Message"}),e.jsx(ur,{value:S.agent_greeting,onChange:z=>T(F=>({...F,agent_greeting:z.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(he,{children:S.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:N,type:"file",accept:"image/*",onChange:A,className:"hidden"}),g?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:g,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:P,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 z;return(z=N.current)==null?void 0:z.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($v,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",S.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(G,{onClick:D,disabled:r.isPending||j,className:"w-full",children:j?"Uploading photo...":r.isPending?"Creating...":S.kind==="virtual"?"Create Virtual Open House":S.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(z=>e.jsx(Ne,{className:"animate-pulse",children:e.jsxs(Ot,{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"})]})},z))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(z=>e.jsx(lOs,{openHouse:z,isExpanded:o===z.id,onToggle:()=>c(o===z.id?null:z.id),onCopyLink:()=>B(z.slug||""),onToggleActive:()=>n.mutate({id:z.id,is_active:!z.is_active}),onDelete:()=>a.mutate(z.id)},z.id))}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(De,{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(Hv,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs(G,{onClick:()=>l(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function lOs({openHouse:s,isExpanded:t,onToggle:r,onCopyLink:n,onToggleActive:a,onDelete:i}){const{data:l}=Aet(t?s.id:void 0),{data:o}=gt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:B,error:z}=await H.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(z)throw z;const F=B.brokerages;return{...B,brokerage_name:(F==null?void 0:F.name)||null}},enabled:!!s.agent_id}),[c,d]=k.useState(!1),[h,m]=k.useState(!1),[x,g]=k.useState(!1),[v,j]=k.useState(!1),b=k.useRef(null),N=`https://${WSe}/${s.slug}`,S=B=>{if(!B)return"";const[z,F]=B.split(":"),$=parseInt(z),X=$>=12?"PM":"AM";return`${$>12?$-12:$||12}:${F} ${X}`},T=()=>{if(!(l!=null&&l.length))return;const B=["First Name","Last Name","Email","Phone","Intent","Wants Market Updates","Message","Signed In"],z=l.map(Q=>[Q.first_name,Q.last_name||"",Q.email||"",Q.phone||"",Q.visitor_intent||"",Q.wants_market_updates?"Yes":"No",(Q.message||"").replace(/"/g,'""'),Ss(new Date(Q.created_at),"MM/dd/yyyy h:mm a")]),F=[B,...z].map(Q=>Q.map(Y=>`"${Y}"`).join(",")).join(` `),$=new Blob([F],{type:"text/csv"}),X=URL.createObjectURL($),K=document.createElement("a");K.href=X,K.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,K.click(),URL.revokeObjectURL(X)},A=k.useCallback(()=>{if(!b.current)return;const B=b.current.querySelector("svg");if(!B)return;const z=new XMLSerializer().serializeToString(B),F=document.createElement("canvas");F.width=1024,F.height=1024;const $=F.getContext("2d"),X=new Image;X.onload=()=>{$==null||$.drawImage(X,0,0,1024,1024);const K=document.createElement("a");K.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,K.href=F.toDataURL("image/png"),K.click()},X.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(z)))},[s.property_address]),P=k.useCallback(()=>{var ve;if(!b.current)return;const B=b.current.querySelector("svg");if(!B)return;const z=new XMLSerializer().serializeToString(B),F="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(z))),$=Ss(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),X=s.start_time?`${S(s.start_time)}${s.end_time?" – "+S(s.end_time):""}`:"",K=[s.city,s.state].filter(Boolean).join(", "),Q=s.agent_greeting||"Welcome! Please sign in below.",Y=!!s.photo_url,ne=!!o,de=Y||ne,ce=Y&&ne,ae=ce?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ie=ce?"28px":"34px",me=ce?"0.2in 0.75in":de?"0.3in 0.75in":"0.4in 0.75in",oe=de?"0.15in":"0.3in",ge=de?"0.15in":"0.3in",be=ce?"14px 36px":"22px 44px",Oe=ce?"20px":"24px",Me=de?"0.2in":"0.35in",Pe=ce?"1.8in":"2.4in",Ee=de?"0.15in":"0.3in",$e=ce?"140px":de?"160px":"200px",Se=ce?"16px":"24px",ze=ce?"10px 20px":"16px 28px",Te=ce?"44px":"56px",ye="0.15in",ct=window.open("","_blank");ct&&(ct.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${K?`
${K}${s.zip?" "+s.zip:""}
`:""}
Date
${$}
${X?`
Time
${X}
`:""}
${Q}
${o?`
${o.avatar_url?`${o.name}`:`
${((ve=o.name)==null?void 0:ve.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
`),ct.document.close(),setTimeout(()=>{ct.focus(),ct.print()},500))},[s,N,o]),D=async()=>{j(!0);try{const{error:B}=await H.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(B)throw B;nn({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(B){nn({title:"Failed to send",description:B.message,variant:"destructive"})}finally{j(!1)}};return e.jsxs(Ne,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Ot,{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(zt,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(Ge,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Ge,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 border-purple-200 dark:border-purple-800",children:[e.jsx(jn,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Ge,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",children:[e.jsx(ja,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Ge,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border-blue-200 dark:border-blue-800",children:[e.jsx(Bi,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Ge,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(xp,{className:"h-4 w-4"}):e.jsx(so,{className:"h-4 w-4"})})]}),e.jsxs(Nr,{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs",children:[s.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ja,{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(cn,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rn,{className:"h-3 w-3"}),Ss(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),S(s.start_time),s.end_time?` – ${S(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(fr,{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(Hv,{className:"h-3 w-3"}),s.qr_scan_count," scan",s.qr_scan_count===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,title:"Go Live",className:"h-9 w-full justify-center gap-1.5 text-xs text-emerald-600 border-emerald-200 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-900/20 sm:h-8 sm:w-auto",children:[e.jsx(r_,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:n,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(Ra,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>g(!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(Pc,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),title:"Preview tour as visitor",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>d(!0),title:"QR Code",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(Hv,{className:"h-3.5 w-3.5"}),"QR"]}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>m(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(lo,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>window.open(N,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:a,title:s.is_active?"Deactivate":"Activate",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:s.is_active?e.jsx(am,{className:"h-3.5 w-3.5"}):e.jsx(jn,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:i,title:"Delete",className:"h-9 w-full justify-center text-xs text-destructive border-destructive/30 hover:bg-destructive/10 sm:h-8 sm:w-auto",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(De,{className:"pt-0",children:[e.jsx(po,{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://",WSe,"/",s.slug]})]}),l!=null&&l.length?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[l.length," Visitor",l.length!==1?"s":""]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:T,className:"h-7 text-xs gap-1",children:[e.jsx(Xa,{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(B=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[B.first_name,B.last_name?` ${B.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[B.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:B.email}),B.phone&&e.jsx("div",{className:"text-xs",children:B.phone})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:B.visitor_intent?e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:B.visitor_intent}):B.partial_signin?e.jsx(Ge,{variant:"outline",className:"text-xs text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-700",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2 text-xs text-muted-foreground",children:Ss(new Date(B.created_at),"h:mm a")})]},B.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(aOs,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(rOs,{openHouseId:s.id})})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"sm:max-w-sm",children:[e.jsxs(js,{children:[e.jsx(bs,{children:"QR Code"}),e.jsx(Fr,{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(Bz,{value:N,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:N}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:P,children:[e.jsx(NO,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(G,{variant:"default",className:"w-full",onClick:D,disabled:v,children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),v?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(tOs,{open:h,onOpenChange:m,openHouse:s}),s.kind==="virtual"&&e.jsx(iOs,{open:x,onOpenChange:g,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function cOs(){const{slug:s}=Xi();return s?e.jsx(jrt,{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 Mgt({photoUrl:s,videoUrl:t,onPhotoChange:r,onVideoChange:n,contactId:a}){const{user:i}=As(),l=O_(),o=k.useRef(null),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[g,v]=k.useState(0),j=async N=>{if(i){h(!0);try{const S=N.name.split(".").pop()||"jpg",T=`${i.id}/card-${Date.now()}.${S}`,{error:A}=await H.storage.from("listing-photos").upload(T,N);if(A)throw A;const{data:{publicUrl:P}}=H.storage.from("listing-photos").getPublicUrl(T);r(P),ue.success("Photo uploaded")}catch(S){ue.error(S.message||"Failed to upload photo")}finally{h(!1)}}},b=async N=>{if(i){if(N.size>500*1024*1024){ue.error("Video must be under 500MB");return}x(!0),v(0);try{const{videoId:S,libraryId:T}=await sT(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:P}=await rT(S);await new Promise((z,F)=>{const $=new XMLHttpRequest;$.upload.addEventListener("progress",X=>{X.lengthComputable&&v(Math.round(X.loaded/X.total*100))}),$.addEventListener("load",()=>{$.status>=200&&$.status<300?z():F(new Error("Upload failed"))}),$.addEventListener("error",()=>F(new Error("Upload failed"))),$.open("PUT",A),$.setRequestHeader("AccessKey",P),$.send(N)});const D=`https://iframe.mediadelivery.net/embed/${T}/${S}`;n(D);const B=parseFloat((N.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:S,playback_url:`https://iframe.mediadelivery.net/play/${T}/${S}`,file_size_mb:B,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ue.success("Video uploaded & added to your library")}catch(S){ue.error(S.message||"Failed to upload video")}finally{x(!1),v(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Media (optional)"}),e.jsxs(Rn,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Dn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Xt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(as,{value:"photo",className:"mt-3",children:[s?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:s,alt:"Card photo",className:"w-full h-40 object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var N;return(N=o.current)==null?void 0:N.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(ls,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(pp,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:N=>{var T;const S=(T=N.target.files)==null?void 0:T[0];S&&j(S),N.target.value=""}})]}),e.jsxs(as,{value:"video",className:"mt-3",children:[t?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("iframe",{src:`${t}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var N;return(N=c.current)==null?void 0:N.click()},disabled:m,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:m?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(ls,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",g,"%"]}),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:`${g}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(oa,{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(dMe,{contactId:a,onVideoReady:N=>n(N)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:N=>{var T;const S=(T=N.target.files)==null?void 0:T[0];S&&b(S),N.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const dOs=[{type:"home_anniversary",label:"Home Anniversary",emoji:"🏡",description:"Celebrate their homeownership milestone",gradient:"from-blue-500/20 to-slate-500/20 border-blue-200 dark:border-blue-800"},{type:"birthday",label:"Birthday",emoji:"🎂",description:"Wish them a happy birthday",gradient:"from-pink-500/20 to-purple-500/20 border-pink-200 dark:border-pink-800"},{type:"just_sold",label:"Just Sold",emoji:"🎉",description:"Announce a successful closing",gradient:"from-emerald-500/20 to-teal-500/20 border-emerald-200 dark:border-emerald-800"},{type:"just_listed",label:"Just Listed",emoji:"🏠",description:"Share a new listing announcement",gradient:"from-amber-500/20 to-orange-500/20 border-amber-200 dark:border-amber-800"},{type:"thank_you",label:"Thank You",emoji:"💐",description:"Show your appreciation",gradient:"from-rose-500/20 to-pink-500/20 border-rose-200 dark:border-rose-800"},{type:"congratulations",label:"Congratulations",emoji:"🏆",description:"Celebrate their achievements",gradient:"from-yellow-500/20 to-amber-500/20 border-yellow-200 dark:border-yellow-800"},{type:"holiday",label:"Holiday",emoji:"🎄",description:"Send seasonal greetings",gradient:"from-red-500/20 to-green-500/20 border-red-200 dark:border-red-800"},{type:"thinking_of_you",label:"Thinking of You",emoji:"💭",description:"Stay top of mind with a personal touch",gradient:"from-violet-500/20 to-indigo-500/20 border-violet-200 dark:border-violet-800"}];function uOs({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:dOs.map((t,r)=>e.jsxs(Cr.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 gL={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function SHe({initialOpen:s,initialCardType:t,initialContactId:r,initialRecipientName:n,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=As(),c=es(),[d,h]=k.useState(!1),[m,x]=k.useState("type"),[g,v]=k.useState(""),[j,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState("home_anniversary"),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState(""),[X,K]=k.useState(""),[Q,Y]=k.useState("elegant"),[ne,de]=k.useState(null),[ce,ae]=k.useState(null),ie=k.useState(!1);!ie[0]&&s&&t&&(ie[1](!0),h(!0),A(t),r&&b(r),n&&D(n),a&&z(a),i&&$(i),x(n?"details":"contact"));const{data:me}=gt({queryKey:["contacts-for-card",o==null?void 0:o.id,g],queryFn:async()=>{let ze=H.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);g&&(ze=ze.or(`first_name.ilike.%${g}%,last_name.ilike.%${g}%`));const{data:Te,error:ye}=await ze;if(ye)throw ye;return Te},enabled:!!(o!=null&&o.id)&&d}),{data:oe}=gt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:ze,error:Te}=await H.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(Te)throw Te;return ze},enabled:!!(o!=null&&o.id)}),ge=ze=>{b(ze.id),D(`${ze.first_name}${ze.last_name?" "+ze.last_name:""}`),z([ze.address,ze.city,ze.state].filter(Boolean).join(", ")),$(ze.home_anniversary||""),x("details")},be=ze=>{A(ze),x("contact")},Oe=async()=>{var ze;if(!(!o||!oe)){S(!0);try{const Te={owner_user_id:o.id,contact_id:j,card_type:T,template:Q,recipient_name:P,property_address:B||null,home_anniversary_date:F||null,custom_message:X||null,property_photo_url:ne||null,video_url:ce||null,agent_name:oe.name||"Agent",agent_photo_url:oe.avatar_url,agent_phone:oe.phone,agent_email:oe.email,agent_brokerage:((ze=oe.brokerage)==null?void 0:ze.name)||null},{error:ye}=await H.from("sendable_cards").insert(Te);if(ye)throw ye;ue.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Me()}catch(Te){ue.error(Te.message||"Failed to create card")}finally{S(!1)}}},Me=()=>{h(!1),x("type"),A("home_anniversary"),v(""),b(null),D(""),z(""),$(""),K(""),Y("elegant"),de(null),ae(null)},Pe={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Ee=gL[T],$e=T==="home_anniversary",Se=["home_anniversary","just_listed","just_sold"].includes(T);return e.jsxs(vs,{open:d,onOpenChange:ze=>{ze?h(!0):(Me(),l==null||l(!1))},children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:m==="type"?"What type of card?":m==="contact"?`${Pe[T]} — Choose a Contact`:`${Pe[T]} — Customize`})}),m==="type"&&e.jsx(uOs,{onSelect:be}),m==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>x("type"),children:[e.jsx(wa,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search contacts...",value:g,onChange:ze=>v(ze.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[me==null?void 0:me.map(ze=>e.jsxs("button",{onClick:()=>ge(ze),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(Bi,{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:[ze.first_name," ",ze.last_name]}),ze.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),ze.address]})]}),ze.home_anniversary&&T==="home_anniversary"&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Anniversary set"})]},ze.id)),(me==null?void 0:me.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No contacts found"})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{x("details")},children:"Skip — enter details manually"})})]}),m==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>x("contact"),children:[e.jsx(wa,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipient Name"}),e.jsx(ke,{value:P,onChange:ze=>D(ze.target.value),placeholder:"John & Jane Smith"})]}),Se&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Address"}),e.jsx(ke,{value:B,onChange:ze=>z(ze.target.value),placeholder:"123 Main St, Austin, TX"})]}),$e&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Home Anniversary Date"}),e.jsx(ke,{type:"date",value:F,onChange:ze=>$(ze.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Message (optional)"}),e.jsx(ur,{value:X,onChange:ze=>K(ze.target.value),placeholder:Ee.defaultMessage,rows:3})]}),e.jsx(Mgt,{photoUrl:ne,videoUrl:ce,onPhotoChange:de,onVideoChange:ae,contactId:j}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key:ze,label:Te,gradient:ye})=>e.jsxs("button",{onClick:()=>Y(ze),className:`p-2 rounded-lg border-2 transition-all text-center ${Q===ze?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${ye}`}),e.jsx("span",{className:"text-[10px] font-medium",children:Te})]},ze))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>x("contact"),className:"flex-1",children:"Back"}),e.jsx(G,{onClick:Oe,disabled:!P||N,className:"flex-1 gap-2",children:N?"Creating...":"Create Card"})]})]})]})]})}const hOs={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};function mOs({card:s}){const{user:t}=As(),{isGmailConnected:r}=Oh(),n=es(),[a,i]=k.useState(!1),[l,o]=k.useState("");k.useEffect(()=>{a&&s.contact_id&&!l&&H.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:j})=>{j!=null&&j.email&&o(j.email)})},[a,s.contact_id]);const c={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[d,h]=k.useState(c[s.card_type]||`A Special Card for ${s.recipient_name}!`),[m,x]=k.useState(""),g=`https://cardstudio.relevelup.com/c/${s.share_token}`,v=Lt({mutationFn:async()=>{var T;if(!l)throw new Error("Recipient email is required");const j=`
${m?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:b}=await H.auth.getSession(),N=(T=b==null?void 0:b.session)==null?void 0:T.access_token,S=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${N}`},body:JSON.stringify({to:l,subject:d,body:j,contactId:s.contact_id||void 0})});if(!S.ok){const A=await S.json();throw new Error(A.error||"Failed to send")}return S.json()},onSuccess:async()=>{await H.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),n.invalidateQueries({queryKey:["sendable-cards"]}),ue.success(`Card sent to ${l}!`),i(!1)},onError:j=>{ue.error(j.message||"Failed to send email")}});return r?e.jsxs(vs,{open:a,onOpenChange:i,children:[e.jsx(Ni,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Zr,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsx(bs,{children:"Send Card via Gmail"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"To"}),e.jsx(ke,{type:"email",value:l,onChange:j=>o(j.target.value),placeholder:"recipient@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Subject"}),e.jsx(ke,{value:d,onChange:j=>h(j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Note (optional)"}),e.jsx(ur,{value:m,onChange:j=>x(j.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:["The email will include a beautiful button linking to your card at:",e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:g})]}),e.jsx(G,{onClick:()=>v.mutate(),disabled:!l||v.isPending,className:"w-full gap-2",children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs opacity-50 cursor-not-allowed",title:"Connect Gmail in Settings to send cards via email",disabled:!0,children:e.jsx(Zr,{className:"h-3 w-3"})})}function fOs({card:s}){const t=es(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(s.recipient_name),[c,d]=k.useState(s.property_address||""),[h,m]=k.useState(s.home_anniversary_date||""),[x,g]=k.useState(s.custom_message||""),[v,j]=k.useState(s.template),[b,N]=k.useState(s.property_photo_url),[S,T]=k.useState(s.video_url||null),A=D=>{D&&(o(s.recipient_name),d(s.property_address||""),m(s.home_anniversary_date||""),g(s.custom_message||""),j(s.template),N(s.property_photo_url),T(s.video_url||null)),n(D)},P=async()=>{if(!l.trim()){ue.error("Recipient name is required");return}i(!0);try{const{error:D}=await H.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:h||null,custom_message:x.trim()||null,template:v,property_photo_url:b||null,video_url:S||null}).eq("id",s.id);if(D)throw D;t.invalidateQueries({queryKey:["sendable-cards"]}),ue.success("Card updated"),n(!1)}catch(D){ue.error(D.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(vs,{open:r,onOpenChange:A,children:[e.jsx(Ni,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ta,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{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(he,{children:"Recipient Name"}),e.jsx(ke,{value:l,onChange:D=>o(D.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Address"}),e.jsx(ke,{value:c,onChange:D=>d(D.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Home Anniversary Date"}),e.jsx(ke,{type:"date",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Message (optional)"}),e.jsx(ur,{value:x,onChange:D=>g(D.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(Mgt,{photoUrl:b,videoUrl:S,onPhotoChange:N,onVideoChange:T,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(D=>e.jsxs("button",{onClick:()=>j(D),className:`p-3 rounded-lg border-2 transition-all text-center ${v===D?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${D==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":D==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:D})]},D))})]}),e.jsx(G,{onClick:P,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 pOs(){const{user:s}=As(),t=es(),[r,n]=k.useState(""),[a,i]=Lc(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),h=a.get("date"),m=!!l,{data:x,isLoading:g}=gt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:T,error:A}=await H.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return T},enabled:!!(s!=null&&s.id)}),v=Lt({mutationFn:async T=>{const{error:A}=await H.from("sendable_cards").delete().eq("id",T);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ue.success("Card deleted")}}),j=T=>{const A=`https://cardstudio.relevelup.com/c/${T}`;navigator.clipboard.writeText(A),ue.success("Share link copied!")},b=x==null?void 0:x.filter(T=>{var A;return!r||T.recipient_name.toLowerCase().includes(r.toLowerCase())||((A=T.property_address)==null?void 0:A.toLowerCase().includes(r.toLowerCase()))}),N={elegant:"Elegant",bold:"Bold",warm:"Warm"},S={home_anniversary:"Home Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(_s,{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(SHe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search cards...",value:r,onChange:T=>n(T.target.value),className:"pl-9"})]}),g?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(T=>e.jsx(Ne,{className:"animate-pulse",children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},T))}):b!=null&&b.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(T=>e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${T.template==="elegant"?"bg-gradient-to-br from-slate-50 via-slate-100 to-slate-200 dark:from-slate-900 dark:via-slate-800 dark:to-slate-700":T.template==="bold"?"bg-gradient-to-br from-violet-600 via-fuchsia-500 to-pink-500":"bg-gradient-to-br from-amber-100 via-orange-200 to-rose-200 dark:from-amber-900 dark:via-orange-800 dark:to-rose-800"}`,children:[T.template==="elegant"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-0 left-0 w-full h-full opacity-10",children:[e.jsx("div",{className:"absolute top-3 left-3 w-16 h-16 border-t-2 border-l-2 border-primary/40 rounded-tl-lg"}),e.jsx("div",{className:"absolute bottom-3 right-3 w-16 h-16 border-b-2 border-r-2 border-primary/40 rounded-br-lg"})]}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-primary/10"})]}),T.template==="bold"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-8 -right-8 w-32 h-32 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute -bottom-6 -left-6 w-24 h-24 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.15)_0%,transparent_70%)]"})]}),T.template==="warm"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-4 -left-4 w-28 h-28 rounded-full bg-orange-400/15 blur-md"}),e.jsx("div",{className:"absolute -bottom-6 -right-6 w-32 h-32 rounded-full bg-rose-400/15 blur-md"})]}),e.jsxs("div",{className:"text-center px-4 relative z-10",children:[e.jsx("div",{className:"text-3xl mb-1.5 opacity-80",children:T.card_type==="home_anniversary"?"🏡":T.card_type==="birthday"?"🎂":T.card_type==="just_sold"?"🎉":T.card_type==="just_listed"?"🏠":T.card_type==="thank_you"?"💐":T.card_type==="congratulations"?"🏆":T.card_type==="holiday"?"🎄":T.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${T.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:S[T.card_type]||T.card_type}),e.jsx("p",{className:`font-semibold text-base ${T.template==="bold"?"text-white":"text-foreground"}`,children:T.recipient_name}),T.property_address&&e.jsx("p",{className:`text-xs mt-1 ${T.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:T.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Ge,{variant:T.template==="bold"?"outline":"secondary",className:`text-[10px] ${T.template==="bold"?"border-white/30 text-white/80":""}`,children:N[T.template]||T.template})})]}),e.jsxs(De,{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(jn,{className:"h-3 w-3"}),T.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:al(new Date(T.created_at),{addSuffix:!0})})]}),T.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Ss(new Date(T.sent_at),"MMM d, yyyy")," via ",T.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>j(T.share_token),children:[e.jsx(Ra,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(fOs,{card:T}),e.jsx(mOs,{card:T}),e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${T.share_token}`,"_blank"),children:e.jsx(Yr,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>v.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]})]},T.id))}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(De,{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(Qs,{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(SHe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]})})]})})}const iq=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Cn,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:nm,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:Xu,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:zv,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:oO,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:_o,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:ku,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:au,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:om,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:Cu,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:cn,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:a_,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:pd,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:rO,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:iu,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:sn,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Nh,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:R3,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:nm,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:wO,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:ja,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:Qs,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:mO,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:fr,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:a_,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:KR,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ja,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function xOs(){var yo,ra,ki,Qi,Po,ci,za,jo,Pi,Lo,rc;const{user:s}=As(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(""),[d,h]=k.useState([]),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[P,D]=k.useState(""),[B,z]=k.useState(""),[F,$]=k.useState(null),[X,K]=k.useState(""),[Q,Y]=k.useState(""),[ne,de]=k.useState(""),[ce,ae]=k.useState(""),[ie,me]=k.useState(""),[oe,ge]=k.useState(""),[be,Oe]=k.useState(""),[Me,Pe]=k.useState(""),[Ee,$e]=k.useState(""),[Se,ze]=k.useState(""),[Te,ye]=k.useState(""),[ct,ve]=k.useState(""),[rt,Re]=k.useState(""),[Qe,Ke]=k.useState(""),[Ce,nt]=k.useState(""),[$t,lt]=k.useState(""),[it,Nt]=k.useState(""),[Ft,at]=k.useState(""),[Ie,et]=k.useState(""),[Dt,Jt]=k.useState(""),[cs,Ht]=k.useState(""),[dt,Qt]=k.useState(""),[yt,ss]=k.useState(""),[Is,fs]=k.useState(""),[ar,Er]=k.useState(""),[Tr,Lr]=k.useState("listing"),[$r,kr]=k.useState("mls"),[Sr,hn]=k.useState({}),[zn,Xs]=k.useState({}),[Ur,xn]=k.useState(!1),[us,pr]=k.useState(!1),Hr=dr=>{Lr(dr);const Jn=iq.find(uo=>uo.category===dr);Jn&&kr(Jn.id)},{data:aa}=gt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Ur,queryFn:async()=>{const{data:dr,error:Jn}=await H.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(Jn)throw Jn;return dr||[]}}),Na=()=>{const dr=o.trim();dr&&(l(Jn=>[...Jn,dr]),c(""))},Je=dr=>l(Jn=>Jn.filter((uo,ll)=>ll!==dr)),Fe=dr=>{var Jn,uo,ll,Va;$(dr.id),r(dr.property_address||""),D(dr.city||""),z(dr.state||""),S(((Jn=dr.price)==null?void 0:Jn.toString())||""),x(((uo=dr.bedrooms)==null?void 0:uo.toString())||""),v(((ll=dr.bathrooms)==null?void 0:ll.toString())||""),b(((Va=dr.square_footage)==null?void 0:Va.toString())||""),A(dr.property_type||""),a(dr.description||""),xn(!1),ue.success("Listing imported")},We=async dr=>{if(!(!dr.target.files||!(s!=null&&s.id))){pr(!0);try{const Jn=[];for(const uo of Array.from(dr.target.files).slice(0,10)){const ll=`${s.id}/${Date.now()}-${uo.name.replace(/[^\w.-]/g,"_")}`,{error:Va}=await H.storage.from("listing-photos").upload(ll,uo,{upsert:!1});if(Va){console.error(Va);continue}const{data:Dl}=H.storage.from("listing-photos").getPublicUrl(ll);Jn.push(Dl.publicUrl)}h(uo=>[...uo,...Jn]),Jn.length&&ue.success(`${Jn.length} photo(s) uploaded`)}catch(Jn){ue.error(Jn.message||"Photo upload failed")}finally{pr(!1)}}},He=iq.find(dr=>dr.id===$r),bt=async dr=>{var uo,ll,Va;const Jn=iq.find(Dl=>Dl.id===dr);if(!t.trim()&&!n.trim()&&i.length===0){ue.error("Add a property address, MLS remarks, or features first");return}if((uo=Jn.extras)!=null&&uo.includes("openHouse")&&(!X||!Q||!ne)){ue.error("Add the open house date, start and end time");return}if((ll=Jn.extras)!=null&&ll.includes("priceImprovement")&&(!ce||!ie)){ue.error("Add previous and new price");return}if((Va=Jn.extras)!=null&&Va.includes("sold")&&!oe){ue.error("Add the sold price");return}kr(dr),Xs(Dl=>({...Dl,[dr]:!0}));try{const{data:Dl,error:Wm}=await H.functions.invoke("listing-studio-generate",{body:{copyType:dr,propertyAddress:t,mlsRemarks:n,features:i,photoUrls:d,listingId:F,bedrooms:m?Number(m):null,bathrooms:g?Number(g):null,squareFootage:j?Number(j):null,price:N?Number(N):null,propertyType:T||null,city:P||null,state:B||null,openHouseDate:X||null,openHouseStart:Q||null,openHouseEnd:ne||null,previousPrice:ce?Number(ce):null,newPrice:ie?Number(ie):null,soldPrice:oe?Number(oe):null,soldDate:be||null,comingSoonDate:Me||null,builderName:Ee||null,yearBuilt:Se?Number(Se):null,warrantyInfo:Te||null,monthlyRent:ct?Number(ct):null,capRate:rt||null,occupancy:Qe||null,daysOnMarket:Ce?Number(Ce):null,offerCount:$t?Number($t):null,originalListPrice:it?Number(it):null,soldDaysOnMarket:Ft?Number(Ft):null,commissionOffered:Ie||null,refreshments:Dt||null,vibe:cs||null,neighborhoodHighlights:dt||null,agentName:yt||null,agentBrokerage:Is||null,agentContact:ar||null}});if(Wm)throw Wm;if(Dl!=null&&Dl.error)throw new Error(Dl.error);hn(Lf=>({...Lf,[dr]:Dl.content}))}catch(Dl){ue.error(Dl.message||"Generation failed")}finally{Xs(Dl=>({...Dl,[dr]:!1}))}},ut=dr=>{navigator.clipboard.writeText(dr),ue.success("Copied to clipboard")},kt=He.icon,Gt=Sr[$r]?Sr[$r].trim().split(/\s+/).length:0,Mt=dr=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:iq.filter(Jn=>Jn.category===dr).map(Jn=>{const uo=Jn.icon,ll=$r===Jn.id,Va=!!Sr[Jn.id];return e.jsxs("button",{onClick:()=>kr(Jn.id),className:Bt("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",ll?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[ll&&e.jsx("div",{className:Bt("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Jn.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Bt("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Jn.accent),children:e.jsx(uo,{className:"h-4 w-4"})}),Va&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Hn,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Jn.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Jn.desc})]})]})]},Jn.id)})}),Kt=(yo=He.extras)==null?void 0:yo.includes("openHouse"),Es=(ra=He.extras)==null?void 0:ra.includes("priceImprovement"),Ls=(ki=He.extras)==null?void 0:ki.includes("sold"),gr=(Qi=He.extras)==null?void 0:Qi.includes("comingSoon"),qr=(Po=He.extras)==null?void 0:Po.includes("newConstruction"),Xr=(ci=He.extras)==null?void 0:ci.includes("investment"),Yn=(za=He.extras)==null?void 0:za.includes("underContract"),Qr=(jo=He.extras)==null?void 0:jo.includes("brokerOpen"),$s=(Pi=He.extras)==null?void 0:Pi.includes("vibe"),Kr=(Lo=He.extras)==null?void 0:Lo.includes("neighborhood"),In=(rc=He.extras)==null?void 0:rc.includes("signoff"),Ja=Kt||Es||Ls||gr||qr||Xr||Yn||Qr||$s||Kr||In;return e.jsx(_s,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(jr,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(vs,{open:Ur,onOpenChange:xn,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(bs,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(aa!=null&&aa.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),aa==null?void 0:aa.map(dr=>e.jsxs("button",{onClick:()=>Fe(dr),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:dr.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[dr.city,dr.state].filter(Boolean).join(", "),dr.price?` · $${Number(dr.price).toLocaleString()}`:"",dr.bedrooms?` · ${dr.bedrooms}bd`:"",dr.bathrooms?` · ${dr.bathrooms}ba`:""]})]},dr.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(Ne,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(De,{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(Cn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Property Details"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Fill in what you have — AI handles the rest"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(ke,{value:t,onChange:dr=>r(dr.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(ke,{value:P,onChange:dr=>D(dr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(ke,{value:B,onChange:dr=>z(dr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(ke,{type:"number",value:N,onChange:dr=>S(dr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(ke,{value:T,onChange:dr=>A(dr.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(ke,{type:"number",value:m,onChange:dr=>x(dr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(ke,{type:"number",step:"0.5",value:g,onChange:dr=>v(dr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(ke,{type:"number",value:j,onChange:dr=>b(dr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(ur,{value:n,onChange:dr=>a(dr.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:o,onChange:dr=>c(dr.target.value),onKeyDown:dr=>dr.key==="Enter"&&(dr.preventDefault(),Na()),placeholder:"e.g. Quartz countertops"}),e.jsx(G,{type:"button",size:"icon",variant:"secondary",onClick:Na,children:e.jsx(Ws,{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((dr,Jn)=>e.jsxs(Ge,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[dr,e.jsx("button",{onClick:()=>Je(Jn),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(_r,{className:"h-3 w-3"})})]},Jn))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Photos (optional)"}),e.jsxs("label",{className:"flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer hover:border-primary hover:bg-accent/30 transition-colors text-sm text-muted-foreground",children:[e.jsx($v,{className:"h-4 w-4"}),us?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:We,disabled:us,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((dr,Jn)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:dr,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>h(uo=>uo.filter((ll,Va)=>Va!==Jn)),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"})})]},Jn))})]}),Ja&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",He.label]})]}),Kt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(ke,{type:"date",value:X,onChange:dr=>K(dr.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(ke,{type:"time",value:Q,onChange:dr=>Y(dr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(ke,{type:"time",value:ne,onChange:dr=>de(dr.target.value)})]})]})]}),Es&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(ke,{type:"number",value:ce,onChange:dr=>ae(dr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(ke,{type:"number",value:ie,onChange:dr=>me(dr.target.value),placeholder:"$"})]})]}),Ls&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(ke,{type:"number",value:oe,onChange:dr=>ge(dr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(ke,{type:"date",value:be,onChange:dr=>Oe(dr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(ke,{type:"number",value:it,onChange:dr=>Nt(dr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ke,{type:"number",value:Ft,onChange:dr=>at(dr.target.value)})]})]})]}),gr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(ke,{type:"date",value:Me,onChange:dr=>Pe(dr.target.value)})]}),qr&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(ke,{value:Ee,onChange:dr=>$e(dr.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(ke,{type:"number",value:Se,onChange:dr=>ze(dr.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(ke,{value:Te,onChange:dr=>ye(dr.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Xr&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(ke,{type:"number",value:ct,onChange:dr=>ve(dr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(ke,{value:rt,onChange:dr=>Re(dr.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Qe,onChange:dr=>Ke(dr.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"})]})]})]}),Yn&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ke,{type:"number",value:Ce,onChange:dr=>nt(dr.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(ke,{type:"number",value:$t,onChange:dr=>lt(dr.target.value),placeholder:"e.g. 5"})]})]}),Qr&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(ke,{value:Ie,onChange:dr=>et(dr.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(ke,{value:Dt,onChange:dr=>Jt(dr.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),$s&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:cs,onChange:dr=>Ht(dr.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"})]})]}),Kr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(ur,{value:dt,onChange:dr=>Qt(dr.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),In&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border/40",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sign-off (optional)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(ke,{value:yt,onChange:dr=>ss(dr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(ke,{value:Is,onChange:dr=>fs(dr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(ke,{value:ar,onChange:dr=>Er(dr.target.value),placeholder:"555-123-4567 or you@brand.com"})]})]})]})]})}),e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"flex gap-2 p-1 rounded-xl bg-muted/60 border border-border/40 overflow-x-auto",children:[{key:"listing",label:"Listing Copy",icon:ln},{key:"social",label:"Social Media",icon:au},{key:"video",label:"Video Scripts",icon:sn},{key:"email",label:"Email Marketing",icon:Qs}].map(dr=>{const Jn=dr.icon,uo=Tr===dr.key;return e.jsxs("button",{onClick:()=>Hr(dr.key),className:Bt("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",uo?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Jn,{className:"h-4 w-4"}),dr.label]},dr.key)})}),Mt(Tr),e.jsxs(Ne,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Bt("h-1 bg-gradient-to-r",He.accent)}),e.jsxs(De,{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:Bt("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",He.accent),children:e.jsx(kt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[He.label,e.jsx(Ge,{variant:"outline",className:"text-[10px] font-normal",children:He.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Sr[$r]?`${Gt} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[Sr[$r]&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>ut(Sr[$r]),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(G,{onClick:()=>bt($r),disabled:zn[$r],className:Bt("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",He.accent),size:"sm",children:zn[$r]?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):Sr[$r]?e.jsxs(e.Fragment,{children:[e.jsx(Di,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ag,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),Sr[$r]?e.jsx(ur,{value:Sr[$r],onChange:dr=>hn(Jn=>({...Jn,[$r]:dr.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:Bt("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",He.accent),children:e.jsx(Ag,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",He.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 lR({delay:s,x:t,y:r,size:n}){return e.jsx(Cr.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 gOs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,g=gL[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(Cr.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(Cr.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(lR,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(lR,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(lR,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(lR,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(lR,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Cr.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(Cr.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(Cr.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(Cr.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(Cr.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:g.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Cr.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(Cr.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:g.title[0]}),g.title[1]&&e.jsx(Cr.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:g.title[1]}),e.jsxs(Cr.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(Cr.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(Cr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Cr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Cr.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||g.defaultMessage}),e.jsxs(Cr.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(Cr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),h&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(Cr.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(Nn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Cr.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(Qs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Cr.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 D_e({delay:s,x:t,y:r,color:n,size:a}){return e.jsx(Cr.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 cR({delay:s,x:t,y:r}){return e.jsx(Cr.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 CHe={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 yOs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,g=gL[t],v=CHe[t]||CHe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${v.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(D_e,{delay:0,x:"10%",y:"10%",color:v.orbs[0],size:200}),e.jsx(D_e,{delay:1,x:"70%",y:"60%",color:v.orbs[1],size:180}),e.jsx(D_e,{delay:2,x:"50%",y:"20%",color:v.orbs[2],size:150}),e.jsx(cR,{delay:0,x:"20%",y:"25%"}),e.jsx(cR,{delay:.8,x:"75%",y:"15%"}),e.jsx(cR,{delay:1.6,x:"85%",y:"65%"}),e.jsx(cR,{delay:2.4,x:"10%",y:"75%"}),e.jsx(cR,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Cr.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(Cr.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(Cr.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(Cr.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(Cr.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:g.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Cr.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(Cr.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(Cr.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:g.title[0]}),g.title[1]&&e.jsx(Cr.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:g.title[1]}),e.jsx(Cr.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:g.emojis.slice(0,3).join("")}),e.jsxs(Cr.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(Cn,{className:"h-3.5 w-3.5"}),n]})]}),m&&e.jsx(Cr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Cr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Cr.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||g.defaultMessage})}),e.jsxs(Cr.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(Cr.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),h&&e.jsx("p",{className:"text-xs text-violet-300/60",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(Cr.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(Nn,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Cr.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(Qs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Cr.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 vOs({emoji:s,delay:t,x:r,duration:n}){return e.jsx(Cr.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 THe={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 bOs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,g=gL[t],v=THe[t]||THe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${v.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[g.emojis.map((j,b)=>e.jsx(vOs,{emoji:j,delay:b*1.2,x:`${15+b*14}%`,duration:5+b%3},b)),e.jsx(Cr.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(Cr.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(Cr.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(Cr.div,{className:`h-28 bg-gradient-to-r ${v.header} relative overflow-hidden`,children:[e.jsx(Cr.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(Cr.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:g.emojis[0]}),e.jsx(Cr.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:g.emojis[1]}),e.jsx(Cr.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:g.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Cr.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(Cr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:g.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Cr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${v.accent}`,children:[e.jsx(Cr.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(Cr.h1,{className:`text-3xl font-bold ${v.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[g.title.join(" ")," ",g.emojis[4]]}),e.jsxs(Cr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${v.text} mb-1`,children:r}),n&&e.jsxs("p",{className:`text-sm ${v.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ja,{className:"h-3 w-3"}),n]})]}),m&&e.jsx(Cr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Cr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Cr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${v.text} leading-relaxed italic`,children:['"',i||g.defaultMessage,'"']})}),e.jsxs(Cr.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(Cr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${v.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${v.accent}`,children:l}),h&&e.jsx("p",{className:`text-xs ${v.text} opacity-60`,children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Cr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Cr.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Qs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Cr.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 oq({delay:s,x:t,y:r,size:n,color:a}){return e.jsx(Cr.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 R_e({delay:s,x:t,y:r,size:n}){return e.jsx(Cr.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 EHe={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 _Os(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,g=gL[t],v=EHe[t]||EHe.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(oq,{delay:0,x:"5%",y:"10%",size:300,color:v.mesh[0]}),e.jsx(oq,{delay:2,x:"60%",y:"50%",size:250,color:v.mesh[1]}),e.jsx(oq,{delay:4,x:"30%",y:"70%",size:200,color:v.mesh[2]}),e.jsx(oq,{delay:1,x:"80%",y:"15%",size:180,color:v.mesh[0]}),e.jsx(R_e,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(R_e,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(R_e,{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(Cr.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(Cr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${v.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(Cr.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(Cr.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(Cr.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(Cr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:g.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Cr.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(Cr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${v.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Cr.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:g.title[0]}),g.title[1]&&e.jsx(Cr.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:g.title[1]}),e.jsxs(Cr.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(ja,{className:"h-3 w-3"})," ",n]})]}),e.jsx(Cr.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(Cr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Cr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Cr.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||g.defaultMessage,'"']})}),e.jsxs(Cr.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(Cr.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),h&&e.jsx("p",{className:"text-xs text-white/30",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Cr.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(Nn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Cr.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(Qs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Cr.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 O_e({delay:s,x:t,angle:r,color:n}){return e.jsx(Cr.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 lq({delay:s,x:t}){return e.jsx(Cr.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 AHe={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 wOs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,g=gL[t],v=AHe[t]||AHe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${v.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(O_e,{delay:0,x:"20%",angle:15,color:v.stripe}),e.jsx(O_e,{delay:2,x:"75%",angle:-12,color:v.stripe}),e.jsx(O_e,{delay:4,x:"50%",angle:5,color:v.stripe}),e.jsx(lq,{delay:0,x:"30%"}),e.jsx(lq,{delay:1.5,x:"60%"}),e.jsx(lq,{delay:3,x:"45%"}),e.jsx(lq,{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(Cr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Cr.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(Cr.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(Cr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${v.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:g.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Cr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Cr.span,{className:`text-6xl font-black bg-gradient-to-r ${v.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(Cr.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:g.title[0]})}),g.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Cr.h2,{className:`text-5xl font-black bg-gradient-to-r ${v.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:g.title[1]})}),e.jsxs(Cr.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(ja,{className:"h-3 w-3"})," ",n]})]}),e.jsxs(Cr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Cr.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(Cr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Cr.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(Cr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),x&&e.jsx(Cr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Cr.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||g.defaultMessage}),e.jsxs(Cr.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(Cr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${v.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),h&&e.jsx("p",{className:"text-[11px] text-white/25",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Cr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Cr.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(Qs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Cr.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 Igt(){const{shareToken:s}=Xi(),{data:t,isLoading:r,error:n}=gt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await H.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(k.useEffect(()=>{s&&H.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()-Ul(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(yOs,{...i});case"warm":return e.jsx(bOs,{...i});case"glass":return e.jsx(_Os,{...i});case"cinematic":return e.jsx(wOs,{...i});case"elegant":default:return e.jsx(gOs,{...i})}}function jOs(){const s=na();return gt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await H.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function NOs(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n}=await H.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(n){const{data:a,error:i}=await H.from("drip_settings").update(r).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await H.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 kOs(){const s=vr(),{isGmailConnected:t,gmailEmail:r}=Oh(),{data:n,isLoading:a}=jOs(),i=NOs(),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[h,m]=k.useState(!1);k.useEffect(()=>{n&&(o(n.is_globally_enabled),d(n.append_signature))},[n]);const x=async v=>{if(v&&!t){ue.error("Connect your Gmail account first before enabling Smart Drips");return}o(v);try{await i.mutateAsync({is_globally_enabled:v}),ue.success(v?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!v),ue.error("Failed to update settings")}},g=async v=>{d(v);try{await i.mutateAsync({append_signature:v}),ue.success(v?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!v),ue.error("Failed to update settings")}};return e.jsxs(vs,{open:h,onOpenChange:m,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(lo,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(lo,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Fr,{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(Qs,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),r&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r})]})]}),t?e.jsxs(Ge,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Mn,{className:"h-3 w-3"}),"Active"]}):e.jsxs(G,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{m(!1),s("/mission-control/integrations")},children:[e.jsx(Yr,{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(po,{}),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(jO,{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(br,{checked:l,onCheckedChange:x,disabled:a||i.isPending})]}),e.jsx(po,{}),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(bv,{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(br,{checked:c,onCheckedChange:g,disabled:a||i.isPending})]}),c&&e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{m(!1),s("/profile")},children:[e.jsx(bv,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function SOs(){const s=na();return gt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.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 COs(){const s=na();return gt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function TOs(){const s=na(),t=es();return Lt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await H.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 EOs(){const s=es();return Lt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await H.from("drip_templates").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function AOs(){const s=es();return Lt({mutationFn:async t=>{const{error:r}=await H.from("drip_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function MOs(){const s=na(),t=es();return Lt({mutationFn:async({templateId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await H.from("drip_templates").select("*").eq("id",r).single();if(i)throw i;const{data:l,error:o}=await H.from("drip_templates").insert({owner_user_id:s,stage_id:n,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const IOs=[{key:"{{client_first_name}}",label:"Client First Name"},{key:"{{client_last_name}}",label:"Client Last Name"},{key:"{{property_address}}",label:"Property Address"},{key:"{{agent_name}}",label:"Your Name"},{key:"{{agent_phone}}",label:"Your Phone"},{key:"{{close_date}}",label:"Target Close Date"},{key:"{{stage_name}}",label:"Current Stage"},{key:"{{portal_link}}",label:"Portal Link"},{key:"{{review_link}}",label:"Review Link"}];function POs({open:s,onOpenChange:t,campaignId:r,campaignName:n}){const{data:a,isLoading:i}=W5s(r||void 0),l=Y5s(),o=Fmt(),c=async(m,x)=>{try{await l.mutateAsync({id:m,status:x}),ue.success(`Enrollment ${x}`)}catch{ue.error("Failed to update")}},d=async m=>{if(r)try{const x=await o.mutateAsync({campaignId:r,contactIds:[m]});x.enrolled>0?ue.success("Contact re-enrolled — first email queued"):x.skipped>0?ue.message("Already active in this campaign"):ue.error("Could not re-enroll")}catch{ue.error("Failed to re-enroll")}},h=m=>{const x={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Ge,{variant:"outline",className:`text-[10px] capitalize ${x[m]||""}`,children:m})};return e.jsx(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(fr,{className:"h-4 w-4 text-primary"}),"Enrollments — ",n||"Campaign"]}),e.jsx(Fr,{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(Vs,{className:"h-14"},m))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(fr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(m=>{var x,g,v,j;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(x=m.contact)==null?void 0:x.first_name," ",(g=m.contact)==null?void 0:g.last_name]}),h(m.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((v=m.contact)==null?void 0:v.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qs,{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: ",Ss(new Date(m.next_send_at),"MMM d, h:mma")]}),m.exit_reason&&e.jsxs("span",{children:["Exit: ",m.exit_reason]})]})]}),m.status==="active"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"paused"),title:"Pause",children:e.jsx(cm,{className:"h-3.5 w-3.5"})}),m.status==="paused"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"active"),title:"Resume",children:e.jsx(Ho,{className:"h-3.5 w-3.5"})}),(m.status==="active"||m.status==="paused")&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"exited"),title:"Exit",children:e.jsx(_r,{className:"h-3.5 w-3.5 text-destructive"})}),(m.status==="exited"||m.status==="completed")&&((j=m.contact)==null?void 0:j.id)&&e.jsxs(G,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(m.contact.id),disabled:o.isPending,children:[e.jsx(Wv,{className:"h-3 w-3"}),"Re-enroll"]})]},m.id)})})})})]})})}function LOs(){var T;const{data:s,isLoading:t}=cAe(),{hasLeadSite:r}=ey(),n=q5s(),a=U5s(),i=Rmt(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,g]=k.useState(null),v=(s||[]).filter(A=>!A.is_starter),j=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||r),b=async A=>{try{await n.mutateAsync(A),ue.success("Campaign added to your library — customize and activate it!"),o(null)}catch(P){ue.error(P.message||"Failed to copy campaign")}},N=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ue.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ue.error("Failed to update")}},S=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ue.success("Campaign deleted")}catch{ue.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(A=>e.jsx(Vs,{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(T3,{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(zd,{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(Zr,{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(fr,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(G,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),v.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(jr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(G,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(A=>e.jsx(DOs,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>N(A),onDelete:()=>S(A.id),onEdit:()=>{m(A.id),d(!0)},onViewEnrollments:()=>g(A.id)},A.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:[j.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:j.map(A=>e.jsx(ROs,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(OOs,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:b,isCloning:n.isPending,onEdit:A=>{o(null),m(A),d(!0)}}),e.jsx($mt,{open:c,onOpenChange:d,campaignId:h}),e.jsx(POs,{open:!!x,onOpenChange:A=>!A&&g(null),campaignId:x,campaignName:(T=v.find(A=>A.id===x))==null?void 0:T.name})]})}function DOs({campaign:s,onPreview:t,onToggleActive:r,onDelete:n,onEdit:a,onViewEnrollments:i}){const o=K5s(s.id).data??0,c=!s.is_active&&o>0;return e.jsxs("div",{className:"group rounded-xl border bg-card overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`h-20 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:s.icon}),s.is_active&&e.jsx(Ge,{className:"absolute top-2 right-2 bg-emerald-500 hover:bg-emerald-500 text-white text-[10px]",children:"Active"})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description||"No description"}),e.jsx(Ge,{variant:"outline",className:"text-[9px] mt-2",children:Ege[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(od,{className:"h-3 w-3 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-[10px] leading-tight text-amber-700 dark:text-amber-300",children:[e.jsxs("strong",{children:[o," contact",o===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-3",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(G,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:r,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:n,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function ROs({campaign:s,onPreview:t}){return e.jsxs("button",{onClick:t,className:"group rounded-xl border bg-card overflow-hidden hover:shadow-xl hover:scale-[1.02] transition-all text-left",children:[e.jsxs("div",{className:`h-24 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:s.icon}),e.jsxs(Ge,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(jr,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(Ge,{variant:"outline",className:"text-[9px] mt-2",children:Ege[s.category]})]})]})}function OOs({campaignId:s,open:t,onOpenChange:r,onClone:n,isCloning:a,onEdit:i}){const{data:l}=cAe(),{data:o}=Omt(s||void 0),[c,d]=k.useState(new Set),h=l==null?void 0:l.find(g=>g.id===s);if(!h)return null;const m=g=>{d(v=>{const j=new Set(v);return j.has(g)?j.delete(g):j.add(g),j})},x=(g,v)=>{if(g.delay_type==="calendar_anchor"){const b=g.anchor_field==="birthday"?"birthday":"home anniversary",N=g.anchor_offset_days||0;return N===0?`On their ${b}`:N<0?`${Math.abs(N)} days before ${b}`:`${N} days after ${b}`}if(v===0&&g.delay_days===0&&g.delay_hours===0)return"Sends immediately";const j=[];return g.delay_days&&j.push(`${g.delay_days}d`),g.delay_hours&&j.push(`${g.delay_hours}h`),v===0?`After ${j.join(" ")}`:`+${j.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 ${h.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:h.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(bs,{className:"text-xl font-bold text-white",children:h.name}),e.jsx(Fr,{className:"text-white/90 mt-1",children:h.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Ge,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:Ege[h.category]}),e.jsxs(Ge,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),h.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((g,v)=>{const j=c.has(g.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:v+1}),vm(g.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:[g.delay_type==="calendar_anchor"?e.jsx(rn,{className:"h-3 w-3"}):e.jsx(cn,{className:"h-3 w-3"}),e.jsx("span",{children:x(g,v)}),e.jsx("span",{children:"·"}),e.jsx(Qs,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:g.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:g.subject}),j?e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:g.body}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 whitespace-pre-line",children:g.body}),g.body&&g.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:j?"Show less":"Show full email"})]})})]},g.id)})]})}),e.jsxs(on,{className:"border-t p-4 shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!h.is_starter&&i&&e.jsxs(G,{variant:"secondary",onClick:()=>i(h.id),children:[e.jsx(Ta,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),h.is_starter&&e.jsxs(G,{onClick:()=>n(h.id),disabled:a,children:[a?e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}function FOs(){const s=na(),t=vr(),{isGmailConnected:r,gmailEmail:n,isLoading:a}=Oh(),{data:i,isLoading:l}=SOs(),{data:o,isLoading:c}=COs(),d=TOs(),h=EOs(),m=AOs(),x=MOs(),[g,v]=k.useState(null),[j,b]=k.useState(null),N=(i==null?void 0:i.filter(F=>!F.is_starter&&F.owner_user_id===s))||[],S=(i==null?void 0:i.filter(F=>F.is_starter))||[],T=F=>N.filter($=>$.stage_id===F),A=async F=>{try{await h.mutateAsync({id:F.id,is_enabled:!F.is_enabled}),ue.success(F.is_enabled?"Drip disabled":"Drip enabled")}catch{ue.error("Failed to update")}},P=async F=>{try{const $=o==null?void 0:o.find(X=>X.id===F);await d.mutateAsync({stage_id:F,title:`${($==null?void 0:$.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),v(F),ue.success("Drip template created")}catch{ue.error("Failed to create template")}},D=async F=>{try{await m.mutateAsync(F),ue.success("Template deleted")}catch{ue.error("Failed to delete")}},B=async F=>{if(!o||o.length===0){ue.error("No pipeline stages found");return}const $=o[0].id;try{await x.mutateAsync({templateId:F,stageId:$}),ue.success("Template copied to your drips!")}catch{ue.error("Failed to copy template")}},z=l||c;return e.jsx(_s,{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(Xu,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Ge,{variant:"outline",className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 border-amber-500 text-amber-600 bg-amber-500/10",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Automatically send personalized emails when deals move through your pipeline."})]}),e.jsx(kOs,{})]}),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(T3,{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(Qs,{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(T3,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium text-foreground mb-0.5",children:"Drips will send from our shared sender"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["You haven't connected Gmail, so drips will send from ",e.jsx("strong",{children:"send.relevelup.com"})," with your name on the From line and your email as Reply-To. Connect Gmail to send directly from your own inbox for better deliverability and a more personal touch."]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(Qs,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(Rn,{defaultValue:"my-drips",children:[e.jsxs(Dn,{className:"grid grid-cols-3 w-full max-w-lg mb-6",children:[e.jsx(Xt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Xt,{value:"campaigns",children:["Campaigns",e.jsx(Ge,{variant:"outline",className:"ml-1.5 text-[9px] bg-amber-500/10 text-amber-600 border-amber-200 px-1 py-0",children:"New"})]}),e.jsxs(Xt,{value:"starters",children:["Stage Starters",S.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:S.length})]})]}),e.jsx(as,{value:"campaigns",children:e.jsx(LOs,{})}),e.jsx(as,{value:"my-drips",children:z?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(F=>e.jsx(Vs,{className:"h-16 w-full rounded-xl"},F))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(Xu,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(F=>!F.is_won_stage&&!F.is_lost_stage).map(F=>{const $=T(F.id),X=g===F.id,K=$.some(Q=>Q.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>v(X?null:F.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),$.length>0&&e.jsxs(Ge,{variant:"outline",className:`text-[10px] ${K?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[$.length," drip",$.length!==1?"s":"",K&&" · Active"]}),X?e.jsx(so,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})]}),X&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:$.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>P(F.id),disabled:d.isPending,children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[$.map(Q=>e.jsx(MHe,{template:Q,isEditing:j===Q.id,onToggleEdit:()=>b(j===Q.id?null:Q.id),onToggleEnabled:()=>A(Q),onUpdate:Y=>h.mutateAsync({id:Q.id,...Y}),onDelete:()=>D(Q.id),userId:s||""},Q.id)),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>P(F.id),children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)}),o.filter(F=>F.is_won_stage||F.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(F=>F.is_won_stage||F.is_lost_stage).map(F=>{const $=T(F.id),X=g===F.id,K=$.some(Q=>Q.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>v(X?null:F.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),$.length>0&&e.jsxs(Ge,{variant:"outline",className:`text-[10px] ${K?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[$.length," drip",$.length!==1?"s":"",K&&" · Active"]}),X?e.jsx(so,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})]}),X&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:$.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>P(F.id),disabled:d.isPending,children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[$.map(Q=>e.jsx(MHe,{template:Q,isEditing:j===Q.id,onToggleEdit:()=>b(j===Q.id?null:Q.id),onToggleEnabled:()=>A(Q),onUpdate:Y=>h.mutateAsync({id:Q.id,...Y}),onDelete:()=>D(Q.id),userId:s||""},Q.id)),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>P(F.id),children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)})]})]})}),e.jsx(as,{value:"starters",children:S.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(jr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:S.map(F=>e.jsx(BOs,{template:F,onCopy:()=>B(F.id),isCopying:x.isPending},F.id))})})]})]})})}function MHe({template:s,isEditing:t,onToggleEdit:r,onToggleEnabled:n,onUpdate:a,onDelete:i,userId:l}){const[o,c]=k.useState(s.title),[d,h]=k.useState(s.subject),[m,x]=k.useState(s.body),[g,v]=k.useState(s.video_url||""),[j,b]=k.useState(s.channel),[N,S]=k.useState(s.delay_type),[T,A]=k.useState(s.delay_minutes),[P,D]=k.useState(!1),B=async()=>{D(!0);try{await a({title:o,subject:d,body:m,video_url:g||null,channel:j,delay_type:N,delay_minutes:T}),ue.success("Drip saved"),r()}catch{ue.error("Failed to save")}finally{D(!1)}},z=F=>{x($=>$+F)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:r,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(bi,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Qs,{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(sn,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(br,{checked:s.is_enabled,onCheckedChange:n})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(ke,{value:o,onChange:F=>c(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(F=>e.jsxs("button",{onClick:()=>b(F),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j===F?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[F==="sms"?e.jsx(bi,{className:"h-3 w-3"}):e.jsx(Qs,{className:"h-3 w-3"}),F==="sms"?"SMS":"Email"]},F))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>S("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${N==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>S("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${N==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(cn,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),N==="scheduled"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ke,{type:"number",min:1,value:T>=60?Math.round(T/60):T,onChange:F=>{const $=parseInt(F.target.value)||0;A(T>=60?$*60:$)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:T<60?T:30},{label:"Hours",mins:T>=60?T:60},{label:"Days",mins:T>=1440?T:1440}].map(F=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${F.label==="Minutes"&&T<60||F.label==="Hours"&&T>=60&&T<1440||F.label==="Days"&&T>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{F.label==="Minutes"?A(30):F.label==="Hours"?A(60):A(1440)},children:F.label},F.label))})]})]}),j==="email"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(ke,{value:d,onChange:F=>h(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(he,{className:"text-xs font-medium",children:j==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:F=>{F.target.value&&z(F.target.value),F.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),IOs.map(F=>e.jsx("option",{value:F.key,children:F.label},F.key))]})]})]}),e.jsx("textarea",{value:m,onChange:F=>x(F.target.value),placeholder:j==="sms"?"Hey {{client_first_name}}, great talking with you today! Here's a quick video about what's next...":`Hi {{client_first_name}}, It was great meeting with you! Here's a video about what to expect next...`,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[100px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Attached Video"}),g?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(sn,{className:"h-3 w-3 inline mr-1 text-primary"}),g.length>50?g.slice(0,50)+"...":g]}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>v(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(dMe,{onVideoReady:F=>v(F)}),e.jsx(sL,{userId:l,onSelect:F=>v(F),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const F=prompt("Paste a YouTube or Loom URL:");F&&v(F)},children:[e.jsx(xo,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(yr,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",className:"text-xs",onClick:r,children:"Cancel"}),e.jsx(G,{size:"sm",className:"text-xs",onClick:B,disabled:P,children:P?"Saving...":"Save Drip"})]})]})]})]})}function BOs({template:s,onCopy:t,isCopying:r}){const[n,a]=k.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!n),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!n&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(bi,{className:"h-3 w-3"}):e.jsx(Qs,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),n?e.jsx(so,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(ya,{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(cn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(G,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:r,children:[e.jsx(Ra,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const Pgt=()=>{const s=sc();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 zOs(){return k.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(Nue,{children:[e.jsx(ps,{path:"/c/:shareToken",element:e.jsx(Igt,{})}),e.jsx(ps,{path:"*",element:e.jsx(Pgt,{})})]})}const F_e={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Lgt({slugOverride:s}){const t=Xi(),r=s||t.slug,[n,a]=k.useState("types"),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState(new Date),[g,v]=k.useState({name:"",email:"",phone:"",message:""}),[j,b]=k.useState(!1),{data:N,isLoading:S}=gt({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:Y,error:ne}=await H.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(ne)throw ne;return Y},enabled:!!r}),{data:T}=gt({queryKey:["public-booking-profile",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Y,error:ne}=await H.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",N.user_id).single();if(ne)throw ne;return Y},enabled:!!(N!=null&&N.user_id)}),{data:A=[]}=gt({queryKey:["public-booking-types",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Y,error:ne}=await H.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",N.user_id).eq("is_active",!0).order("sort_order");if(ne)throw ne;return Y},enabled:!!(N!=null&&N.user_id)}),{data:P=[]}=gt({queryKey:["public-availability",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Y,error:ne}=await H.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",N.user_id).eq("is_active",!0);if(ne)throw ne;return Y},enabled:!!(N!=null&&N.user_id)}),{data:D=[]}=gt({queryKey:["public-blocked-dates",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Y,error:ne}=await H.from("agent_blocked_dates").select("blocked_date").eq("user_id",N.user_id);if(ne)throw ne;return Y.map(de=>de.blocked_date)},enabled:!!(N!=null&&N.user_id)}),{data:B=[]}=gt({queryKey:["public-existing-bookings",N==null?void 0:N.user_id,o],queryFn:async()=>{if(!o)return[];const Y=Ss(o,"yyyy-MM-dd"),{data:ne,error:de}=await H.from("bookings").select("start_time, end_time").eq("agent_user_id",N.user_id).eq("booking_date",Y).eq("status","confirmed");if(de)throw de;return ne},enabled:!!(N!=null&&N.user_id)&&!!o}),z=k.useMemo(()=>[...new Set(P.map(Y=>Y.day_of_week))],[P]),F=Y=>{const ne=Tf(new Date),de=Hl(ne,(N==null?void 0:N.max_advance_days)||30),ce=Hl(ne,0);return v5(Y,ce)||y5(Y,de)||D.includes(Ss(Y,"yyyy-MM-dd"))?!1:z.includes(Y.getDay())},$=k.useMemo(()=>{if(!o||!i||!N)return[];const Y=P.filter(me=>me.day_of_week===o.getDay()),ne=i.duration_minutes,de=N.buffer_minutes||0,ce=[],ae=new Date,ie=(N.min_notice_hours||2)*60*60*1e3;for(const me of Y){const[oe,ge]=me.start_time.split(":").map(Number),[be,Oe]=me.end_time.split(":").map(Number);let Me=WO(GO(o,oe),ge);const Pe=WO(GO(o,be),Oe);for(;EA(Me,ne)<=Pe;){const Ee=Ss(Me,"HH:mm"),$e=Ss(EA(Me,ne),"HH:mm");Me.getTime()-ae.getTime()>=ie&&(B.some(ze=>{const Te=ze.start_time.slice(0,5),ye=ze.end_time.slice(0,5);return EeTe})||ce.push(Ee)),Me=EA(Me,ne+de)}}return ce},[o,i,P,N,B]),X=k.useMemo(()=>{const Y=m.getFullYear(),ne=m.getMonth(),de=new Date(Y,ne,1),ce=new Date(Y,ne+1,0),ae=de.getDay(),ie=[];for(let me=0;me{if(!(!i||!o||!d||!g.name||!N)){b(!0);try{const Y=Ss(EA(WO(GO(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:ne}=await H.from("bookings").insert({agent_user_id:N.user_id,booking_type_id:i.id,booking_date:Ss(o,"yyyy-MM-dd"),start_time:d,end_time:Y,guest_name:g.name,guest_email:g.email||null,guest_phone:g.phone||null,guest_message:g.message||null});if(ne)throw ne;H.functions.invoke("booking-notify",{body:{agentUserId:N.user_id,guestName:g.name,guestEmail:g.email||null,guestPhone:g.phone||null,guestMessage:g.message||null,bookingTypeName:i.name,bookingDate:Ss(o,"yyyy-MM-dd"),startTime:d,endTime:Y,durationMinutes:i.duration_minutes,meetingLink:N.meeting_link||null}}).catch(de=>console.error("Booking notify error:",de)),a("confirmed")}catch(Y){ue.error("Failed to book: "+Y.message)}finally{b(!1)}}},Q=Y=>{const[ne,de]=Y.split(":").map(Number),ce=ne>=12?"PM":"AM";return`${ne%12||12}:${de.toString().padStart(2,"0")} ${ce}`};return S?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):N?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[T!=null&&T.avatar_url?e.jsx("img",{src:T.avatar_url,alt:(T==null?void 0:T.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(Bi,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(T==null?void 0:T.name)||"Agent"}),(T==null?void 0:T.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:T.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:T.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:T.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[n==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:A.map(Y=>e.jsx("button",{onClick:()=>{l(Y),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:Y.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:F_e[Y.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:Y.name}),Y.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:Y.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(cn,{className:"h-3 w-3"}),Y.duration_minutes,"m"]})]})})},Y.id))})]}),n==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),h(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(wa,{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:F_e[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(cn,{className:"h-3 w-3"}),i.duration_minutes," min"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(m,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>x(new Date(m.getFullYear(),m.getMonth()-1)),children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>x(new Date(m.getFullYear(),m.getMonth()+1)),children:e.jsx(ya,{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(Y=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:Y},Y)),X.map((Y,ne)=>{if(!Y)return e.jsx("div",{},`pad-${ne}`);const de=F(Y),ce=o&&$l(Y,o),ae=$l(Y,new Date);return e.jsx("button",{disabled:!de,onClick:()=>{c(Y),h(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ce?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":de?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${ae&&!ce?"ring-1 ring-[#406E71]/40":""}`,children:Y.getDate()},Y.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pd,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(o,"EEEE, MMMM d")})]}),$.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(cn,{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:$.map(Y=>{const ne=d===Y;return e.jsx("button",{onClick:()=>h(Y),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ne?"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(Y)},Y)})}),d&&e.jsx(G,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),n==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(wa,{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:F_e[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(pd,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ss(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{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(he,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(ke,{value:g.name,onChange:Y=>v({...g,name:Y.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(Qs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ke,{type:"email",value:g.email,onChange:Y=>v({...g,email:Y.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Nn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ke,{type:"tel",value:g.phone,onChange:Y=>v({...g,phone:Y.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(ur,{value:g.message,onChange:Y=>v({...g,message:Y.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),e.jsx(G,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:K,disabled:!g.name||j,children:j?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(Mn,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(T==null?void 0:T.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&Ss(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."}),((T==null?void 0:T.phone)||(T==null?void 0:T.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Call"]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(Qs,{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(pd,{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 $Os(){const t=sc().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(Lgt,{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 UOs(){const t=sc().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(Unt,{slugOverride:t})}function qOs(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 VOs={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function HOs({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=VOs[s.heading_font||"playfair"],h=s.eyebrow||null,m=s.headline_accent||null,x=Array.isArray(s.trust_pills)?s.trust_pills:[],g=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(GOs,{src:s.logo_url}),h&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:h}),e.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:d,letterSpacing:"-0.015em"},children:[s.hero_headline,m&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:m})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(Nn,{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(Qs,{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:[g.map(v=>e.jsxs("div",{children:[e.jsxs(he,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[v.label,v.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(v,r,n,c)})]},v.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),x.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:x.map((v,j)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),v]},j))})]})})]})})]})}function GOs({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(qOs(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 Dgt({slugOverride:s}){const{slug:t}=Xi(),r=s||t,[n,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(0),[d,h]=k.useState(!1),{data:m,isLoading:x}=gt({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:B,error:z}=await H.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(z)throw z;return B},enabled:!!r}),{data:g=[]}=gt({queryKey:["public-landing-page-fields",m==null?void 0:m.id],queryFn:async()=>{const{data:B,error:z}=await H.from("landing_page_fields").select("*").eq("page_id",m.id).order("sort_order");if(z)throw z;return B},enabled:!!(m!=null&&m.id)});k.useEffect(()=>{m!=null&&m.id&&H.from("landing_pages").update({view_count:(m.view_count||0)+1}).eq("id",m.id).then(()=>{})},[m==null?void 0:m.id]);const v=Lt({mutationFn:async()=>{const B=g.find(Y=>Y.field_type==="text"&&Y.label.toLowerCase().includes("name")),z=g.find(Y=>Y.field_type==="email"),F=g.find(Y=>Y.field_type==="phone"),$=B?String(i[B.label]||""):null,X=z?String(i[z.label]||""):null,K=F?String(i[F.label]||""):null,{error:Q}=await H.from("landing_page_submissions").insert([{page_id:m.id,answers:JSON.parse(JSON.stringify(i)),contact_name:$,contact_email:X,contact_phone:K,referrer:document.referrer||null,user_agent:navigator.userAgent,utm_source:new URLSearchParams(window.location.search).get("utm_source"),utm_medium:new URLSearchParams(window.location.search).get("utm_medium"),utm_campaign:new URLSearchParams(window.location.search).get("utm_campaign")}]);if(Q)throw Q;H.functions.invoke("landing-page-lead-notify",{body:{page_id:m.id,contact_name:$,contact_email:X,contact_phone:K,answers:i}}).catch(Y=>console.error("Landing page lead notification error:",Y))},onSuccess:()=>a(!0)}),j=B=>{B.preventDefault(),!(g.filter(F=>F.is_required&&!i[F.label]).length>0)&&v.mutate()};if(x)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!m)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const b=m.primary_color||"#406E71",N=m.accent_color||"#2a4c64",S=m,T=m.page_type==="lead_magnet",A=m.page_type==="just_listed"||m.page_type==="just_sold",P=Array.isArray(S.property_photos)?S.property_photos:[],D=S.lead_magnet_file_url||S.lead_magnet_external_url;if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Mn,{className:"h-16 w-16 mx-auto mb-4",style:{color:b}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:T?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:m.success_message}),T&&D&&e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:b},children:[e.jsx(Xa,{className:"h-5 w-5"}),"Download ",S.lead_magnet_file_name||"Your File"]}),m.agent_name&&e.jsxs("div",{className:"mt-6 pt-4 border-t",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),e.jsx("p",{className:"font-semibold",children:m.agent_name}),m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(Nn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(Qs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})});if(A){const B=z=>{const F=parseFloat(z.replace(/[^0-9.]/g,""));return isNaN(F)?z:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&P.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>h(!1),children:[e.jsx("button",{onClick:()=>h(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(_r,{className:"h-8 w-8"})}),e.jsx("button",{onClick:z=>{z.stopPropagation(),c(F=>F===0?P.length-1:F-1)},className:"absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(Vo,{className:"h-6 w-6"})}),e.jsx("img",{src:P[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:z=>z.stopPropagation()}),e.jsx("button",{onClick:z=>{z.stopPropagation(),c(F=>F===P.length-1?0:F+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(ya,{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," / ",P.length]})]}),P.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:S.property_status==="just_sold"?"#e74c3c":b},children:S.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),P.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),h(!0)},children:[e.jsx("img",{src:P[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(r2,{className:"h-4 w-4"})," View"]})]}):P.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:P.slice(0,2).map((z,F)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(F),h(!0)},children:e.jsx("img",{src:z,alt:`Property ${F+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},F))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),h(!0)},children:e.jsx("img",{src:P[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),P.slice(1,5).map((z,F)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(F+1),h(!0)},children:[e.jsx("img",{src:z,alt:`Property ${F+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),F===3&&P.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",P.length-5," more"]})]},F))]}),P.length>2&&e.jsxs("button",{onClick:()=>{c(0),h(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(r2,{className:"h-4 w-4"})," View all ",P.length," photos"]})]}),P.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.hero_subtext})]})}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[e.jsx("div",{className:"md:col-span-3 space-y-6",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[S.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:b},children:B(S.property_price)}),S.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(ja,{className:"h-5 w-5 shrink-0"})," ",S.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[S.property_beds&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(e0,{className:"h-5 w-5",style:{color:b}})," ",S.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),S.property_baths&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(fp,{className:"h-5 w-5",style:{color:b}})," ",S.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),S.property_sqft&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(U3,{className:"h-5 w-5",style:{color:b}})," ",Number(S.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),S.property_description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),e.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:S.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:b},children:S.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:m.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Qs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:j,className:"space-y-3",children:[g.map(z=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs font-medium",children:[z.label,z.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),B_e(z,i,l)]},z.id)),e.jsx(G,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:v.isPending,children:v.isPending?"Submitting...":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return m.theme_style!=="classic"&&!T?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx(HOs,{page:m,fields:g,answers:i,setAnswers:l,onSubmit:j,isSubmitting:v.isPending,renderField:B_e}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.hero_subtext}),T&&S.lead_magnet_file_name&&e.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[e.jsx(Xa,{className:"h-4 w-4"}),"Free Download: ",S.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[T&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:m.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Qs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[g.map(B=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-sm font-medium",children:[B.label,B.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),B_e(B,i,l)]},B.id)),e.jsx(G,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:v.isPending,children:v.isPending?"Submitting...":T?"Get My Free Download":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function B_e(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(ke,{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(ur,{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(zs,{value:String(a),onValueChange:l=>r(o=>({...o,[s.label]:l})),children:[e.jsx(Os,{className:"mt-1",children:e.jsx(Us,{placeholder:"Select..."})}),e.jsx(Fs,{children:i.map(l=>e.jsx(mt,{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(Ei,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(h=>h!==l);r(h=>({...h,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(br,{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(ke,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function WOs(){const t=sc().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(Dgt,{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 KOs=[{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}],nqs={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase"},aqs={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery"},IHe={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","lifestyle_gallery","market_pulse","concierge_services"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase"]};function iqs(s){return IHe[s]||IHe.basic}function YOs(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:KOs,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 ZOs(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function XOs(){const s=ZOs(),{data:t,isLoading:r,error:n}=gt({queryKey:["lead-site",s],queryFn:async()=>{var h;if(!s)return null;const{data:a,error:i}=await H.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 H.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 H.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();m&&((h=m.teams)!=null&&h.avatar_url)&&(o=m.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(m=>m&&typeof m=="object"&&m.text).map(m=>({name:String(m.name||"Client"),text:String(m.text),rating:typeof m.rating=="number"?m.rating:5,location:m.location?String(m.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=YOs(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 QOs(s,t){try{await H.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(r){console.warn("Lead notification failed:",r)}}const Rgt=k.createContext(null);function nye(){const s=k.useContext(Rgt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function JOs({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}}=H.auth.onAuthStateChange(async(x,g)=>{const v=(g==null?void 0:g.user)??null;if(n(v),v){const{data:j}=await H.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",v.id).eq("lead_site_id",s.id).maybeSingle();j&&i({...j,email:v.email||""})}else i(null);o(!1)});return H.auth.getSession().then(({data:{session:x}})=>{n((x==null?void 0:x.user)??null),x!=null&&x.user?H.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",x.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:g})=>{g&&i({...g,email:x.user.email||""}),o(!1)}):o(!1)}),()=>m.unsubscribe()},[s.id]);const c=k.useCallback(async m=>{const x=m.email.toLowerCase().trim(),g=m.phone.replace(/\D/g,""),{data:v,error:j}=await H.auth.signUp({email:x,password:g,options:{data:{full_name:m.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(j){if(j.message.includes("already registered")){await d(x,g);return}throw j}if(v.user){const{error:b}=await H.from("lead_site_consumer_profiles").insert({user_id:v.user.id,lead_site_id:s.id,name:m.name.trim(),phone:m.phone.trim()});b&&console.warn("Consumer profile insert error:",b);const{error:N}=await H.from("lead_site_leads").insert({lead_site_id:s.id,name:m.name.trim(),email:x,phone:m.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});N&&console.error("Lead insert error (CRM sync may not trigger):",N),QOs(s.id,{name:m.name.trim(),email:x,phone:m.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=k.useCallback(async(m,x)=>{const g=x.replace(/\D/g,""),{error:v}=await H.auth.signInWithPassword({email:m.toLowerCase().trim(),password:g});if(v)throw v},[]),h=k.useCallback(async()=>{await H.auth.signOut(),n(null),i(null)},[]);return e.jsx(Rgt.Provider,{value:{user:r,profile:a,isLoading:l,signUp:c,signIn:d,signOut:h},children:t})}function bMe({open:s,mode:t,siteConfig:r,onComplete:n,onSkip:a,theme:i="default",accentColor:l}){var Q;const{signUp:o,signIn:c}=nye(),[d,h]=k.useState(!1),[m,x]=k.useState(""),[g,v]=k.useState(""),[j,b]=k.useState(""),[N,S]=k.useState(!1),[T,A]=k.useState(""),P=t==="required",D=i==="luxury",B=l||(D?"#c9a96e":"#2563eb"),z=((Q=r.agent)==null?void 0:Q.full_name)||"the agent",F={borderColor:`${B}66`,"--tw-ring-color":`${B}66`},$=async Y=>{var de;if(Y.preventDefault(),A(""),!g.trim()||!j.trim()){A("Email and phone number are required.");return}if(!d&&!m.trim()){A("Name is required.");return}if(j.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}S(!0);try{d?await c(g,j):await o({name:m,email:g,phone:j}),n()}catch(ce){(de=ce==null?void 0:ce.message)!=null&&de.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((ce==null?void 0:ce.message)||"Something went wrong. Please try again.")}finally{S(!1)}},X=D?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",K=D?F:void 0;return e.jsx(vs,{open:s,onOpenChange:P?void 0:Y=>{Y||a()},children:e.jsxs(ys,{className:`sm:max-w-md ${D?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:P?Y=>Y.preventDefault():void 0,onEscapeKeyDown:P?Y=>Y.preventDefault():void 0,children:[e.jsxs(js,{children:[e.jsx(bs,{className:"text-xl",style:D?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":P?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Fr,{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 ${z}.`})]}),e.jsxs("form",{onSubmit:$,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:m,onChange:Y=>x(Y.target.value),className:X,style:K}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:g,onChange:Y=>v(Y.target.value),className:X,style:K}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:j,onChange:Y=>b(Y.target.value),className:X,style:K}),e.jsx("p",{className:`text-xs mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),T&&e.jsx("p",{className:"text-red-600 text-sm",children:T}),e.jsx("button",{type:"submit",disabled:N,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${D?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:D?{backgroundColor:B}:void 0,children:N?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{h(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:B},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!P&&!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 _Me({siteConfig:s,pagePath:t}){const r=s.agent;if(!r)return null;const n=`https://${s.subdomainSlug}.thelocalmove.com`,i=(r.areas_served||"").split(/,|;|\|/).map(T=>T.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(d.map(T=>T.toUpperCase()))],m=s.testimonials||[],x=m.length?{"@type":"AggregateRating",ratingValue:(m.reduce((T,A)=>T+(A.rating||5),0)/m.length).toFixed(1),reviewCount:m.length,bestRating:5,worstRating:1}:void 0,g=[r.facebook_url,r.instagram_url,r.linkedin_url].filter(Boolean),v={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...g.length&&{sameAs:g},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(T=>{const[A,P]=T.split(/,\s*/);return{"@type":"City",name:A,...P&&{containedInPlace:{"@type":"State",name:P}}}})},...x&&{aggregateRating:x},...m.length&&{review:m.slice(0,10).map(T=>({"@type":"Review",author:{"@type":"Person",name:T.name},reviewBody:T.text,reviewRating:{"@type":"Rating",ratingValue:T.rating||5,bestRating:5,worstRating:1},...T.location&&{locationCreated:{"@type":"Place",name:T.location}}}))}},j={"@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,...g.length&&{sameAs:g},...r.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...h.length&&{hasCredential:h.map(T=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:T}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},b={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:s.siteTitle||`${r.full_name} Real Estate`,url:n,publisher:{"@id":`${n}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},N=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${r.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],S={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:N.map((T,A)=>({"@type":"SiteNavigationElement",position:A+1,name:T.name,description:T.description,url:`${n}${T.path}`}))};return e.jsxs(il,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(j)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(S)})]})}function oqs({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(il,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function lqs({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(il,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function e8s({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(il,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function cqs({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(il,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function wMe({siteConfig:s}){var g;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=((g=a.split(/,|;|\|/)[0])==null?void 0:g.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,h=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],m=[...new Set(h.map(v=>v.toUpperCase()))],x=[{question:`Who is ${r}?`,answer:`${r} is a ${t.title||"REALTOR®"} with ${n}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${r} serve?`,answer:`${r} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${r.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${r}?`,answer:`You can reach ${r} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...m.length?[{question:`What real estate designations does ${r} hold?`,answer:`${r} holds the following professional designations: ${m.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${r} a licensed real estate agent?`,answer:`Yes, ${r} is a fully licensed real estate professional (License #${d}) with ${n}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${r} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${r.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${r}. ${r.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(e8s,{faqs:x})}const PHe="ls_visitor_geo",t8s=1e3*60*60;function s8s(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 r8s(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 n8s(){try{const s=localStorage.getItem(PHe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,n8s().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=s8s(l),c=r8s(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=a.current;H.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,visitor_city:(h==null?void 0:h.city)||null,visitor_region:(h==null?void 0:h.region)||null,visitor_country:(h==null?void 0:h.country)||null,visitor_lat:(h==null?void 0:h.lat)||null,visitor_lng:(h==null?void 0:h.lng)||null}).then(({error:m})=>{m&&console.error("[PageTracking] insert failed:",m.message)})},[r.pathname,s==null?void 0:s.id,t])}const a8s=3e4;function NMe(s,t){const r=sc(),n=k.useRef(null),a=k.useRef(null),i=k.useRef(0),l=r.pathname,o=i8s(l),c=o8s(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const h=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,m=async()=>{const{data:x,error:g}=await H.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:h,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!g&&x&&(n.current=x.id,i.current>=2&&!x.notified_agent&&H.functions.invoke("lead-site-presence-notify",{body:{visitor_id:x.id,lead_site_id:s.id}}).catch(()=>{}))};return m(),a.current&&clearInterval(a.current),a.current=setInterval(m,a8s),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const h=()=>{n.current&&H.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",h),()=>window.removeEventListener("beforeunload",h)},[s==null?void 0:s.id,t])}function i8s(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 o8s(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 Xn=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},l8s=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=c8s},c8s=Number.MAX_SAFE_INTEGER||9007199254740991;let Ma=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}({}),ir=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}({}),xt=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 io={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},da={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class eA{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 d8s{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 eA(t),this.fast_=new eA(r),this.defaultTTFB_=a,this.ttfb_=new eA(t)}update(t,r){const{slow_:n,fast_:a,ttfb_:i}=this;n.halfLife!==t&&(this.slow_=new eA(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==r&&(this.fast_=new eA(r,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new eA(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 u8s(s,t,r){return(t=m8s(t))in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Vl(){return Vl=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):lj}function DHe(s,t,r){return t[s]?t[s].bind(t):p8s(s,r)}const YSe=KSe();function x8s(s,t,r){const n=KSe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{n[i]=DHe(i,s,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return KSe()}a.forEach(i=>{YSe[i]=DHe(i,s)})}else Vl(YSe,n);return n}const Ml=YSe;function P2(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function g8s(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Ogt(s,t){const r=Object.keys(s),n=Object.keys(t),a=r.length,i=n.length;return!a||!i||a===i&&!r.some(l=>n.indexOf(l)===-1)}function Ex(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const h=d.indexOf("\0");return h!==-1?d.substring(0,h):d}return d.replace(/\0/g,"")}const r=s.length;let n,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((n&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((n&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function Xh(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(!Xn(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return tu(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 b8s extends Bgt{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 zgt(s,t){const r=Object.getPrototypeOf(s);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||zgt(r,t)}}function _8s(s,t){const r=zgt(s,t);r&&(r.enumerable=!0,Object.defineProperty(s,t,r))}const OHe=Math.pow(2,32)-1,w8s=[].push,$gt={video:1,audio:2,id3:3,text:4};function Fu(s){return String.fromCharCode.apply(null,s)}function Ugt(s,t){const r=s[t]<<8|s[t+1];return r<0?65536+r:r}function Ci(s,t){const r=qgt(s,t);return r<0?4294967296+r:r}function FHe(s,t){let r=Ci(s,t);return r*=Math.pow(2,32),r+=Ci(s,t+4),r}function qgt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function j8s(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 no(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=no(s.subarray(a+8,o),t.slice(1));c.length&&w8s.apply(r,c)}a=o}return r}function N8s(s){const t=[],r=s[0];let n=8;const a=Ci(s,n);n+=4;let i=0,l=0;r===0?(i=Ci(s,n),l=Ci(s,n+4),n+=8):(i=FHe(s,n),l=FHe(s,n+8),n+=16),n+=2;let o=s.length+l;const c=Ugt(s,n);n+=2;for(let d=0;d>>31===1)return Ml.warn("SIDX has hierarchical references (not supported)"),null;const v=Ci(s,h);h+=4,t.push({referenceSize:x,subsegmentDuration:v,info:{duration:v/a,start:o,end:o+x-1}}),o+=x,h+=4,n=h}return{earliestPresentationTime:i,timescale:a,version:r,referencesCount:c,references:t}}function Vgt(s){const t=[],r=no(s,["moov","trak"]);for(let a=0;a{const i=Ci(a,4),l=t[i];l&&(l.default={duration:Ci(a,12),flags:Ci(a,20)})}),t}function k8s(s){const t=s.subarray(8),r=t.subarray(86),n=Fu(t.subarray(4,8));let a=n,i;const l=n==="enca"||n==="encv";if(l){const d=no(t,[n])[0].subarray(n==="enca"?28:78);no(d,["sinf"]).forEach(m=>{const x=no(m,["schm"])[0];if(x){const g=Fu(x.subarray(4,8));if(g==="cbcs"||g==="cenc"){const v=no(m,["frma"])[0];v&&(a=Fu(v))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=no(r,["avcC"])[0];c&&c.length>3&&(a+="."+dq(c[1])+dq(c[2])+dq(c[3]),i=cq(o==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const c=no(t,[n])[0],d=no(c.subarray(28),["esds"])[0];if(d&&d.length>7){let h=4;if(d[h++]!==3)break;h=U_e(d,h),h+=2;const m=d[h++];if(m&128&&(h+=2),m&64&&(h+=d[h++]),d[h++]!==4)break;h=U_e(d,h);const x=d[h++];if(x===64)a+="."+dq(x);else break;if(h+=12,d[h++]!==5)break;h=U_e(d,h);const g=d[h++];let v=(g&248)>>3;v===31&&(v+=1+((g&7)<<3)+((d[h]&224)>>5)),a+="."+v}break}case"hvc1":case"hev1":{const c=no(r,["hvcC"])[0];if(c&&c.length>12){const d=c[1],h=["","A","B","C"][d>>6],m=d&31,x=Ci(c,2),g=(d&32)>>5?"H":"L",v=c[12],j=c.subarray(6,12);a+="."+h+m,a+="."+S8s(x).toString(16).toUpperCase(),a+="."+g+v;let b="";for(let N=j.length;N--;){const S=j[N];(S||b)&&(b="."+S.toString(16).toUpperCase()+b)}a+=b}i=cq(o=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=cq(a,r)||a;break}case"vp09":{const c=no(r,["vpcC"])[0];if(c&&c.length>6){const d=c[4],h=c[5],m=c[6]>>4&15;a+="."+pv(d)+"."+pv(h)+"."+pv(m)}break}case"av01":{const c=no(r,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,h=c[1]&31,m=c[2]>>>7?"H":"M",x=(c[2]&64)>>6,g=(c[2]&32)>>5,v=d===2&&x?g?12:10:x?10:8,j=(c[2]&16)>>4,b=(c[2]&8)>>3,N=(c[2]&4)>>2,S=c[2]&3;a+="."+d+"."+pv(h)+m+"."+pv(v)+"."+j+"."+b+N+S+"."+pv(1)+"."+pv(1)+"."+pv(1)+"."+0,i=cq("dav1",r)}break}}return{codec:a,encrypted:l,supplemental:i}}function cq(s,t){const r=no(t,["dvvC"]),n=r.length?r[0]:no(t,["dvcC"])[0];if(n){const a=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return s+"."+pv(a)+"."+pv(i)}}function S8s(s){let t=0;for(let r=0;r<32;r++)t|=(s>>r&1)<<31-r;return t>>>0}function U_e(s,t){const r=t+5;for(;s[t++]&128&&t{const i=n.subarray(8,24);i.some(l=>l!==0)||(Ml.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Xh(i)} -> ${Xh(r)}`),n.set(r,8))})}function T8s(s){const t=[];return Hgt(s,r=>t.push(r.subarray(8,24))),t}function Hgt(s,t){no(s,["moov","trak"]).forEach(n=>{const a=no(n,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=no(i,["enca"]);const o=l.length>0;o||(l=no(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);no(d,["sinf"]).forEach(m=>{const x=Ggt(m);x&&t(x,o)})})})}function Ggt(s){const t=no(s,["schm"])[0];if(t){const r=Fu(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=no(s,["schi","tenc"])[0];if(n)return n}}}function E8s(s,t,r){const n={},a=no(s,["moof","traf"]);for(let i=0;in[i].duration)){let i=1/0,l=0;const o=no(s,["sidx"]);for(let c=0;cm+x.info.duration||0,0);l=Math.max(l,h+d.earliestPresentationTime/d.timescale)}}l&&Xn(l)&&Object.keys(n).forEach(c=>{n[c].duration||(n[c].duration=l*n[c].timescale-n[c].start)})}return n}function A8s(s){const t={valid:null,remainder:null},r=no(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 Zg(s,t){const r=new Uint8Array(s.length+t.length);return r.set(s),r.set(t,s.length),r}function BHe(s,t){const r=[],n=t.samples,a=t.timescale,i=t.id;let l=!1;return no(n,["moof"]).map(c=>{const d=c.byteOffset-8;no(c,["traf"]).map(m=>{const x=no(m,["tfdt"]).map(g=>{const v=g[0];let j=Ci(g,4);return v===1&&(j*=Math.pow(2,32),j+=Ci(g,8)),j/a})[0];return x!==void 0&&(s=x),no(m,["tfhd"]).map(g=>{const v=Ci(g,4),j=Ci(g,0)&16777215,b=(j&1)!==0,N=(j&2)!==0,S=(j&8)!==0;let T=0;const A=(j&16)!==0;let P=0;const D=(j&32)!==0;let B=8;v===i&&(b&&(B+=8),N&&(B+=4),S&&(T=Ci(g,B),B+=4),A&&(P=Ci(g,B),B+=4),D&&(B+=4),t.type==="video"&&(l=aye(t.codec)),no(m,["trun"]).map(z=>{const F=z[0],$=Ci(z,0)&16777215,X=($&1)!==0;let K=0;const Q=($&4)!==0,Y=($&256)!==0;let ne=0;const de=($&512)!==0;let ce=0;const ae=($&1024)!==0,ie=($&2048)!==0;let me=0;const oe=Ci(z,4);let ge=8;X&&(K=Ci(z,ge),ge+=4),Q&&(ge+=4);let be=K+d;for(let Oe=0;Oe>1&63;return r===39||r===40}else return(t&31)===6}function CMe(s,t,r,n){const a=Wgt(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let h=i;if(od){Ml.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[h++]===181){const x=Ugt(a,h);if(h+=2,x===49){const g=Ci(a,h);if(h+=4,g===1195456820){const v=a[h++];if(v===3){const j=a[h++],b=31&j,N=64&j,S=N?2+b*3:0,T=new Uint8Array(S);if(N){T[0]=j;for(let A=1;A16){const m=[];for(let v=0;v<16;v++){const j=a[h++].toString(16);m.push(j.length==1?"0"+j:j),(v===3||v===5||v===7||v===9)&&m.push("-")}const x=o-16,g=new Uint8Array(x);for(let v=0;v>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=n&255,i.set(s,4),a=0,n=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),P8s([112,115,115,104],new Uint8Array([n,0,0,0]),s,i,a,l,r)}function D8s(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=Xh(new Uint8Array(l,r+12,16));let c=null,d=null,h=0;if(i===0)h=28;else{const x=s.getUint32(28);if(!x||n<32+x*16)return{offset:r,size:t};c=[];for(let g=0;g/\(Windows.+Firefox\//i.test(navigator.userAgent),uP={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 TMe(s,t){const r=uP[t];return!!r&&!!r[s.slice(0,4)]}function dB(s,t,r=!0){return!s.split(",").some(n=>!EMe(n,t,r))}function EMe(s,t,r=!0){var n;const a=P2(r);return(n=a==null?void 0:a.isTypeSupported(uB(s,t)))!=null?n:!1}function uB(s,t){return`${t}/mp4;codecs=${s}`}function zHe(s){if(s){const t=s.substring(0,4);return uP.video[t]}return 2}function pfe(s){const t=Kgt();return s.split(",").reduce((r,n)=>{const i=t&&aye(n)?9:uP.video[n];return i?(i*2+r)/(r?3:2):(uP.audio[n]+r)/(r?2:1)},0)}const q_e={};function O8s(s,t=!0){if(q_e[s])return q_e[s];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aO8s(r.toLowerCase(),t))}function B8s(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)&&($He(s,"audio")||$He(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 $He(s,t){return TMe(s,t)&&EMe(s,t)}function z8s(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 $8s(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 UHe(s){const t=P2(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 ZSe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const U8s={supported:!0,powerEfficient:!0,smooth:!0},q8s={supported:!1,smooth:!1,powerEfficient:!1},Ygt={supported:!0,configurations:[],decodingInfoResults:[U8s]};function Zgt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[q8s],error:s}}function V8s(s,t,r,n,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,h=d?parseInt(d):c?1/0:2;let m=null;if(o!=null&&o.length)try{o.length===1&&o[0]?m=t.groups[o[0]].channels:m=o.reduce((x,g)=>{if(g){const v=t.groups[g];if(!v)throw new Error(`Audio track group ${g} not found`);Object.keys(v.channels).forEach(j=>{x[j]=(x[j]||0)+v.channels[j]})}return x},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(x=>aye(x))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(n,30)||s.videoRange!=="SDR"&&s.videoRange!==r||s.bitrate>Math.max(a,8e6))||!!m&&Xn(h)&&Object.keys(m).some(x=>parseInt(x)>h)}function Xgt(s,t,r,n={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!r)return Promise.resolve(Ygt);const i=[],l=H8s(s),o=l.length,c=G8s(s,t,o>0),d=c.length;for(let h=o||1*d||1;h--;){const m={type:"media-source"};if(o&&(m.video=l[h%o]),d){m.audio=c[h%d];const x=m.audio.bitrate;m.video&&x&&(m.video.bitrate-=x)}i.push(m)}if(a){const h=navigator.userAgent;if(a.split(",").some(m=>aye(m))&&Kgt())return Promise.resolve(Zgt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),i))}return Promise.all(i.map(h=>{const m=K8s(h);return n[m]||(n[m]=r.decodingInfo(h))})).then(h=>({supported:!h.some(m=>!m.supported),configurations:i,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:i,decodingInfoResults:[],error:h}))}function H8s(s){var t;const r=(t=s.videoCodec)==null?void 0:t.split(","),n=Qgt(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:uB($8s(c),"video"),width:a,height:i,bitrate:n,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function G8s(s,t,r){var n;const a=(n=s.audioCodec)==null?void 0:n.split(","),i=Qgt(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((h,m)=>{if(m.groupId===o){const x=parseFloat(m.channels||"");a.forEach(g=>{const v={contentType:uB(g,"audio"),bitrate:r?W8s(g,i):i};x&&(v.channels=""+x),h.push(v)})}return h},l):l},[]):[]}function W8s(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 Qgt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function K8s(s){let t="";const{audio:r,video:n}=s;if(n){const a=ZSe(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=ZSe(r.contentType);t+=`${n?"_":""}${a}_c${r.channels}`}return t}const XSe=["NONE","TYPE-0","TYPE-1",null];function Y8s(s){return XSe.indexOf(s)>-1}const gfe=["SDR","PQ","HLG"];function Z8s(s){return!!s&&gfe.indexOf(s)>-1}var zde={No:"",Yes:"YES",v2:"v2"};function qHe(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 HHe(this._audioGroups,t)}hasSubtitleGroup(t){return HHe(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 HHe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function X8s(){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 Q8s(s,t){let r=!1,n=[];if(s&&(r=s!=="SDR",n=[s]),t){n=t.allowedVideoRanges||gfe.slice(0);const a=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:a&&X8s(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const J8s=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}},ec=(s,t)=>JSON.stringify(s,J8s(t));function eFs(s,t,r,n,a){const i=Object.keys(s),l=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let h=!1,m=!1,x=1/0,g=1/0,v=1/0,j=1/0,b=0,N=[];const{preferHDR:S,allowedVideoRanges:T}=Q8s(t,a);for(let z=i.length;z--;){const F=s[i[z]];h||(h=F.channels[2]>0),x=Math.min(x,F.minHeight),g=Math.min(g,F.minFramerate),v=Math.min(v,F.minBitrate),T.filter(X=>F.videoRanges[X]>0).length>0&&(m=!0)}x=Xn(x)?x:0,g=Xn(g)?g:0;const A=Math.max(1080,x),P=Math.max(30,g);v=Xn(v)?v:r,r=Math.max(v,r),m||(t=void 0);const D=i.length>1;return{codecSet:i.reduce((z,F)=>{const $=s[F];if(F===z)return z;if(N=m?T.filter(X=>$.videoRanges[X]>0):[],D){if($.minBitrate>r)return nv(F,`min bitrate of ${$.minBitrate} > current estimate of ${r}`),z;if(!$.hasDefaultAudio)return nv(F,"no renditions with default or auto-select sound found"),z;if(o&&F.indexOf(o.substring(0,4))%5!==0)return nv(F,`audio codec preference "${o}" not found`),z;if(l&&!d){if(!$.channels[l])return nv(F,`no renditions with ${l} channel sound found (channels options: ${Object.keys($.channels)})`),z}else if((!o||d)&&h&&$.channels[2]===0)return nv(F,"no renditions with stereo sound found"),z;if($.minHeight>A)return nv(F,`min resolution of ${$.minHeight} > maximum of ${A}`),z;if($.minFramerate>P)return nv(F,`min framerate of ${$.minFramerate} > maximum of ${P}`),z;if(!N.some(X=>$.videoRanges[X]>0))return nv(F,`no variants with VIDEO-RANGE of ${ec(N)} found`),z;if(c&&F.indexOf(c.substring(0,4))%5!==0)return nv(F,`video codec preference "${c}" not found`),z;if($.maxScore=pfe(z)||$.fragmentError>s[z].fragmentError)?z:(j=$.minIndex,b=$.maxScore,F)},void 0),videoRanges:N,preferHDR:S,minFramerate:g,minBitrate:v,minIndex:j}}function nv(s,t){Ml.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function Jgt(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 tFs(s,t,r,n){return s.slice(r,n+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const m=t.groups[h];m&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach(x=>{c.channels[x]=(c.channels[x]||0)+m.channels[x]}))}),a},{})}function GHe(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 Lv(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 P4(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 nFs(s,t,r,n,a){const i=t[n],o=t.reduce((x,g,v)=>{const j=g.uri;return(x[j]||(x[j]=[])).push(v),x},{})[i.uri];o.length>1&&(n=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,h=i.codecSet.substring(0,4),m=WHe(t,n,x=>{if(x.videoRange!==c||x.frameRate!==d||x.codecSet.substring(0,4)!==h)return!1;const g=x.audioGroups,v=r.filter(j=>!g||g.indexOf(j.groupId)!==-1);return Lv(s,v,a)>-1});return m>-1?m:WHe(t,n,x=>{const g=x.audioGroups,v=r.filter(j=>!g||g.indexOf(j.groupId)!==-1);return Lv(s,v,a)>-1})}function WHe(s,t,r){for(let n=t;n>-1;n--)if(r(s[n]))return n;for(let n=t+1;n{var n;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),h=i?i.stats:a.stats,m=i?i.duration:a.duration,x=d-h.loading.start,g=l.minAutoLevel,v=a.level,j=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||v<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const b=j>-1&&j!==v,N=!!r||b;if(!N&&(c.paused||!c.playbackRate||!c.readyState))return;const S=l.mainForwardBufferInfo;if(!N&&S===null)return;const T=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(x<=Math.max(T,1e3*(m/(A*2))))return;const P=S?S.len/A:0,D=h.loading.first?h.loading.first-h.loading.start:-1,B=h.loaded&&D>-1,z=this.getBwEstimate(),F=l.levels,$=F[v],X=Math.max(h.loaded,Math.round(m*(a.bitrate||$.averageBitrate)/8));let K=B?x-D:x;K<1&&B&&(K=Math.min(x,h.loaded*8/z));const Q=B?h.loaded*1e3/K:0,Y=T/1e3,ne=Q?(X-h.loaded)/Q:X*8/z+Y;if(ne<=P)return;const de=Q?Q*8:z,ce=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,ae=this.hls.config.abrBandWidthUpFactor;let ie=Number.POSITIVE_INFINITY,me;for(me=v-1;me>g;me--){const Oe=F[me].maxBitrate,Me=!F[me].details||ce;if(ie=this.getTimeToLoadFrag(Y,de,m*Oe,Me),ie=ne||ie>m*10)return;B?this.bwEstimator.sample(x-Math.min(T,D),h.loaded):this.bwEstimator.sampleTTFB(x);const oe=F[me].maxBitrate;this.getBwEstimate()*ae>oe&&this.resetEstimator(oe);const ge=this.findBestLevel(oe,g,me,0,P,1,1);ge>-1&&(me=ge),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${v} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${P.toFixed(3)} s Estimated load time for current fragment: ${ne.toFixed(3)} s Estimated load time for down switch fragment: ${ie.toFixed(3)} s TTFB estimate: ${D|0} ms Current BW estimate: ${Xn(z)?z|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${me} @ ${oe|0} bps`),l.nextLoadLevel=l.nextAutoLevel=me,this.clearTimer();const be=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===me&&me>0){const Oe=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${me>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Oe.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,me>g){let Me=this.findBestLevel(this.hls.levels[g].bitrate,g,me,0,Oe,1,1);Me===-1&&(Me=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Me,this.resetEstimator(this.hls.levels[Me].bitrate)}}};b||ne>ie*2?be():this.timer=self.setInterval(be,ie*1e3),l.trigger(xt.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new d8s(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.FRAG_LOADING,this.onFragLoading,this),t.on(xt.FRAG_LOADED,this.onFragLoaded,this),t.on(xt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(xt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.FRAG_LOADING,this.onFragLoading,this),t.off(xt.FRAG_LOADED,this.onFragLoaded,this),t.off(xt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(xt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(xt.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 ir.BUFFER_ADD_CODEC_ERROR:case ir.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ir.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;Xn(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===da.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(xt.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!==da.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,r,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,r),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!n||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=n&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:r,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=n,o=r?r.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let h=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(d){const b=this.findBestLevel(c,l,a,d,0,h,m);if(b>=0)return this.rebufferNotice=-1,b}let x=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const b=this.bitrateTestDelay;b&&(x=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-b,this.info(`bitrate test took ${Math.round(1e3*b)}ms, set first fragment max fetchDuration to ${Math.round(1e3*x)} ms`),h=m=1)}const g=this.findBestLevel(c,l,a,d,x,h,m);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const v=n.levels[l],j=n.loadLevelObj;return j&&(v==null?void 0:v.bitrate)=r;de--){var ne;const ce=v[de],ae=de>m;if(!ce)continue;if(N.useMediaCapabilities&&!ce.supportedResult&&!ce.supportedPromise){const Me=navigator.mediaCapabilities;typeof(Me==null?void 0:Me.decodingInfo)=="function"&&V8s(ce,$,D,B,t,z)?(ce.supportedPromise=Xgt(ce,$,Me,this.supportedCache),ce.supportedPromise.then(Pe=>{if(!this.hls)return;ce.supportedResult=Pe;const Ee=this.hls.levels,$e=Ee.indexOf(ce);Pe.error?this.warn(`MediaCapabilities decodingInfo error: "${Pe.error}" for level ${$e} ${ec(Pe)}`):Pe.supported?Pe.decodingInfoResults.some(Se=>Se.smooth===!1||Se.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${$e} not smooth or powerEfficient: ${ec(Pe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${$e} ${ec(Pe)}`),$e>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${$e}`),this.hls.removeLevel($e),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Pe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Pe}`)})):ce.supportedResult=Ygt}if((P&&ce.codecSet!==P||D&&ce.videoRange!==D||ae&&B>ce.frameRate||!ae&&B>0&&BMe.smooth===!1))&&(!A||de!==X)){Y.push(de);continue}const ie=ce.details,me=(g?ie==null?void 0:ie.partTarget:ie==null?void 0:ie.averagetargetduration)||K;let oe;ae?oe=o*t:oe=l*t;const ge=K&&a>=K*2&&i===0?ce.averageBitrate:ce.maxBitrate,be=this.getTimeToLoadFrag(Q,oe,ge*me,ie===void 0);if(oe>=ge&&(de===h||ce.loadError===0&&ce.fragmentError===0)&&(be<=Q||!Xn(be)||T&&!this.bitrateTestDelay||be${de} adjustedbw(${Math.round(oe)})-bitrate=${Math.round(oe-ge)} ttfb:${Q.toFixed(1)} avgDuration:${me.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${be.toFixed(1)} firstSelection:${A} codecSet:${ce.codecSet} videoRange:${ce.videoRange} hls.loadLevel:${b}`)),A&&(this.firstSelection=de),de}}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 eyt={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 iFs(s,t,r){if(t===null||!Array.isArray(s)||!s.length||!Xn(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)&&KHe(r,n,i)===0||oFs(i,s,Math.min(a,n))))return i;const l=eyt.search(t,KHe.bind(null,r,n));return l&&(l!==s||!i)?l:i}function oFs(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 KHe(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 lFs(s,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>s}function tyt(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 eyt.search(n,l=>l.cct?-1:(i=l,l.end<=r?1:l.start>r?-1:0)),i||null}return null}function vfe(s){switch(s.details){case ir.FRAG_LOAD_TIMEOUT:case ir.KEY_LOAD_TIMEOUT:case ir.LEVEL_LOAD_TIMEOUT:case ir.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function syt(s){return s.details.startsWith("key")}function ryt(s){return syt(s)&&!!s.frag&&!s.frag.decryptdata}function YHe(s,t){const r=vfe(t);return s.default[`${r?"timeout":"error"}Retry`]}function AMe(s,t){const r=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*s.retryDelayMs,s.maxRetryDelayMs)}function ZHe(s){return Cl(Cl({},s),{errorRetry:null,timeoutRetry:null})}function bfe(s,t,r,n){if(!s)return!1;const a=n==null?void 0:n.code,i=t499)}function QSe(s){return s===0&&navigator.onLine===!1}var Yh={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Qp={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class dFs extends ay{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(xt.ERROR,this.onError,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(xt.ERROR,this.onError,this),t.off(xt.ERROR,this.onErrorOut,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.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)===da.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 ir.FRAG_LOAD_ERROR:case ir.FRAG_LOAD_TIMEOUT:case ir.KEY_LOAD_ERROR:case ir.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case ir.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=FM();return}case ir.FRAG_GAP:case ir.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=Yh.SendAlternateToPenaltyBox;return}case ir.LEVEL_EMPTY_ERROR:case ir.LEVEL_PARSING_ERROR:{var l;const c=r.parent===da.MAIN?r.level:a.loadLevel;r.details===ir.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 ir.LEVEL_LOAD_ERROR:case ir.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.level));return;case ir.AUDIO_TRACK_LOAD_ERROR:case ir.AUDIO_TRACK_LOAD_TIMEOUT:case ir.SUBTITLE_LOAD_ERROR:case ir.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===io.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===io.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.loadLevel),r.errorAction.action=Yh.SendAlternateToPenaltyBox,r.errorAction.flags=Qp.MoveAllAlternatesMatchingHost;return}}return;case ir.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:Yh.SendAlternateToPenaltyBox,flags:Qp.MoveAllAlternatesMatchingHDCP};return;case ir.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ir.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ir.KEY_SYSTEM_NO_SESSION:r.errorAction={action:Yh.SendAlternateToPenaltyBox,flags:Qp.MoveAllAlternatesMatchingKey};return;case ir.BUFFER_ADD_CODEC_ERROR:case ir.REMUX_ALLOC_ERROR:case ir.BUFFER_APPEND_ERROR:if(!r.errorAction){var o;r.errorAction=this.getLevelSwitchAction(r,(o=r.level)!=null?o:a.loadLevel)}return;case ir.INTERNAL_EXCEPTION:case ir.BUFFER_APPENDING_ERROR:case ir.BUFFER_FULL_ERROR:case ir.LEVEL_SWITCH_ERROR:case ir.BUFFER_STALLED_ERROR:case ir.BUFFER_SEEK_OVER_HOLE:case ir.BUFFER_NUDGE_ON_STALL:r.errorAction=FM();return}r.type===Ma.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=FM())}getPlaylistRetryOrSwitchAction(t,r){const n=this.hls,a=YHe(n.config.playlistLoadPolicy,t),i=this.playlistError++;if(bfe(a,i,vfe(t),t.response))return{action:Yh.RetryRequest,flags:Qp.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=YHe(syt(t)?l:i,t),c=r.levels.reduce((h,m)=>h+m.fragmentError,0);if(a&&(t.details!==ir.FRAG_GAP&&a.fragmentError++,!ryt(t)&&bfe(o,c,vfe(t),t.response)))return{action:Yh.RetryRequest,flags:Qp.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===ir.BUFFER_APPEND_ERROR&&a.fragmentError++;let h=-1;const{levels:m,loadLevel:x,minAutoLevel:g,maxAutoLevel:v}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const j=(i=t.frag)==null?void 0:i.type,N=(j===da.AUDIO&&d===ir.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===ir.BUFFER_ADD_CODEC_ERROR||d===ir.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:D})=>a.audioCodec!==D),T=t.sourceBufferName==="video"&&(d===ir.BUFFER_ADD_CODEC_ERROR||d===ir.BUFFER_APPEND_ERROR)&&m.some(({codecSet:D,audioCodec:B})=>a.codecSet!==D&&a.audioCodec===B),{type:A,groupId:P}=(l=t.context)!=null?l:{};for(let D=m.length;D--;){const B=(D+x)%m.length;if(B!==x&&B>=g&&B<=v&&m[B].loadError===0){var o,c;const z=m[B];if(d===ir.FRAG_GAP&&j===da.MAIN&&t.frag){const F=m[B].details;if(F){const $=$5(t.frag,F.fragments,t.frag.start);if($!=null&&$.gap)continue}}else{if(A===io.AUDIO_TRACK&&z.hasAudioGroup(P)||A===io.SUBTITLE_TRACK&&z.hasSubtitleGroup(P))continue;if(j===da.AUDIO&&(o=a.audioGroups)!=null&&o.some(F=>z.hasAudioGroup(F))||j===da.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(F=>z.hasSubtitleGroup(F))||N&&a.audioCodec===z.audioCodec||T&&a.codecSet===z.codecSet||!N&&a.codecSet!==z.codecSet)continue}h=B;break}}if(h>-1&&n.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:Yh.SendAlternateToPenaltyBox,flags:Qp.None,nextAutoLevel:h}}return{action:Yh.SendAlternateToPenaltyBox,flags:Qp.MoveAllAlternatesMatchingHost}}onErrorOut(t,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case Yh.DoNothing:break;case Yh.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==ir.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 Qp.None:this.switchLevel(t,i);break;case Qp.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=r.levels[c],h=d==null?void 0:d.attrs["HDCP-LEVEL"];if(n.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){r.maxHdcpLevel=XSe[XSe.indexOf(h)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case Qp.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,h=d.length;for(let x=h;x--;)if(this.variantHasKey(d[x],c)){var l,o;this.log(`Banned key found in level ${x} (${d[x].bitrate}bps) or audio group "${(l=d[x].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${Xh(c.keyId||[])}`),d[x].fragmentError++,d[x].loadError++,this.log(`Removing level ${x} with key error (${t.error})`),this.hls.removeLevel(x)}const m=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===n&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(h=>{const m=!this.isTimeBuffered(h.startPTS,h.endPTS,r);return m&&this.removeFragment(c.body),m})}})}detectPartialFragments(t){const r=this.timeRanges;if(!r||t.frag.sn==="initSegment")return;const n=t.frag,a=tA(n),i=this.fragments[a];if(!i||i.buffered&&n.gap)return;const l=!n.relurl;Object.keys(r).forEach(o=>{const c=n.elementaryStreams[o];if(!c)return;const d=r[o],h=l||c.partial===!0;i.range[o]=this.getBufferedTimes(n,t.part,h,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),uq(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]=XHe(n,a=>a.fragment.sn>=t))}fragBuffered(t,r){const n=tA(t);let a=this.fragments[n];!a&&r&&(a=this.fragments[n]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,r,n,a){const i={time:[],partial:n},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let h=0;h=m&&c<=x){i.time.push({startPTS:Math.max(l,a.start(h)),endPTS:Math.min(o,a.end(h))});break}else if(lm){const g=Math.max(l,a.start(h)),v=Math.min(o,a.end(h));v>g&&(i.partial=!0,i.time.push({startPTS:g,endPTS:v}))}else if(o<=m)break}return i}getPartialFragment(t){let r=null,n,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const h=c[d];h&&uq(h)&&(a=h.body.start-o,i=h.body.end+o,t>=a&&t<=i&&(n=Math.min(t-a,i-t),l<=n&&(r=h.body,l=n)))}),r}isEndListAppended(t){const r=this.endListFragments[t];return r!==void 0&&(r.buffered||uq(r))}getState(t){const r=tA(t),n=this.fragments[r];return n?n.buffered?uq(n)?$u.PARTIAL:$u.OK:$u.APPENDING:$u.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=tA(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=tA(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=tA(t);t.clearElementaryStreamInfo();const n=this.activePartLists[t.type];if(n){const a=t.sn;this.activePartLists[t.type]=XHe(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 uq(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 tA(s){return`${s.type}_${s.level}_${s.sn}`}function XHe(s,t){return s.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var L2={cbc:0,ctr:1};class hFs{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 L2.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,t);case L2.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 mFs(s){const t=s.byteLength,r=t&&new DataView(s.buffer).getUint8(t-1);return r?s.slice(0,t-r):s}class fFs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const r=new DataView(t),n=new Uint32Array(4);for(let a=0;a<4;a++)n[a]=r.getUint32(a*4);return n}initTable(){const t=this.sBox,r=this.invSBox,n=this.subMix,a=n[0],i=n[1],l=n[2],o=n[3],c=this.invSubMix,d=c[0],h=c[1],m=c[2],x=c[3],g=new Uint32Array(256);let v=0,j=0,b=0;for(b=0;b<256;b++)b<128?g[b]=b<<1:g[b]=b<<1^283;for(b=0;b<256;b++){let N=j^j<<1^j<<2^j<<3^j<<4;N=N>>>8^N&255^99,t[v]=N,r[N]=v;const S=g[v],T=g[S],A=g[T];let P=g[N]*257^N*16843008;a[v]=P<<24|P>>>8,i[v]=P<<16|P>>>16,l[v]=P<<8|P>>>24,o[v]=P,P=A*16843009^T*65537^S*257^v*16843008,d[N]=P<<24|P>>>8,h[N]=P<<16|P>>>16,m[N]=P<<8|P>>>24,x[N]=P,v?(v=S^g[g[g[A^S]]],j^=g[g[j]]):v=j=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!==L2.cbc||r.byteLength!==16)return Ml.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Zg(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 fFs),d.expandKey(r);const h=l;return this.currentResult=d.decrypt(c.buffer,0,n),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(t,r,n,a){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,r,n,a));this.key=r,this.fastAesKey=new pFs(this.subtle,r,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new hFs(this.subtle,new Uint8Array(n),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Ml.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%gFs;return n!==t.length&&(r=t.slice(0,n),this.remainderData=t.slice(n)),r}logOnce(t){this.logEnabled&&(Ml.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const QHe=Math.pow(2,17);class yFs{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 Cb({type:Ma.NETWORK_ERROR,details:ir.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(v=>v[0]==="GAP")){c(eGe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),h=JHe(t);t.loader=d;const m=ZHe(a.fragLoadPolicy.default),x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:QHe};t.stats=d.stats;const g={onSuccess:(v,j,b,N)=>{this.resetLoader(t,d);let S=v.data;b.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),o({frag:t,part:null,payload:S,networkDetails:N})},onError:(v,j,b,N)=>{this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Cl({url:n,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:b,stats:N}))},onAbort:(v,j,b)=>{this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:b,stats:v}))},onTimeout:(v,j,b)=>{this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${x.timeout}ms`),networkDetails:b,stats:v}))}};r&&(g.onProgress=(v,j,b,N)=>r({frag:t,part:null,payload:b,networkDetails:N})),d.load(h,x,g)})}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(eGe(t,r));return}const d=this.loader=i?new i(a):new l(a),h=JHe(t,r);t.loader=d;const m=ZHe(a.fragLoadPolicy.default),x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:QHe};r.stats=d.stats,d.load(h,x,{onSuccess:(g,v,j,b)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,r);const N={frag:t,part:r,payload:g.data,networkDetails:b};n(N),o(N)},onError:(g,v,j,b)=>{this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:r,response:Cl({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:j,stats:b}))},onAbort:(g,v,j)=>{t.stats.aborted=r.stats.aborted,this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.INTERNAL_ABORTED,fatal:!1,frag:t,part:r,error:new Error("Aborted"),networkDetails:j,stats:g}))},onTimeout:(g,v,j)=>{this.resetLoader(t,d),c(new Cb({type:Ma.NETWORK_ERROR,details:ir.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:r,error:new Error(`Timeout after ${x.timeout}ms`),networkDetails:j,stats:g}))}})})}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 JHe(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(Xn(a)&&Xn(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&vFs((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 eGe(s,t){const r=new Error(`GAP ${s.gap?"tag":"attribute"} found`),n={type:Ma.MEDIA_ERROR,details:ir.FRAG_GAP,fatal:!1,frag:s,error:r,networkDetails:null};return t&&(n.part=t),(t||s).stats.aborted=!0,new Cb(n)}function vFs(s){return s==="AES-128"||s==="AES-256"}class Cb extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class nyt extends ay{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 IMe{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=hq(),this.buffering={audio:hq(),video:hq(),audiovideo:hq()},this.level=t,this.sn=r,this.id=n,this.size=a,this.part=i,this.partial=l}}function hq(){return{start:0,executeStart:0,executeEnd:0,end:0}}const tGe={length:0,start:()=>0,end:()=>0};class Ii{static isBuffered(t,r){if(t){const n=Ii.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=Ii.getBuffered(t);return Ii.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n1&&t.sort((h,m)=>h.start-m.start||m.end-h.end);let a=-1,i=[];if(n)for(let h=0;h=t[h].start&&r<=t[h].end&&(a=h);const m=i.length;if(m){const x=i[m-1].end;t[h].start-xx&&(i[m-1].end=t[h].end):i.push(t[h])}else i.push(t[h])}else i=t;let l=0,o,c=r,d=r;for(let h=0;h=m&&r<=x&&(a=h),r+n>=m&&r{const a=n.substring(2,n.length-1),i=r==null?void 0:r[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),n):i})}return t}function rGe(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 bFs(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 _Fs=/^(\d+)x(\d+)$/,nGe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class sd{constructor(t,r){typeof t=="string"&&(t=sd.parseAttrList(t,r)),Vl(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=_Fs.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(nGe.lastIndex=0;(n=nGe.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=JSe(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":Ml.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const wFs="com.apple.hls.interstitial";function jFs(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function NFs(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class iyt{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]){Ml.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Vl(new sd({}),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"]);Xn(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?(Ml.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(Xn(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===wFs}get isValid(){return!!this.id&&!this._badValueForSameId&&Xn(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 kFs=10;class SFs{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?Xn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||kFs}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 _fe(s,t){return s.length===t.length?!s.some((r,n)=>r!==t[n]):!1}function aGe(s,t){return!s&&!t?!0:!s||!t?!1:_fe(s,t)}function BM(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function PMe(s){switch(s){case"AES-128":case"AES-256":return L2.cbc;case"AES-256-CTR":return L2.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function LMe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function eCe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function CFs(s){const t=eCe(s).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function oyt(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 lyt(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=LMe(l)):r=CFs(l)}}return r}const wfe=typeof self<"u"?self:void 0;var ld={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},em={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function $de(s){switch(s){case em.FAIRPLAY:return ld.FAIRPLAY;case em.PLAYREADY:return ld.PLAYREADY;case em.WIDEVINE:return ld.WIDEVINE;case em.CLEARKEY:return ld.CLEARKEY}}function V_e(s){switch(s){case ld.FAIRPLAY:return em.FAIRPLAY;case ld.PLAYREADY:return em.PLAYREADY;case ld.WIDEVINE:return em.WIDEVINE;case ld.CLEARKEY:return em.CLEARKEY}}function MR(s){const{drmSystems:t,widevineLicenseUrl:r}=s,n=t?[ld.FAIRPLAY,ld.WIDEVINE,ld.PLAYREADY,ld.CLEARKEY].filter(a=>!!t[a]):[];return!n[ld.WIDEVINE]&&r&&n.push(ld.WIDEVINE),n}const cyt=function(s){return wfe!=null&&(s=wfe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function TFs(s,t,r,n){let a;switch(s){case ld.FAIRPLAY:a=["cenc","sinf"];break;case ld.WIDEVINE:case ld.PLAYREADY:a=["cenc"];break;case ld.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return EFs(a,t,r,n)}function EFs(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 AFs(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function dyt(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=LMe(o).subarray(0,16);return oyt(c),c}}return null}let sA={};class p2{static clearKeyUriToKeyIdMap(){sA={}}static setKeyIdForUri(t,r){sA[t]=r}static addKeyIdForUri(t){const r=Object.keys(sA).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),sA[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&&!BM(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Fgt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&_fe(t.keyFormatVersions,this.keyFormatVersions)&&aGe(t.iv,this.iv)&&aGe(t.keyId,this.keyId)}isSupported(){if(this.method){if(BM(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case em.FAIRPLAY:case em.WIDEVINE:case em.PLAYREADY:case em.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(BM(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Ml.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=IFs(t)),new p2(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=sA[this.uri];if(i&&!_fe(this.keyId,i)&&p2.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=lyt(this.uri);if(n)switch(this.keyFormat){case em.WIDEVINE:if(this.pssh=n,!this.keyId){const i=D8s(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=iGe(r));break;case em.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=L8s(i,null,n),this.keyId=dyt(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=MFs(r),i||(i=iGe(r),i||(i=sA[this.uri])),i&&(this.keyId=i,p2.setKeyIdForUri(this.uri,i))}return this}}function MFs(s){const t=s==null?void 0:s[em.WIDEVINE];return t?t.keyId:null}function iGe(s){const t=s==null?void 0:s[em.PLAYREADY];if(t){const r=lyt(t.uri);if(r)return dyt(r)}return null}function IFs(s){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=s>>8*(15-r)&255;return t}const oGe=/#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,lGe=/#EXT-X-MEDIA:(.*)/g,PFs=/^#EXT(?:INF|-X-TARGETDURATION):/m,H_e=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),LFs=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Dv{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(lGe.lastIndex=0;(a=lGe.exec(t))!==null;){const d=new sd(a[1],n),h=d.TYPE;if(h){const m=o[h],x=i[h]||[];i[h]=x;const g=d.LANGUAGE,v=d["ASSOC-LANGUAGE"],j=d.CHANNELS,b=d.CHARACTERISTICS,N=d["INSTREAM-ID"],S={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||g||"",type:h,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:g,url:d.URI?Dv.resolve(d.URI,r):""};if(v&&(S.assocLang=v),j&&(S.channels=j),b&&(S.characteristics=b),N&&(S.instreamId=N),m!=null&&m.length){const T=Dv.findGroup(m,S.groupId)||m[0];hGe(S,T,"audioCodec"),hGe(S,T,"textCodec")}x.push(S)}}return i}static parseLevelPlaylist(t,r,n,a,i,l){var o;const c={url:r},d=new SFs(r),h=d.fragments,m=[];let x=null,g=0,v=0,j=0,b=0,N=0,S=null,T=new $_e(a,c),A,P,D,B=-1,z=!1,F=null,$;if(H_e.lastIndex=0,d.m3u8=t,d.hasVariableRefs=sGe(t),((o=H_e.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=H_e.exec(t))!==null;){z&&(z=!1,T=new $_e(a,c),T.playlistOffset=j,T.setStart(j),T.sn=g,T.cc=b,N&&(T.bitrate=N),T.level=n,x&&(T.initSegment=x,x.rawProgramDateTime&&(T.rawProgramDateTime=x.rawProgramDateTime,x.rawProgramDateTime=null),F&&(T.setByteRange(F),F=null)));const Y=A[1];if(Y){T.duration=parseFloat(Y);const ne=(" "+A[2]).slice(1);T.title=ne||null,T.tagList.push(ne?["INF",Y,ne]:["INF",Y])}else if(A[3]){if(Xn(T.duration)){T.playlistOffset=j,T.setStart(j),D&&fGe(T,D,d),T.sn=g,T.level=n,T.cc=b,h.push(T);const ne=(" "+A[3]).slice(1);T.relurl=JSe(d,ne),tCe(T,S,m),S=T,j+=T.duration,g++,v=0,z=!0}}else{if(A=A[0].match(LFs),!A){Ml.warn("No matches on slow regex match for level playlist!");continue}for(P=1;P0&&pGe(d,ne,A),g=d.startSN=parseInt(de);break;case"SKIP":{d.skippedSegments&&gb(d,ne,A);const ae=new sd(de,d),ie=ae.decimalInteger("SKIPPED-SEGMENTS");if(Xn(ie)){d.skippedSegments+=ie;for(let oe=ie;oe--;)h.push(null);g+=ie}const me=ae.enumeratedString("RECENTLY-REMOVED-DATERANGES");me&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(me.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&gb(d,ne,A),d.targetduration=Math.max(parseInt(de),1);break;case"VERSION":d.version!==null&&gb(d,ne,A),d.version=parseInt(de);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||gb(d,ne,A),d.live=!1;break;case"#":(de||ce)&&T.tagList.push(ce?[de,ce]:[de]);break;case"DISCONTINUITY":b++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([ne]);break;case"BITRATE":T.tagList.push([ne,de]),N=parseInt(de)*1e3,Xn(N)?T.bitrate=N:N=0;break;case"DATERANGE":{const ae=new sd(de,d),ie=new iyt(ae,d.dateRanges[ae.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ie.isValid||d.skippedSegments?d.dateRanges[ie.id]=ie:Ml.warn(`Ignoring invalid DATERANGE tag: "${de}"`),T.tagList.push(["EXT-X-DATERANGE",de]);break}case"DEFINE":{{const ae=new sd(de,d);"IMPORT"in ae?bFs(d,ae,l):rGe(d,ae,r)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?gb(d,ne,A):h.length>0&&pGe(d,ne,A),d.startCC=b=parseInt(de);break;case"KEY":{const ae=cGe(de,r,d);if(ae.isSupported()){if(ae.method==="NONE"){D=void 0;break}D||(D={});const ie=D[ae.keyFormat];ie!=null&&ie.matches(ae)||(ie&&(D=Vl({},D)),D[ae.keyFormat]=ae)}else Ml.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${de}"`);break}case"START":d.startTimeOffset=dGe(de);break;case"MAP":{const ae=new sd(de,d);if(T.duration){const ie=new $_e(a,c);mGe(ie,ae,n,D),x=ie,T.initSegment=x,x.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=x.rawProgramDateTime)}else{const ie=T.byteRangeEndOffset;if(ie){const me=T.byteRangeStartOffset;F=`${ie-me}@${me}`}else F=null;mGe(T,ae,n,D),x=T,z=!0}x.cc=b;break}case"SERVER-CONTROL":{$&&gb(d,ne,A),$=new sd(de),d.canBlockReload=$.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=$.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&$.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=$.optionalFloat("PART-HOLD-BACK",0),d.holdBack=$.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&gb(d,ne,A);const ae=new sd(de);d.partTarget=ae.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ae=d.partList;ae||(ae=d.partList=[]);const ie=v>0?ae[ae.length-1]:void 0,me=v++,oe=new sd(de,d),ge=new b8s(oe,T,c,me,ie);ae.push(ge),T.duration+=ge.duration;break}case"PRELOAD-HINT":{const ae=new sd(de,d);d.preloadHint=ae;break}case"RENDITION-REPORT":{const ae=new sd(de,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ae);break}default:Ml.warn(`line parsed but not handled: ${A}`);break}}}S&&!S.relurl?(h.pop(),j-=S.duration,d.partList&&(d.fragmentHint=S)):d.partList&&(tCe(T,S,m),T.cc=b,d.fragmentHint=T,D&&fGe(T,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const X=h.length,K=h[0],Q=h[X-1];if(j+=d.skippedSegments*d.targetduration,j>0&&X&&Q){d.averagetargetduration=j/X;const Y=Q.sn;d.endSN=Y!=="initSegment"?Y:0,d.live||(Q.endList=!0),B>0&&(RFs(h,B),K&&m.unshift(K))}return d.fragmentHint&&(j+=d.fragmentHint.duration),d.totalduration=j,m.length&&d.dateRangeTagCount&&K&&uyt(m,d),d.endCC=b,d}}function uyt(s,t){let r=s.length;if(!r)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),r++}else return;const n=s[r-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=n.ref;for(let h=r;h--;){var l;if(((l=s[h])==null?void 0:l.sn)=o||n===0){var l;const c=(((l=r[n+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=r[n].sn-s.startSN;if(d<0)return-1;const h=s.fragments;if(h.length>r.length){const x=(r[n+1]||h[h.length-1]).sn-s.startSN;for(let g=x;g>d;g--){const v=h[g].programDateTime;if(t>=v&&tn);["video","audio","text"].forEach(n=>{const a=r.filter(i=>TMe(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 hGe(s,t,r){const n=t[r];n&&(s[r]=n)}function RFs(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 tCe(s,t,r){s.rawProgramDateTime?r.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function mGe(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 fGe(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 gb(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function pGe(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function G_e(s,t){const r=t.startPTS;if(Xn(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 hyt(s,t,r,n,a,i,l){n-r<=0&&(l.warn("Fragment should have a positive duration",t),n=r+t.duration,i=a+t.duration);let c=r,d=n;const h=t.startPTS,m=t.endPTS;if(Xn(h)){const N=Math.abs(h-r);s&&N>s.totalduration?l.warn(`media timestamps and playlist times differ by ${N}s for level ${t.level} ${s.url}`):Xn(t.deltaPTS)?t.deltaPTS=Math.max(N,t.deltaPTS):t.deltaPTS=N,c=Math.max(r,h),r=Math.min(r,h),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(n,m),n=Math.max(n,m),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const x=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=c,t.startDTS=a,t.endPTS=n,t.minEndPTS=d,t.endDTS=i;const g=t.sn;if(!s||gs.endSN)return 0;let v;const j=g-s.startSN,b=s.fragments;for(b[j]=t,v=j;v>0;v--)G_e(b[v],b[v-1]);for(v=j;v=0;h--){const m=a[h].initSegment;if(m){n=m;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;zFs(s,t,(h,m,x,g)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==h.cc){const v=h.cc-m.cc;for(let j=x;j{var m;h&&(!h.initSegment||h.initSegment.relurl===((m=n)==null?void 0:m.relurl))&&(h.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(h=>!h),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=t.skippedSegments;h--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=FFs(s.dateRanges,t,r));const h=s.fragments.filter(m=>m.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let m=1;m{m.elementaryStreams=h.elementaryStreams,m.stats=h.stats}),i?hyt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):myt(s,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const h=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=h),t.driftEndTime=d,t.driftEnd=h}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function FFs(s,t,r){const{dateRanges:n,recentlyRemovedDateranges:a}=t,i=Vl({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(n).forEach(c=>{const d=i[c],h=new iyt(n[c].attr,d);h.isValid?(i[c]=h,d||(h.tagOrder+=o)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ec(n[c].attr)}"`)}),i):n}function BFs(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 zFs(s,t,r){const n=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(n?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const h=c[l+d];let m=o[d];if(n&&!m&&h&&(m=t.fragments[d]=h),h&&m){r(h,m,d,o);const x=h.relurl,g=m.relurl;if(x&&$Fs(x,g)){t.playlistParsingError=xGe(`media sequence mismatch ${m.sn}:`,s,t,h,m);return}else if(h.cc!==m.cc){t.playlistParsingError=xGe(`discontinuity sequence mismatch (${h.cc}!=${m.cc})`,s,t,h,m);return}}}}function xGe(s,t,r,n,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function myt(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 $Fs(s,t){return s!==t&&t?yGe(s)!==yGe(t):!1}function yGe(s){return s.replace(/\?[^?]*$/,"")}function k8(s,t){for(let n=0,a=s.length;ns.startCC)}function vGe(s,t){const r=s.start+t;s.startPTS=r,s.setStart(r),s.endPTS=r+s.duration}function yyt(s,t){const r=t.fragments;for(let n=0,a=r.length;n{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:h}=this,m=c?c.currentTime:0,x=Ii.bufferInfo(d||c,m,l.maxBufferHole),g=!x.len;if(this.log(`Media seeking to ${Xn(m)?m.toFixed(3):m}, state: ${h}, ${g?"out of":"in"} buffer`),this.state===Dr.ENDED)this.resetLoadingState();else if(o){const v=l.maxFragLookUpTolerance,j=o.start-v,b=o.start+o.duration+v;if(g||bx.end){const N=m>b;(mv&&(this.lastCurrentTime=m),!this.loadingParts){const j=Math.max(x.end,m),b=this.shouldLoadParts(this.getLevelDetails(),j);b&&(this.log(`LL-Part loading ON after seeking to ${m.toFixed(2)} with buffer @${j.toFixed(2)}`),this.loadingParts=b)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${m} for seek without enough to start`),this.nextLoadPosition=m,g&&(this.startPosition=m)),g&&this.state===Dr.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=t,this.fragmentLoader=new yFs(t.config),this.keyLoader=n,this.fragmentTracker=r,this.config=t.config,this.decrypter=new MMe(t.config)}registerListeners(){const{hls:t}=this;t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(xt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Dr.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Dr.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition: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=Ii.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===Dr.FRAG_LOADING||!this.fragCurrent&&l===Dr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Dr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(xt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Dr.STOPPED||this.state===Dr.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var r;const{fragmentTracker:n}=this;if(n.getState(t)===$u.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)===$u.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(xt.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&&BM(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,PMe(o.method)).catch(d=>{throw a.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const h=self.performance.now();return a.trigger(xt.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:h}}),n.payload=d,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===Dr.STOPPED||this.state===Dr.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!==Dr.STOPPED&&(this.state=Dr.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(xt.ERROR,{type:Ma.KEY_SYSTEM_ERROR,details:ir.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?VFs.toString(Ii.getBuffered(n)):"(detached)"})`),tu(t)){var a;if(t.type!==da.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Dr.IDLE;return}}const i=(a=this.levels)==null?void 0:a[t.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=Dr.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new IMe(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=Dr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(x=>{if(!this.fragContextChanged(x.frag))return this.hls.trigger(xt.KEY_LOADED,x),this.state===Dr.KEY_LOADING&&(this.state=Dr.IDLE),x}),this.hls.trigger(xt.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(tu(t)&&(!c||t.sn!==c.sn)){const x=this.shouldLoadParts(r.details,t.end);x!==this.loadingParts&&(this.log(`LL-Part loading ${x?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=x)}if(n=Math.max(t.start,n||0),this.loadingParts&&tu(t)){const x=l.partList;if(x&&a){n>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const g=this.getNextPart(x,t,n);if(g>-1){const v=x[g];t=this.fragCurrent=v.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${v.index} (${g}/${x.length-1}) of ${this.fragInfo(t,!1,v)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=v.start+v.duration,this.state=Dr.FRAG_LOADING;let j;return o?j=o.then(b=>!b||this.fragContextChanged(b.frag)?null:this.doFragPartsLoad(t,v,r,a)).catch(b=>this.handleFragLoadError(b)):j=this.doFragPartsLoad(t,v,r,a).catch(b=>this.handleFragLoadError(b)),this.hls.trigger(xt.FRAG_LOADING,{frag:t,part:v,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):j}else if(!t.url||this.loadedEndOfParts(x,n))return Promise.resolve(null)}}if(tu(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(x=>x.loaded).map(x=>`[${x.start}-${x.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),Xn(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Dr.FRAG_LOADING;const h=this.config.progressive&&t.type!==da.SUBTITLE;let m;return h&&o?m=o.then(x=>!x||this.fragContextChanged(x.frag)?null:this.fragmentLoader.load(t,a)).catch(x=>this.handleFragLoadError(x)):m=Promise.all([this.fragmentLoader.load(t,h?a:void 0),o]).then(([x])=>(!h&&a&&a(x),x)).catch(x=>this.handleFragLoadError(x)),this.hls.trigger(xt.FRAG_LOADING,{frag:t,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m}doFragPartsLoad(t,r,n,a){return new Promise((i,l)=>{var o;const c=[],d=(o=n.details)==null?void 0:o.partList,h=m=>{this.fragmentLoader.loadPart(t,m,a).then(x=>{c[m.index]=x;const g=x.part;this.hls.trigger(xt.FRAG_LOADED,x);const v=gGe(n.details,t.sn,m.index+1)||xyt(d,t.sn,m.index+1);if(v)h(v);else return i({frag:t,part:g,partsLoaded:c})}).catch(l)};h(r)})}handleFragLoadError(t){if("data"in t){const r=t.data;r.frag&&r.details===ir.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===Ma.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(xt.ERROR,r)}else this.hls.trigger(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const r=this.getCurrentContext(t);if(!r||this.state!==Dr.PARSING){!this.fragCurrent&&this.state!==Dr.STOPPED&&this.state!==Dr.ERROR&&(this.state=Dr.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===da.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?gGe(c,i,l):null,h=d?d.fragment:pyt(c,i,n);return h?(n&&n!==h&&(h.stats=n.stats),{frag:h,part:d,level:o}):null}bufferFragmentData(t,r,n,a,i){if(this.state!==Dr.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Zg(l,o)),!c.length)return;const d=this.initPTS[r.cc],h=d?-d.baseTime/d.timescale:void 0,m={type:t.type,frag:r,part:n,chunkMeta:a,offset:h,parent:r.type,data:c};if(this.hls.trigger(xt.BUFFER_APPENDING,m),t.dropped&&t.independent&&!n){if(i)return;this.flushBufferGap(r)}}flushBufferGap(t){const r=this.media;if(!r)return;if(!Ii.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,t.start);return}const n=r.currentTime,a=Ii.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(!Xn(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=Ii.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 Ii.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=da.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=g,N=g===x?"config":"next load start"):v!==null?(b=v,N="live edge"):(b=t,N="buffer pos"),b=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(bGe(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(bGe(this.config)&&t.type!==da.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=iFs(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=tyt(t,n.cc,n.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,r,n){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=n;const{fragmentHint:c}=n,{maxFragLookUpTolerance:d}=a,h=n.partList,m=!!(this.loadingParts&&h!=null&&h.length&&c);m&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let x;if(tr-d||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:d;x=$5(i,l,t,j)}else x=l[l.length-1];if(x){const v=x.sn-n.startSN,j=this.fragmentTracker.getState(x);if((j===$u.OK||j===$u.PARTIAL&&x.gap)&&(i=x),i&&x.sn===i.sn&&(!m||h[0].fragment.sn>x.sn||!n.live)&&x.level===i.level){const N=l[v+1];x.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(t,r){this.transmuxer&&t.type===this.playlistType&&tu(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!==Dr.FRAG_LOADING_WAITING_RETRY)&&(this.state=Dr.IDLE)}onFragmentOrKeyLoadError(t,r){var n;if(r.chunkMeta&&!r.frag){const N=this.getCurrentContext(r.chunkMeta);N&&(r.frag=N.frag)}const a=r.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=r.details===ir.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=r.errorAction;if(!o){this.state=Dr.ERROR;return}const{action:c,flags:d,retryCount:h=0,retryConfig:m}=o,x=!!m,g=x&&c===Yh.RetryRequest,v=x&&!o.resolved&&d===Qp.MoveAllAlternatesMatchingHost,j=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!g&&v&&tu(a)&&!a.endList&&j&&!ryt(r))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((g||v)&&h=r||n&&!QSe(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Dr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Dr.PARSING||this.state===Dr.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===da.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Dr.STOPPED&&(this.state=Dr.IDLE)}afterBufferFlushed(t,r,n){if(!t)return;const a=Ii.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,a,n),this.state===Dr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Dr.STOPPED&&(this.state=Dr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,r=t?t.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,r,n,a){const i=n.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const h=t.elementaryStreams[d];if(h){const m=h.endPTS-h.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${m})`),c||!1;const x=a?0:hyt(i,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(xt.LEVEL_PTS_UPDATED,{details:i,level:n,drift:x,type:d,frag:t,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((n.fragmentError===0||c&&(n.fragmentError<2||t.endList))&&this.treatAsGap(t,n),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.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=Dr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)})`),this.hls.trigger(xt.FRAG_PARSED,{frag:t,part:r})}playlistLabel(){return this.playlistType===da.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 bGe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class byt{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=HFs(t,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function HFs(s,t){const r=new Uint8Array(t);let n=0;for(let a=0;a0)return s.subarray(r,r+n)}function QFs(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 g=new Error(`invalid ADTS sampling index:${l}`);s.emit(xt.ERROR,xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(i>>6&3)+1,c=t[r+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,h=a[l];let m=l;(o===5||o===29)&&(m-=3);const x=[o<<3|(m&14)>>1,(m&1)<<7|c<<3];return Ml.log(`manifest codec:${n}, parsed codec:${d}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${l})`),{config:x,samplerate:h,channelCount:c,codec:d,parsedCodec:d,manifestCodec:n}}function wyt(s,t){return s[t]===255&&(s[t+1]&246)===240}function jyt(s,t){return s[t+1]&1?7:9}function FMe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function JFs(s,t){return t+5=s.length)return!1;const n=FMe(s,t);if(n<=r)return!1;const a=t+n;return a===s.length||Nfe(s,a)}return!1}function Nyt(s,t,r,n,a){if(!s.samplerate){const i=QFs(t,r,n,a);if(!i)return;Vl(s,i)}}function kyt(s){return 1024*9e4/s}function sBs(s,t){const r=jyt(s,t);if(t+r<=s.length){const n=FMe(s,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function Syt(s,t,r,n,a){const i=kyt(s.samplerate),l=n+a*i,o=sBs(t,r);let c;if(o){const{frameLength:m,headerLength:x}=o,g=x+m,v=Math.max(0,r+g-t.length);v?(c=new Uint8Array(g-x),c.set(t.subarray(r+x,t.length),0)):c=t.subarray(r+x,r+g);const j={unit:c,pts:l};return v||s.samples.push(j),{sample:j,length:g,missing:v}}const d=t.length-r;return c=new Uint8Array(d),c.set(t.subarray(r,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function rBs(s,t){return OMe(s,t)&&iye(s,t+6)+10<=s.length-t}function nBs(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function K_e(s,t=0,r=1/0){return aBs(s,t,r,Uint8Array)}function aBs(s,t,r,n){const a=iBs(s);let i=1;"BYTES_PER_ELEMENT"in n&&(i=n.BYTES_PER_ELEMENT);const l=oBs(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(d+Math.max(r,0),o));return new n(a,d,h-d)}function iBs(s){return s instanceof ArrayBuffer?s:s.buffer}function oBs(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function lBs(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(s.size<2)return;if(s.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=s.data.subarray(1).indexOf(0);if(n===-1)return;const a=Ex(K_e(s.data,1,n)),i=s.data[2+n],l=s.data.subarray(3+n).indexOf(0);if(l===-1)return;const o=Ex(K_e(s.data,3+n,l));let c;return a==="-->"?c=Ex(K_e(s.data,4+n+l)):c=nBs(s.data.subarray(4+n+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function cBs(s){if(s.size<2)return;const t=Ex(s.data,!0),r=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:r.buffer}}function dBs(s){if(s.size<2)return;if(s.type==="TXXX"){let r=1;const n=Ex(s.data.subarray(r),!0);r+=n.length+1;const a=Ex(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=Ex(s.data.subarray(1));return{key:s.type,info:"",data:t}}function uBs(s){if(s.type==="WXXX"){if(s.size<2)return;let r=1;const n=Ex(s.data.subarray(r),!0);r+=n.length+1;const a=Ex(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=Ex(s.data);return{key:s.type,info:"",data:t}}function hBs(s){return s.type==="PRIV"?cBs(s):s.type[0]==="W"?uBs(s):s.type==="APIC"?lBs(s):dBs(s)}function mBs(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),r=iye(s,4),n=10;return{type:t,size:r,data:s.subarray(n,n+r)}}const mq=10,fBs=10;function Cyt(s){let t=0;const r=[];for(;OMe(s,t);){const n=iye(s,t+6);s[t+5]>>6&1&&(t+=mq),t+=mq;const a=t+n;for(;t+fBs0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:cx.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Xn(s))return s*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n};let fq=null;const gBs=[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],yBs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],vBs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],bBs=[0,1,1,4];function Eyt(s,t,r,n,a){if(r+24>t.length)return;const i=Ayt(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 Ayt(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=gBs[c*14+a-1]*1e3,m=yBs[(r===3?0:r===2?1:2)*3+i],x=o===3?1:2,g=vBs[r][n],v=bBs[n],j=g*8*v,b=Math.floor(g*d/m+l)*v;if(fq===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fq=T?parseInt(T[1]):0}return!!fq&&fq<=87&&n===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:m,channelCount:x,frameLength:b,samplesPerFrame:j}}}function $Me(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Myt(s,t){return t+1{let r=0,n=5;t+=n;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;n>0;){l[0]=s[t];const o=Math.min(n,8),c=8-o;i[0]=4278190080>>>24+c<>c,r=r?r<t.length||t[r]!==11||t[r+1]!==119)return-1;const i=t[r+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[r+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(r+h>t.length)return-1;const m=t[r+6]>>5;let x=0;m===2?x+=2:(m&1&&m!==1&&(x+=2),m&4&&(x+=2));const g=(t[r+6]<<8|t[r+7])>>12-x&1,j=[2,1,2,3,3,4,4,5][m]+g,b=t[r+5]>>3,N=t[r+5]&7,S=new Uint8Array([i<<6|b<<1|N>>2,(N&3)<<6|m<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,A=n+a*T,P=t.subarray(r,r+h);return s.config=S,s.channelCount=j,s.samplerate=o,s.samples.push({unit:P,pts:A}),h}class NBs extends zMe{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=fB(t,0);let n=(r==null?void 0:r.length)||0;if(r&&t[n]===11&&t[n+1]===119&&BMe(r)!==void 0&&Pyt(t,n)<=16)return!1;for(let a=t.length;n{const l=I8s(i);if(kBs.test(l.schemeIdUri)){const o=wGe(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:cx.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=wGe(l,r);n.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:cx.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 wGe(s,t){return Xn(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class CBs{constructor(t,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new MMe(r,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,L2.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 Dyt{constructor(){this.VideoSample=null}createVideoSample(t,r,n){return{key:t,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(t){var r;let n=this.VideoSample,a;if((!n||n.units.length===0)&&(n=t[t.length-1]),(r=n)!=null&&r.units){const i=n.units;a=i[i.length-1]}return a}pushAccessUnit(t,r){if(t.units.length&&t.frame){if(t.pts===void 0){const n=r.samples,a=n.length;if(a){const i=n[a-1];t.pts=i.pts,t.dts=i.dts}else{r.dropped++;return}}r.samples.push(t)}}parseNALu(t,r,n){const a=r.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,h,m,x=-1,g=0;for(i===-1&&(x=0,g=this.getNALuType(r,0),i=0,c=1);c=0){const v={data:r.subarray(x,h),type:g};o.push(v)}else{const v=this.getLastNalUnit(t.samples);v&&(l&&c<=4-l&&v.state&&(v.data=v.data.subarray(0,v.data.byteLength-l)),h>0&&(v.data=Zg(v.data,r.subarray(0,h)),v.state=0))}c=0&&i>=0){const v={data:r.subarray(x,a),type:g,state:i};o.push(v)}if(o.length===0){const v=this.getLastNalUnit(t.samples);v&&(v.data=Zg(v.data,r))}return t.naluState=i,o}}class S8{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&&Ml.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 TBs extends Dyt{parsePES(t,r,n,a){const i=this.parseNALu(t,n.data,a);let l=this.VideoSample,o,c=!1;n.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(d=>{var h,m;switch(d.type){case 1:{let j=!1;o=!0;const b=d.data;if(c&&b.length>4){const N=this.readSliceType(b);(N===2||N===4||N===7||N===9)&&(j=!0)}if(j){var x;(x=l)!=null&&x.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.frame=!0,l.key=j;break}case 5:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,CMe(d.data,1,n.pts,r.samples);break}case 7:{var g,v;o=!0,c=!0;const j=d.data,b=this.readSPS(j);if(!t.sps||t.width!==b.width||t.height!==b.height||((g=t.pixelRatio)==null?void 0:g[0])!==b.pixelRatio[0]||((v=t.pixelRatio)==null?void 0:v[1])!==b.pixelRatio[1]){t.width=b.width,t.height=b.height,t.pixelRatio=b.pixelRatio,t.sps=[j];const N=j.subarray(1,4);let S="avc1.";for(let T=0;T<3;T++){let A=N[T].toString(16);A.length<2&&(A="0"+A),S+=A}t.codec=S}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,r){return t[r]&31}readSliceType(t){const r=new S8(t);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(t,r){let n=8,a=8,i;for(let l=0;l{var h,m;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var x;(x=l)!=null&&x.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,CMe(d.data,2,n.pts,r.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Vl(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 g=this.readSPS(d.data);t.width=g.width,t.height=g.height,t.pixelRatio=g.pixelRatio,t.codec=g.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const v in g.params)t.params[v]=g.params[v]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const g=this.readPPS(d.data);for(const v in g)t.params[v]=g[v]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,r,n){(n&&n[0]===this.initVPS||!n&&!t.length)&&t.push(r)}getNALuType(t,r){return(t[r]&126)>>>1}ebsp2rbsp(t){const r=new Uint8Array(t.byteLength);let n=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(r[n]=t[a],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(t,r){super.pushAccessUnit(t,r),this.initVPS&&(this.initVPS=null)}readVPS(t){const r=new S8(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 S8(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const a=r.readBits(2),i=r.readBoolean(),l=r.readBits(5),o=r.readUByte(),c=r.readUByte(),d=r.readUByte(),h=r.readUByte(),m=r.readUByte(),x=r.readUByte(),g=r.readUByte(),v=r.readUByte(),j=r.readUByte(),b=r.readUByte(),N=r.readUByte(),S=[],T=[];for(let Re=0;Re0)for(let Re=n;Re<8;Re++)r.readBits(2);for(let Re=0;Re1&&r.readEG();for(let $t=0;$t0&<<16?(ge=it[lt-1],be=Nt[lt-1]):lt===255&&(ge=r.readBits(16),be=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),Ee=r.readBoolean(),Ee&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(Me=r.readBits(32),Pe=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const Nt=r.readBoolean(),Ft=r.readBoolean();let at=!1;(Nt||Ft)&&(at=r.readBoolean(),at&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),at&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let Ie=0;Ie<=n;Ie++){Oe=r.readBoolean();const et=Oe||r.readBoolean();let Dt=!1;et?r.readEG():Dt=r.readBoolean();const Jt=Dt?1:r.readUEG()+1;if(Nt)for(let cs=0;cs>Re&1)<<31-Re)>>>0;let ve=ct.toString(16);return l===1&&ve==="2"&&(ve="6"),{codecString:`hvc1.${Te}${l}.${ve}.${i?"H":"L"}${N}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,h],general_constraint_indicator_flags:[m,x,g,v,j,b],general_level_idc:N,bit_depth:K+8,bit_depth_luma_minus8:K,bit_depth_chroma_minus8:Q,min_spatial_segmentation_idc:oe,chroma_format_idc:A,frame_rate:{fixed:Oe,fps:Pe/Me}},width:Se,height:ze,pixelRatio:[ge,be]}}readPPS(t){const r=new S8(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 fh=188;class cj{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=cj.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(fh*5,r-fh)+1,a=0;for(;a1&&(l===0&&o>2||c+fh>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:$gt[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=cj.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=cj.createTrack("audio",a),this._id3Track=cj.createTrack("id3"),this._txtTrack=cj.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,a=!1){n||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let h=l.pid,m=l.pesData,x=o.pid,g=c.pid,v=o.pesData,j=c.pesData,b=null,N=this.pmtParsed,S=this._pmtId,T=t.length;if(this.remainderData&&(t=Zg(this.remainderData,t),T=t.length,this.remainderData=null),T>4;let X;if($>1){if(X=B+5+t[B+4],X===B+fh)continue}else X=B+4;switch(F){case h:z&&(m&&(i=rA(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(X,B+fh)),m.size+=B+fh-X);break;case x:if(z){if(v&&(i=rA(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}v={data:[],size:0}}v&&(v.data.push(t.subarray(X,B+fh)),v.size+=B+fh-X);break;case g:z&&(j&&(i=rA(j,this.logger))&&this.parseID3PES(c,i),j={data:[],size:0}),j&&(j.data.push(t.subarray(X,B+fh)),j.size+=B+fh-X);break;case 0:z&&(X+=t[X]+1),S=this._pmtId=ABs(t,X);break;case S:{z&&(X+=t[X]+1);const K=MBs(t,X,this.typeSupported,n,this.observer,this.logger);h=K.videoPid,h>0&&(l.pid=h,l.segmentCodec=K.segmentVideoCodec),x=K.audioPid,x>0&&(o.pid=x,o.segmentCodec=K.segmentAudioCodec),g=K.id3Pid,g>0&&(c.pid=g),b!==null&&!N&&(this.logger.warn(`MPEG-TS PMT found at ${B} after unknown PID '${b}'. Backtracking to sync byte @${A} to parse all TS packets.`),b=null,B=A-188),N=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=F;break}}else P++;P>0&&nCe(this.observer,new Error(`Found ${P} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=m,o.pesData=v,c.pesData=j;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=rA(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=rA(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=rA(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 CBs(this.observer,this.config,r);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new TBs:t==="hevc"&&(this.videoParser=new EBs))}decrypt(t,r){return new Promise(n=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?r.decryptAacSamples(a.samples,0,()=>{i.samples?r.decryptAvcSamples(i.samples,0,0,()=>{n(t)}):n(t)}):i.samples&&r.decryptAvcSamples(i.samples,0,0,()=>{n(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,r){let n=0;const a=this.aacOverFlow;let i=r.data;if(a){this.aacOverFlow=null;const m=a.missing,x=a.sample.unit.byteLength;if(m===-1)i=Zg(a.sample.unit,i);else{const g=x-m;a.sample.unit.set(i.subarray(0,m),g),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=Vl({},r,{type:this._videoTrack?cx.emsg:cx.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}}function rCe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function ABs(s,t){return(s[t+10]&31)<<8|s[t+11]}function MBs(s,t,r,n,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let x=t+5,g=m;for(;g>2;){switch(s[x]){case 106:r.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3");break}const j=s[x+1]+2;x+=j,g-=j}}break;case 194:case 135:return nCe(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=h,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=m+5}return l}function nCe(s,t,r,n){n.warn(`parsing error: ${t.message}`),s.emit(xt.ERROR,xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Y_e(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function rA(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]=Zg(c[0],c[1]),c.splice(1,1);if(n=c[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(a=(n[4]<<8)+n[5],a&&a>s.size-6)return null;const h=n[7];h&192&&(l=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,h&64?(o=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=n[8];let m=i+9;if(s.size<=m)return null;s.size-=m;const x=new Uint8Array(s.size);for(let g=0,v=c.length;gj){m-=j;continue}else n=n.subarray(m),j-=m,m=0;x.set(n,r),r+=j}return a&&(a-=i+3),{data:x,pts:l,dts:o,len:a}}return null}class IBs{static getSilentFrame(t,r){switch(t){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(r===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(r===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Bw=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/(Bw+1)),a=Math.floor(r%(Bw+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,h=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([h>>24,h>>16&255,h>>8&255,h&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(t){const r=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...r,6,1,2])}static audioStsd(t){const r=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(t){return 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/(Bw+1)),o=Math.floor(n%(Bw+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/(Bw+1)),l=Math.floor(r%(Bw+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,h,m,x;for(r+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,x>>>24&255,x>>>16&255,x>>>8&255,x&255],12+16*o);return nr.box(nr.types.trun,l)}static initSegment(t){nr.types||nr.init();const r=nr.moov(t);return Zg(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 v=0;v>8,n[v][j].length&255]),l),l+=2,o.set(n[v][j],l),l+=n[v][j].length}const d=nr.box(nr.types.hvcC,o),h=t.width,m=t.height,x=t.pixelRatio[0],g=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,h>>8&255,h&255,m>>8&255,m&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,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([x>>24,x>>16&255,x>>8&255,x&255,g>>24,g>>16&255,g>>8&255,g&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 Ryt=9e4;function UMe(s,t,r=1,n=!1){const a=s*t*r;return n?Math.round(a):a}function PBs(s,t,r=1,n=!1){return UMe(s,t,1/r,n)}function dR(s,t=!1){return UMe(s,1e3,1/Ryt,t)}function LBs(s,t=1){return UMe(s,Ryt,1/t)}function jGe(s){const{baseTime:t,timescale:r,trackId:n}=s;return`${t/r} (${t}/${r}) trackId: ${n}`}const DBs=10*1e3,RBs=1024,OBs=1152,FBs=1536;let nA=null,Z_e=null;function NGe(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 Ude extends ay{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,nA===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);nA=l?parseInt(l[1]):0}if(Z_e===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);Z_e=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&&jGe(r)} > ${t&&jGe(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=Jp(o,n),c=o-i),c>0?i:o},n);return r&&this.debug("PTS rollover detected"),a}remux(t,r,n,a,i,l,o,c){let d,h,m,x,g,v,j=i,b=i;const N=t.pid>-1,S=r.pid>-1,T=r.samples.length,A=t.samples.length>0,P=o&&T>0||T>1;if((!N||A)&&(!S||P)||this.ISGenerated||o){if(this.ISGenerated){var B,z,F,$;const Y=this.videoTrackConfig;(Y&&(r.width!==Y.width||r.height!==Y.height||((B=r.pixelRatio)==null?void 0:B[0])!==((z=Y.pixelRatio)==null?void 0:z[0])||((F=r.pixelRatio)==null?void 0:F[1])!==(($=Y.pixelRatio)==null?void 0:$[1]))||!Y&&P||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(t,r,i,l));const X=this.isVideoContiguous;let K=-1,Q;if(P&&(K=BBs(r.samples),!X&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,K>0){this.warn(`Dropped ${K} out of ${T} video samples due to a missing keyframe`);const Y=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(K),r.dropped+=K,b+=(r.samples[0].pts-Y)/r.inputTimeScale,Q=b}else K===-1&&(this.warn(`No keyframe found out of ${T} video samples`),v=!1);if(this.ISGenerated){if(A&&P){const Y=this.getVideoStartPts(r.samples),de=(Jp(t.samples[0].pts,Y)-Y)/r.inputTimeScale;j+=Math.max(0,de),b+=Math.max(0,-de)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(t,r,i,l)),h=this.remuxAudio(t,j,this.isAudioContiguous,l,S||P||c===da.AUDIO?b:void 0),P){const Y=h?h.endPTS-h.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(t,r,i,l)),d=this.remuxVideo(r,b,X,Y)}}else P&&(d=this.remuxVideo(r,b,X,0));d&&(d.firstKeyFrame=K,d.independent=K!==-1,d.firstKeyFramePTS=Q)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(g=Oyt(n,i,this._initPTS,this._initDTS)),a.samples.length&&(x=Fyt(a,i,this._initPTS))),{audio:h,video:d,initSegment:m,independent:v,text:x,id3:g}}computeInitPts(t,r,n,a){const i=Math.round(n*r);let l=Jp(t,i);if(l0?oe-1:oe].dts&&(S=!0)}S&&l.sort(function(oe,ge){const be=oe.dts-ge.dts,Oe=oe.pts-ge.pts;return be||Oe}),v=l[0].dts,j=l[l.length-1].dts;const A=j-v,P=A?Math.round(A/(c-1)):g||t.inputTimeScale/30;if(n){const oe=v-T,ge=oe>P,be=oe<-1;if((ge||be)&&(ge?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${dR(oe,!0)} ms (${oe}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${dR(-oe,!0)} ms (${oe}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!be||T>=l[0].pts||nA)){v=T;const Oe=l[0].pts-oe;if(ge)l[0].dts=v,l[0].pts=Oe;else{let Me=!0;for(let Pe=0;PeOe&&Me);Pe++){const Ee=l[Pe].pts;if(l[Pe].dts-=oe,l[Pe].pts-=oe,Pe0?ge.dts-l[oe-1].dts:P;if(Me=oe>0?ge.pts-l[oe-1].pts:P,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const Se=Math.floor(Ee.maxBufferHole*i),ze=(a?b+a*i:this.nextAudioTs+h)-ge.pts;ze>Se?(g=ze-$e,g<0?g=$e:K=!0,this.log(`It is approximately ${ze/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=$e}else g=$e}const Pe=Math.round(ge.pts-ge.dts);Q=Math.min(Q,g),ne=Math.max(ne,g),Y=Math.min(Y,Me),de=Math.max(de,Me),o.push(NGe(ge.key,g,Oe,Pe))}if(o.length){if(nA){if(nA<70){const oe=o[0].flags;oe.dependsOn=2,oe.isNonSync=0}}else if(Z_e&&de-Y0&&(a&&Math.abs(T-(N+S))<9e3||Math.abs(Jp(j[0].pts,T)-(N+S))<20*h),j.forEach(function(de){de.pts=Jp(de.pts,T)}),!n||N<0){const de=j.length;if(j=j.filter(ce=>ce.pts>=0),de!==j.length&&this.warn(`Removed ${j.length-de} of ${de} samples (initPTS ${S} / ${l})`),!j.length)return;i===0?N=0:a&&!v?N=Math.max(0,T-S):N=j[0].pts-S}if(t.segmentCodec==="aac"){const de=this.config.maxAudioFramesDrift;for(let ce=0,ae=N+S;ce=de*h&&ge0){B+=b;try{D=new Uint8Array(B)}catch(ge){this.observer.emit(xt.ERROR,xt.ERROR,{type:Ma.MUX_ERROR,details:ir.REMUX_ALLOC_ERROR,fatal:!1,error:ge,bytes:B,reason:`fail allocating audio mdat ${B}`});return}x||(new DataView(D.buffer).setUint32(0,B),D.set(nr.types.mdat,4))}else return;D.set(ie,b);const oe=ie.byteLength;b+=oe,g.push(NGe(!0,d,oe,0)),P=me}const F=g.length;if(!F)return;const $=g[g.length-1];N=P-S,this.nextAudioTs=N+c*$.duration;const X=x?new Uint8Array(0):nr.moof(t.sequenceNumber++,A/c,Vl({},t,{samples:g}));t.samples=[];const K=(A-S)/l,Q=this.nextAudioTs/l,ne={data1:X,data2:D,startPTS:K,endPTS:Q,startDTS:K,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,ne}}function Jp(s,t){let r;if(t===null)return s;for(t4294967296;)s+=r;return s}function BBs(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class zBs extends ay{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=Vgt(t);if(r)C8s(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=kGe(i,Gl.AUDIO,this)),l&&(a=kGe(l,Gl.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:n+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:n,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,r,n,a,i,l){var o,c;let{initPTS:d,lastEndTime:h}=this;const m={audio:void 0,video:void 0,text:a,id3:n,initSegment:void 0};Xn(h)||(h=this.lastEndTime=i||0);const x=r.samples;if(!x.length)return m;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if((o=v)!=null&&o.length||(this.generateInitSegment(x),v=this.initData),!((c=v)!=null&&c.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const j=E8s(x,v,this),b=v.audio?j[v.audio.id]:null,N=v.video?j[v.video.id]:null,S=pq(N,1/0),T=pq(b,1/0),A=pq(N,0,!0),P=pq(b,0,!0);let D=i,B=0;const z=b&&(!N||!d&&T0?this.lastEndTime=X:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K=!!v.audio,Q=!!v.video;let Y="";K&&(Y+="audio"),Q&&(Y+="video");const ne=(v.audio?v.audio.encrypted:!1)||(v.video?v.video.encrypted:!1),de={data1:x,startPTS:$,startDTS:$,endPTS:X,endDTS:X,type:Y,hasAudio:K,hasVideo:Q,nb:1,dropped:0,encrypted:ne};m.audio=K&&!Q?de:void 0,m.video=Q?de:void 0;const ce=N==null?void 0:N.sampleCount;if(ce){const ae=N.keyFrameIndex,ie=ae!==-1;de.nb=ce,de.dropped=ae===0||this.isVideoContiguous?0:ie?ae:ce,de.independent=ie,de.firstKeyFrame=ae,ie&&N.keyFrameStart&&(de.firstKeyFramePTS=(N.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(m.independent=ie),this.isVideoContiguous||(this.isVideoContiguous=ie),de.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ae}/${ce} dropped: ${de.dropped} start: ${de.firstKeyFramePTS||"NA"}`)}return m.initSegment=g,m.id3=Oyt(n,i,d,d),a.samples.length&&(m.text=Fyt(a,i,d)),m}}function pq(s,t,r=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(r?s.duration:0))/s.timescale:t}function $Bs(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 kGe(s,t,r){const n=s.codec;return n&&n.length>4?n:t===Gl.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?xfe(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 Tb;try{Tb=self.performance.now.bind(self.performance)}catch{Tb=Date.now}const qde=[{demux:SBs,remux:zBs},{demux:cj,remux:Ude},{demux:wBs,remux:Ude},{demux:NBs,remux:Ude}];qde.splice(2,0,{demux:jBs,remux:Ude});class SGe{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=Tb();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:h,trackSwitch:m,accurateTimeOffset:x,timeOffset:g,initSegmentChange:v}=a||o,{audioCodec:j,videoCodec:b,defaultInitPts:N,duration:S,initSegmentData:T}=c,A=UBs(l,r);if(A&&BM(A.method)){const z=this.getDecrypter(),F=PMe(A.method);if(z.isSync()){let $=z.softwareDecrypt(l,A.key.buffer,A.iv.buffer,F);if(n.part>-1){const K=z.flush();$=K&&K.buffer}if(!$)return i.executeEnd=Tb(),X_e(n);l=new Uint8Array($)}else return this.asyncResult=!0,this.decryptionPromise=z.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,F).then($=>{const X=this.push($,null,n);return this.decryptionPromise=null,X}),this.decryptionPromise}const P=this.needsProbing(h,m);if(P){const z=this.configureTransmuxer(l);if(z)return this.logger.warn(`[transmuxer] ${z.message}`),this.observer.emit(xt.ERROR,xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.FRAG_PARSING_ERROR,fatal:!1,error:z,reason:z.message}),i.executeEnd=Tb(),X_e(n)}(h||m||v||P)&&this.resetInitSegment(T,j,b,S,r),(h||v||P)&&this.resetInitialTimestamp(N),d||this.resetContiguity();const D=this.transmux(l,A,g,x,n);this.asyncResult=pB(D);const B=this.currentTransmuxState;return B.contiguous=!0,B.discontinuity=!1,B.trackSwitch=!1,i.executeEnd=Tb(),D}flush(t){const r=t.transmuxing;r.executeStart=Tb();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=Tb();const m=[X_e(t)];return this.asyncResult?Promise.resolve(m):m}const h=c.flush(o);return pB(h)?(this.asyncResult=!0,h.then(m=>(this.flushRemux(l,m,t),l))):(this.flushRemux(l,h,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,r,n){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=r,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===da.MAIN?"level":"track"} ${n.level}`);const h=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:h,chunkMeta:n}),n.transmuxing.executeEnd=Tb()}resetInitialTimestamp(t){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(t),n.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(t,r,n,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,r,n,a),o.resetInitSegment(t,r,n,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,r,n,a,i){let l;return r&&r.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,r,n,a,i):l=this.transmuxUnencrypted(t,n,a,i),l}transmuxUnencrypted(t,r,n,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,r,n,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,r,n,a,i){return this.demuxer.demuxSampleAes(t,r,n).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,n,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:r,observer:n,typeSupported:a}=this;let i;for(let m=0,x=qde.length;m0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(r=t),r}const X_e=s=>({remuxResult:{},chunkMeta:s});function pB(s){return"then"in s&&s.then instanceof Function}class qBs{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 VBs{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 CGe=0;class Byt{constructor(t,r,n,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=CGe++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,h=this.hls;if(!(!h||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var m;const x=(m=this.workerContext)==null?void 0:m.objectURL;x&&self.URL.revokeObjectURL(x);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{h.logger[d.data.logType]&&h.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,h.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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===xt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new RMe,this.observer.on(xt.FRAG_DECRYPTED,l),this.observer.on(xt.ERROR,l);const o=UHe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||KFs()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${r}"`),this.workerContext=ZFs(i.workerPath)):(c.log(`injecting Web Worker for "${r}"`),this.workerContext=YFs());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:r,config:ec(i)})}catch(h){c.warn(`Error setting up "${r}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new SGe(this.observer,o,i,"",r,t.logger)}return}}this.transmuxer=new SGe(this.observer,o,i,"",r,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=CGe++;const r=this.hls.config,n=UHe(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:n,id:this.id,config:ec(r)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),XFs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,r,n,a,i,l,o,c,d,h){var m,x;d.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:v}=this,j=l?l.start:i.start,b=i.decryptdata,N=this.frag,S=!(N&&i.cc===N.cc),T=!(N&&d.level===N.level),A=N?d.sn-N.sn:-1,P=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===(N==null?void 0:N.stats.chunkCount),B=!T&&(A===1||A===0&&(P===1||D&&P<=0)),z=self.performance.now();(T||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=z),l&&(P||!B)&&(l.stats.parsing.start=z);const F=!(N&&((m=i.initSegment)==null?void 0:m.url)===((x=N.initSegment)==null?void 0:x.url)),$=new VBs(S,B,c,T,j,F);if(!B||S||F){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===da.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${S} trackSwitch: ${T} contiguous: ${B} accurateTimeOffset: ${c} timeOffset: ${j} initSegmentChange: ${F}`);const X=new qBs(n,a,r,o,h);this.configureTransmuxer(X)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:t,decryptdata:b,chunkMeta:d,state:$},t instanceof ArrayBuffer?[t]:[]);else if(v){const X=v.push(t,b,d,$);pB(X)?X.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(X)}}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);pB(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(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.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 TGe=100;class HBs extends DMe{constructor(t,r,n){super(t,r,n,"audio-stream-controller",da.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(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(xt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(xt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(xt.BUFFER_RESET,this.onBufferReset,this),t.on(xt.BUFFER_CREATED,this.onBufferCreated,this),t.on(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(xt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(xt.FRAG_LOADING,this.onFragLoading,this),t.on(xt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(xt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(xt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(xt.BUFFER_RESET,this.onBufferReset,this),t.off(xt.BUFFER_CREATED,this.onBufferCreated,this),t.off(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(xt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(xt.FRAG_LOADING,this.onFragLoading,this),t.off(xt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){if(n===da.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===Dr.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===Dr.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=tyt(l,i,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===Dr.IDLE&&this.doTickIdle())}startLoad(t,r){if(!this.levels){this.startPosition=t,this.state=Dr.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(TGe),n>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n,this.state=Dr.IDLE):this.state=Dr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}doTick(){switch(this.state){case Dr.IDLE:this.doTickIdle();break;case Dr.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=Dr.WAITING_INIT_PTS}break}case Dr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Dr.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:r,part:n,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=Dr.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=Dr.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls: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=Dr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Gl.AUDIO,da.AUDIO));const h=this.getFwdBufferInfo(d,da.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){r.trigger(xt.BUFFER_EOS,{type:"audio"}),this.state=Dr.ENDED;return}const m=h.len,x=r.maxBufferLength,g=c.fragments,v=g[0].start,j=this.getLoadPosition(),b=this.flushing?j:h.end;if(this.switchingTrack&&a){const T=j;c.PTSKnown&&Tv||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=v+.05)}if(m>=x&&!this.switchingTrack&&bS.end){const A=this.fragmentTracker.getFragAtPos(b,da.MAIN);A&&A.end>S.end&&(S=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(N.start>S.end)return}this.loadFragment(N,o,b)}onMediaDetaching(t,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,r)}onAudioTracksUpdated(t,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new hB(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!==Dr.STOPPED&&(this.setInterval(TGe),this.state=Dr.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(xt.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!==Dr.STOPPED&&(this.state=Dr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const h=a[l];let m=0;if(i.live||(n=h.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(h.details){var x;m=this.alignPlaylists(i,h.details,(x=this.levelLastLoaded)==null?void 0:x.details)}i.alignedSliding||(vyt(i,d),i.alignedSliding||jfe(i,d),m=i.fragmentStart)}h.details=i,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,m),this.hls.trigger(xt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:r.groupId}),this.state===Dr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Dr.IDLE),this.tick()}_handleFragmentLoadProgress(t){var r;const n=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const h=d.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const m=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let x=this.transmuxer;x||(x=this.transmuxer=new Byt(this.hls,da.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[n.cc],v=(r=n.initSegment)==null?void 0:r.data;if(g!==void 0){const b=a?a.index:-1,N=b!==-1,S=new IMe(n.level,n.sn,n.stats.chunkCount,i.byteLength,b,N);x.push(i,v,m,"",n,a,h.totalduration,!1,S,g)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:j}=this.waitingData=this.waitingData||{frag:n,part:a,cache:new byt,complete:!1};j.push(new Uint8Array(i)),this.state!==Dr.STOPPED&&(this.state=Dr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,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===da.MAIN&&tu(r.frag)&&(this.mainFragLoading=r,this.state===Dr.IDLE&&this.tick())}onFragBuffered(t,r){const{frag:n,part:a}=r;if(n.type!==da.AUDIO){!this.audioOnly&&n.type===da.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(tu(n)){this.fragPrevious=n;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(xt.AUDIO_TRACK_SWITCHED,Cl({},i)))}this.fragBufferedComplete(n,a),this.media&&this.tick()}onError(t,r){var n;if(r.fatal){this.state=Dr.ERROR;return}switch(r.details){case ir.FRAG_GAP:case ir.FRAG_PARSING_ERROR:case ir.FRAG_DECRYPT_ERROR:case ir.FRAG_LOAD_ERROR:case ir.FRAG_LOAD_TIMEOUT:case ir.KEY_LOAD_ERROR:case ir.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(da.AUDIO,r);break;case ir.AUDIO_TRACK_LOAD_ERROR:case ir.AUDIO_TRACK_LOAD_TIMEOUT:case ir.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Dr.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===io.AUDIO_TRACK&&(this.state=Dr.IDLE);break;case ir.BUFFER_ADD_CODEC_ERROR:case ir.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case ir.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ir.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(t,{type:r}){r!==Gl.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:r}){if(r!==Gl.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Dr.ENDED&&(this.state=Dr.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,da.AUDIO),this.tick())}}_handleTransmuxComplete(t){var r;const n="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:h}=o,{details:m}=h,{audio:x,text:g,id3:v,initSegment:j}=i;if(this.fragContextChanged(c)||!m){this.fragmentTracker.removeFragment(c);return}if(this.state=Dr.PARSING,this.switchingTrack&&x&&this.completeAudioSwitch(this.switchingTrack),j!=null&&j.tracks){const b=c.initSegment||c;if(this.unhandledEncryptionError(j,c))return;this._bufferInitSegment(h,j.tracks,b,l),a.trigger(xt.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:n,tracks:j.tracks})}if(x){const{startPTS:b,endPTS:N,startDTS:S,endDTS:T}=x;d&&(d.elementaryStreams[Gl.AUDIO]={startPTS:b,endPTS:N,startDTS:S,endDTS:T}),c.setElementaryStreamInfo(Gl.AUDIO,b,N,S,T),this.bufferFragmentData(x,c,d,l)}if(v!=null&&(r=v.samples)!=null&&r.length){const b=Vl({id:n,frag:c,details:m},v);a.trigger(xt.FRAG_PARSING_METADATA,b)}if(g){const b=Vl({id:n,frag:c,details:m},g);a.trigger(xt.FRAG_PARSING_USERDATA,b)}}_bufferInitSegment(t,r,n,a){if(this.state!==Dr.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const i=r.audio;i.id=da.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(xt.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(xt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===$u.NOT_LOADED||a===$u.PARTIAL){var i;if(!tu(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=Dr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==r.details.fragmentStart&&jfe(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;l5({name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,P4)||(yfe(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(xt.AUDIO_TRACK_SWITCHED,Cl({},t))}}class qMe extends ay{constructor(t,r){super(r,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,r,n){const a=r==null?void 0:r.renditionReports;if(a){let i=-1;for(let l=0;l=0&&h>r.partTarget&&(c+=1)}const d=n&&qHe(n);return new VHe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,r){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,r){if(r)try{return r.addDirectives(t)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return t}playlistLoaded(t,r,n){const{details:a,stats:i}=r,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const h=Math.max(c||0,0);a.appliedTimelineOffset=h,a.fragments.forEach(m=>{m.setStart(m.playlistOffset+h)})}if(a.live||n!=null&&n.live){const h="levelInfo"in r?r.levelInfo:r.track;if(a.reloaded(n),n&&a.fragments.length>0){OFs(n,a,this);const S=a.playlistParsingError;if(S){this.warn(S);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=r;T.trigger(xt.ERROR,{type:Ma.NETWORK_ERROR,details:ir.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:S,reason:S.message,level:r.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:A,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const m=this.hls.mainForwardBufferInfo,x=m?m.end-m.len:0,g=(a.edge-x)*1e3,v=fyt(a,g);if(a.requestScheduled+v0){if(F>a.targetduration*3)this.log(`Playlist last advanced ${z.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,N=void 0;else if(n!=null&&n.tuneInGoal&&F-a.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${$} with playlist age: ${a.age}`),$=0;else{const X=Math.floor($/a.targetduration);if(b+=X,N!==void 0){const K=Math.round($%a.targetduration/a.partTarget);N+=K}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${z.toFixed(2)}s goal: ${$} skip sn ${X} to part ${N}`)}a.tuneInGoal=$}if(j=this.getDeliveryDirectives(a,r.deliveryDirectives,b,N),S||!B){a.requestScheduled=l,this.loadingPlaylist(h,j);return}}else(a.canBlockReload||a.canSkipUntil)&&(j=this.getDeliveryDirectives(a,r.deliveryDirectives,b,N));j&&b!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(v-o*2,v/2)),this.scheduleLoading(h,j,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=qHe(t);return r!=null&&r.skip&&t.deltaUpdateFailed&&(n=r.msn,a=r.part,i=zde.No),new VHe(n,a,i)}checkRetry(t){const r=t.details,n=vfe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===Yh.RetryRequest||!a.resolved&&i===Yh.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(n&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const h=AMe(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" in ${h}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function zyt(s,t){if(s.length!==t.length)return!1;for(let r=0;rs[a]!==t[a])}function aCe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class GBs extends qMe{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(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.LEVEL_LOADING,this.onLevelLoading,this),t.on(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(xt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.LEVEL_LOADING,this.onLevelLoading,this),t.off(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(xt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(xt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Audio track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Audio track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(x=>!n||n.indexOf(x.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(x=>x.default)&&(this.selectDefaultTrack=!1),o.forEach((x,g)=>{x.id=g});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const x=Lv(c,o,P4);if(x>-1)i=o[x];else{const g=Lv(c,this.tracks);i=this.tracks[g]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(xt.AUDIO_TRACKS_UPDATED,h);const m=this.trackId;if(d!==-1&&m===-1)this.setAudioTrack(d);else if(o.length&&m===-1){var l;const x=new Error(`No audio track selected for current audio group-ID(s): ${(l=this.groupIds)==null?void 0:l.join(",")} track count: ${o.length}`);this.warn(x.message),this.hls.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:x})}}}onError(t,r){r.fatal||!r.context||r.context.type===io.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&&l5(t,a,P4))return a;const i=Lv(t,this.tracksInGroup,P4);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=nFs(t,r.levels,n,l,P4);if(o===-1)return null;r.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=Lv(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(xt.AUDIO_TRACK_SWITCHING,Cl({},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 EGe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,$yt="HlsJsTrackRemovedError";class KBs extends Error{constructor(t){super(t),this.name=$yt}}class YBs extends ay{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(xt.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=g8s(P2(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(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.BUFFER_RESET,this.onBufferReset,this),t.on(xt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(xt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(xt.BUFFER_EOS,this.onBufferEos,this),t.on(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(xt.FRAG_PARSED,this.onFragParsed,this),t.on(xt.FRAG_CHANGED,this.onFragChanged,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.BUFFER_RESET,this.onBufferReset,this),t.off(xt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(xt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(xt.BUFFER_EOS,this.onBufferEos,this),t.off(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(xt.FRAG_PARSED,this.onFragParsed,this),t.off(xt.FRAG_CHANGED,this.onFragChanged,this),t.off(xt.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?Vl(n,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(n[l]=Vl({},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=P2(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,AGe(n),ZBs(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: ${ec(n,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${ec(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!Ogt(a,n)){r.mediaSource=null,r.tracks=void 0;const c=t.currentTime,d=this.details,h=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(n)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(xt.MEDIA_DETACHING,{}),this.onMediaAttaching(xt.MEDIA_ATTACHING,r),t.currentTime=h;return}this.transferData=void 0,i.forEach(c=>{const d=c,h=a[d];if(h){const m=h.buffer;if(m){const x=this.fragmentTracker,g=h.id;if(x.hasFragments(g)||x.hasParts(g)){const b=Ii.getBuffered(m);x.detectEvictedFragments(d,b,g,null,!0)}const v=Q_e(d),j=[d,m];this.sourceBuffers[v]=j,m.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const r=(t=this.mediaSource)==null?void 0:t.readyState;return r==="open"||r==="ended"}onMediaDetaching(t,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),n||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&AGe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(xt.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[Q_e(t)]=[null,null];const r=this.tracks[t];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new WBs(this.tracks)}onBufferCodecs(t,r){var n;const a=this.tracks,i=Object.keys(r);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in r&&(a.audio||a.video)||a.audiovideo&&("audio"in r||"video"in r),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,h;const m=r[c],{id:x,codec:g,levelCodec:v,container:j,metadata:b,supplemental:N}=m;let S=a[c];const T=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=T!=null&&T.buffer?T:S,P=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),D=A==null?void 0:A.levelCodec;S||(S=a[c]={buffer:void 0,listeners:[],codec:g,supplemental:N,container:j,levelCodec:v,metadata:b,id:x});const B=Bde(P,D),z=B==null?void 0:B.replace(EGe,"$1");let F=Bde(g,v);const $=(h=F)==null?void 0:h.replace(EGe,"$1");F&&B&&z!==$&&(c.slice(0,5)==="audio"&&(F=xfe(F,this.appendSource)),this.log(`switching codec ${P} to ${F}`),F!==(S.pendingCodec||S.codec)&&(S.pendingCodec=F),S.container=j,this.appendChangeType(c,j,F))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,r)=>{const n=this.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}appendChangeType(t,r,n){const a=`${r};codecs=${n}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=n,l.container=r)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var r;const n=t.start,a=n+t.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,da.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&&Ii.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,da.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:r}=this;t&&r&&(this.blockedAudioAppend=null,r.unblockAudio(t.op))}onBufferAppending(t,r){const{tracks:n}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:h}=r,m=d.buffering[i],{sn:x,cc:g}=o,v=self.performance.now();m.start=v;const j=o.stats.buffering,b=c?c.stats.buffering:null;j.start===0&&(j.start=v),b&&b.start===0&&(b.start=v);const N=n.audio;let S=!1;i==="audio"&&(N==null?void 0:N.container)==="audio/mpeg"&&(S=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const T=n.video,A=T==null?void 0:T.buffer;if(A&&x!=="initSegment"){const B=c||o,z=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const $=B.start+B.duration*.05,X=A.buffered,K=this.currentOp("video");!X.length&&!K?this.blockAudio(B):!K&&!Ii.isBuffered(A,$)&&this.lastVideoAppendEnd<$&&this.blockAudio(B)}else if(i==="video"){const F=B.end;if(z){const $=z.frag.start;(F>$||F{var B;m.executeStart=self.performance.now();const z=(B=this.tracks[i])==null?void 0:B.buffer;z&&(S?this.updateTimestampOffset(z,P,.1,i,x,g):h!==void 0&&Xn(h)&&this.updateTimestampOffset(z,h,1e-6,i,x,g)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const B=self.performance.now();m.executeEnd=m.end=B,j.first===0&&(j.first=B),b&&b.first===0&&(b.first=B);const z={};this.sourceBuffers.forEach(([F,$])=>{F&&(z[F]=Ii.getBuffered($))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(xt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:z})},onError:B=>{var z;const F={type:Ma.MEDIA_ERROR,parent:o.type,details:ir.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:B,err:B,fatal:!1},$=(z=this.media)==null?void 0:z.error;if(B.code===DOMException.QUOTA_EXCEEDED_ERR||B.name=="QuotaExceededError"||"quota"in B)F.details=ir.BUFFER_FULL_ERROR;else if(B.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!$)F.errorAction=FM(!0);else if(B.name===$yt&&this.sourceBufferCount===0)F.errorAction=FM(!0);else{const X=++this.appendErrors[i];this.warn(`Failed ${X}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${$||"no media error"})`),(X>=this.hls.config.appendErrorMaxRetry||$)&&(F.fatal=!0)}this.hls.trigger(xt.ERROR,F)}};this.log(`queuing "${i}" append sn: ${x}${c?" p: "+c.index:""} of ${o.type===da.MAIN?"level":"track"} ${o.level} cc: ${g}`),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(xt.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[Gl.AUDIOVIDEO]?i.push("audiovideo"):(l[Gl.AUDIO]&&i.push("audio"),l[Gl.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(xt.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(xt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(xt.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===ir.BUFFER_APPEND_ERROR&&r.frag){var n;const a=(n=r.errorAction)==null?void 0:n.nextAutoLevel;Xn(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(Xn(o)&&o>=0){const d=Math.max(o,l),h=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,h)}const c=a.frontBufferFlushThreshold;if(Xn(c)&&c>0){const d=Math.max(a.maxBufferLength,c),h=Math.max(d,l),m=Math.floor(i/l)*l+h;this.flushFrontBuffer(i,l,m)}}flushBackBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=Ii.getBuffered(i);if(o.length>0&&n>o.start(0)){var l;this.hls.trigger(xt.BACK_BUFFER_REACHED,{bufferEnd:n});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(xt.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(xt.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:a})}}})}flushFrontBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=Ii.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(xt.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const a=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const d=Math.max(0,r.fragmentStart),h=Math.max(d,a);return{duration:1/0,start:d,end:h}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return Xn(i)?{duration:i}:null;const l=this.media.duration,o=Xn(n.duration)?n.duration:0;return a>o&&a>l||!Xn(l)?{duration:a}:null}updateMediaSource({duration:t,start:r,end:n}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Xn(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}) ${ec(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(xt.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(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.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":""} ${ec(o)}`);try{const h=n.addSourceBuffer(d),m=Q_e(l),x=[l,h];r[m]=x,o.buffer=h}catch(h){var a;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,r){const n=t.supplemental;let a=t.codec;n&&(r==="video"||r==="audiovideo")&&dB(n,"video")&&(a=B8s(a,n));const i=Bde(a,t.levelCodec);return i?r.slice(0,5)==="audio"?xfe(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(xt.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(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.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=Xn(a.duration)?a.duration:1/0,d=Xn(i.duration)?i.duration:1/0,h=Math.max(0,r),m=Math.min(n,c,d);m>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${m}] from the ${t} SourceBuffer`),o.remove(h,m)):this.shiftAndExecuteNext(t)}appendExecutor(t,r){const n=this.tracks[r],a=n==null?void 0:n.buffer;if(!a)throw new KBs(`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 AGe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(r=>{s.removeChild(r)})}function ZBs(s,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,s.appendChild(r)}function Q_e(s){return s==="audio"?1:0}class VMe{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(xt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(xt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(xt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(xt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(xt.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&&Xn(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,VMe.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 XBs={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Jf=XBs,QBs={HLS:"h"},JBs=QBs;class m1{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof m1?n:new m1(n))),this.value=t,this.params=r}}const ezs="Dict";function tzs(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 szs(s,t,r,n){return new Error(`failed to ${s} "${tzs(t)}" as ${r}`,{cause:n})}function f1(s,t,r){return szs("serialize",s,t,r)}class Uyt{constructor(t){this.description=t}}const MGe="Bare Item",rzs="Boolean";function nzs(s){if(typeof s!="boolean")throw f1(s,rzs);return s?"?1":"?0"}function azs(s){return btoa(String.fromCharCode(...s))}const izs="Byte Sequence";function ozs(s){if(ArrayBuffer.isView(s)===!1)throw f1(s,izs);return`:${azs(s)}:`}const lzs="Integer";function czs(s){return s<-999999999999999||99999999999999912)throw f1(s,uzs);const r=t.toString();return r.includes(".")?r:`${r}.0`}const mzs="String",fzs=/[\x00-\x1f\x7f]+/;function pzs(s){if(fzs.test(s))throw f1(s,mzs);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function xzs(s){return s.description||s.toString().slice(7,-1)}const gzs="Token";function IGe(s){const t=xzs(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw f1(t,gzs);return t}function iCe(s){switch(typeof s){case"number":if(!Xn(s))throw f1(s,MGe);return Number.isInteger(s)?qyt(s):hzs(s);case"string":return pzs(s);case"symbol":return IGe(s);case"boolean":return nzs(s);case"object":if(s instanceof Date)return dzs(s);if(s instanceof Uint8Array)return ozs(s);if(s instanceof Uyt)return IGe(s);default:throw f1(s,MGe)}}const yzs="Key";function oCe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw f1(s,yzs);return s}function HMe(s){return s==null?"":Object.entries(s).map(([t,r])=>r===!0?`;${oCe(t)}`:`;${oCe(t)}=${iCe(r)}`).join("")}function Hyt(s){return s instanceof m1?`${iCe(s.value)}${HMe(s.params)}`:iCe(s)}function vzs(s){return`(${s.value.map(Hyt).join(" ")})${HMe(s.params)}`}function bzs(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw f1(s,ezs);const r=s instanceof Map?s.entries():Object.entries(s),n=t!=null&&t.whitespace?" ":"";return Array.from(r).map(([a,i])=>{i instanceof m1||(i=new m1(i));let l=oCe(a);return i.value===!0?l+=HMe(i.params):(l+="=",Array.isArray(i.value)?l+=vzs(i):l+=Hyt(i)),l}).join(`,${n}`)}function Gyt(s,t){return bzs(s,t)}const av="CMCD-Object",kd="CMCD-Request",mk="CMCD-Session",zw="CMCD-Status",_zs={br:av,ab:av,d:av,ot:av,tb:av,tpb:av,lb:av,tab:av,lab:av,url:av,pb:kd,bl:kd,tbl:kd,dl:kd,ltc:kd,mtp:kd,nor:kd,nrr:kd,rc:kd,sn:kd,sta:kd,su:kd,ttfb:kd,ttfbb:kd,ttlb:kd,cmsdd:kd,cmsds:kd,smrt:kd,df:kd,cs:kd,ts:kd,cid:mk,pr:mk,sf:mk,sid:mk,st:mk,v:mk,msd:mk,bs:zw,bsd:zw,cdn:zw,rtp:zw,bg:zw,pt:zw,ec:zw,e:zw},wzs={REQUEST:kd};function jzs(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 Nzs(s,t){const r={};if(!s)return r;const n=Object.keys(s),a=t?jzs(t):{};return n.reduce((i,l)=>{var o;const c=_zs[l]||a[l]||wzs.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},r)}function kzs(s){return["ot","sf","st","e","sta"].includes(s)}function Szs(s){return typeof s=="number"?Xn(s):s!=null&&s!==""&&s!==!1}const Wyt="event";function Czs(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 Vde=s=>Math.round(s),lCe=(s,t)=>Array.isArray(s)?s.map(r=>lCe(r,t)):s instanceof m1&&typeof s.value=="string"?new m1(lCe(s.value,t),s.params):(t.baseUrl&&(s=Czs(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),xq=s=>Vde(s/100)*100,Tzs=(s,t)=>{let r=s;return t.version>=2&&(s instanceof m1&&typeof s.value=="string"?r=new m1([s]):typeof s=="string"&&(r=[s])),lCe(r,t)},Ezs={br:Vde,d:Vde,bl:xq,dl:xq,mtp:xq,nor:Tzs,rtp:xq,tb:Vde},Kyt="request",Yyt="response",GMe=["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"],Azs=["e"],Mzs=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function oye(s){return Mzs.test(s)}function Izs(s){return GMe.includes(s)||Azs.includes(s)||oye(s)}const Zyt=["d","dl","nor","ot","rtp","su"];function Pzs(s){return GMe.includes(s)||Zyt.includes(s)||oye(s)}const Lzs=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Dzs(s){return GMe.includes(s)||Zyt.includes(s)||Lzs.includes(s)||oye(s)}const Rzs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ozs(s){return Rzs.includes(s)||oye(s)}const Fzs={[Yyt]:Dzs,[Wyt]:Izs,[Kyt]:Pzs};function Xyt(s,t={}){const r={};if(s==null||typeof s!="object")return r;const n=t.version||s.v||1,a=t.reportingMode||Kyt,i=n===1?Ozs:Fzs[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Yyt||a===Wyt;c&&!l.includes("ts")&&l.push("ts"),n>1&&!l.includes("v")&&l.push("v");const d=Vl({},Ezs,t.formatters),h={version:n,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(m=>{let x=s[m];const g=d[m];if(typeof g=="function"&&(x=g(x,h)),m==="v"){if(n===1)return;x=n}m=="pr"&&x===1||(c&&m==="ts"&&!Xn(x)&&(x=Date.now()),Szs(x)&&(kzs(m)&&typeof x=="string"&&(x=new Uyt(x)),r[m]=x))}),r}function Bzs(s,t={}){const r={};if(!s)return r;const n=Xyt(s,t),a=Nzs(n,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Gyt(o,{whitespace:!1});return c&&(i[l]=c),i},r)}function zzs(s,t,r){return Vl(s,Bzs(t,r))}const $zs="CMCD";function Uzs(s,t={}){return s?Gyt(Xyt(s,t),{whitespace:!1}):""}function qzs(s,t={}){if(!s)return"";const r=Uzs(s,t);return encodeURIComponent(r)}function Vzs(s,t={}){if(!s)return"";const r=qzs(s,t);return`${$zs}=${r}`}const PGe=/CMCD=[^&#]+/;function Hzs(s,t,r){const n=Vzs(t,r);if(!n)return s;if(PGe.test(s))return s.replace(PGe,n);const a=s.includes("?")?"&":"?";return`${s}${a}${n}`}class Gzs{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:Jf.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===Jf.VIDEO||c===Jf.AUDIO||c==Jf.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const h=l?this.getNextPart(l):this.getNextFrag(i);h!=null&&h.url&&h.url!==i.url&&(d.nor=h.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const r=this.config=t.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(xt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(xt.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:JBs.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,r={}){Vl(r,this.createData());const n=r.ot===Jf.INIT||r.ot===Jf.VIDEO||r.ot===Jf.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={}),zzs(t.headers,r,i)):t.url=Hzs(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 Jf.TIMED_TEXT;if(t.sn==="initSegment")return Jf.INIT;if(r==="audio")return Jf.AUDIO;if(r==="main")return this.hls.audioTracks.length?Jf.VIDEO:Jf.MUXED}getTopBandwidth(t){let r=0,n;const a=this.hls;if(t===Jf.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===Jf.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:Ii.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 Wzs=3e5;class Kzs extends ay{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(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.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)===Yh.SendAlternateToPenaltyBox&&n.flags===Qp.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===ir.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: ${ec(i)} penalized: ${ec(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]>Wzs&&delete n[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,gyt(r),this.hls.trigger(xt.LEVELS_UPDATED,{levels:r});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,r,n){const a=this.getLevelsForPathway(n).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(r.some(h=>h.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(h=>{const m=new sd(h.attrs);m["PATHWAY-ID"]=l;const x=m.AUDIO&&`${m.AUDIO}_clone_${l}`,g=m.SUBTITLES&&`${m.SUBTITLES}_clone_${l}`;x&&(n[m.AUDIO]=x,m.AUDIO=x),g&&(a[m.SUBTITLES]=g,m.SUBTITLES=g);const v=Qyt(h.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),j=new hB({attrs:m,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:v,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let b=1;b{this.log(`Loaded steering manifest: "${a}"`);const v=h.data;if((v==null?void 0:v.VERSION)!==1){this.log(`Steering VERSION ${v.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=v.TTL;const{"RELOAD-URI":j,"PATHWAY-CLONES":b,"PATHWAY-PRIORITY":N}=v;if(j)try{this.uri=new self.URL(j,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${j}`);return}this.scheduleRefresh(this.uri||x.url),b&&this.clonePathways(b);const S={steeringManifest:v,url:a.toString()};this.hls.trigger(xt.STEERING_MANIFEST_LOADED,S),N&&this.updatePathwayPriority(N)},onError:(h,m,x,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${m.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${m.url} no longer available`);return}let v=this.timeToLoad*1e3;if(h.code===429){const j=this.loader;if(typeof(j==null?void 0:j.getResponseHeader)=="function"){const b=j.getResponseHeader("Retry-After");b&&(v=parseFloat(b)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,v)},onTimeout:(h,m,x)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const a=(n=this.hls)==null?void 0:n.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},r)}}function LGe(s,t,r,n){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Vl({},l);return o.details=void 0,o.attrs=new sd(o.attrs),o.url=o.attrs.URI=Qyt(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 Qyt(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 zM extends ay{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=zM.CDMCleanupPromise?[zM.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=MR(this.config));const o=l.map(V_e).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=$de(l);if(n!=="sinf"||o!==ld.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${o}`);return}let c;try{const g=Fu(new Uint8Array(a)),v=LMe(JSON.parse(g).sinf),j=Ggt(v);if(!j)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(j.subarray(8,24))}catch(g){this.warn(`${i} Failed to parse sinf: ${g}`);return}const d=Xh(c),{keyIdToKeySessionPromise:h,mediaKeySessions:m}=this;let x=h[d];for(let g=0;gthis.generateRequestWithPreferredKeySession(v,n,a,"encrypted-event-key-match")),x.catch(N=>this.handleError(N));break}}x||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(xt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(xt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(xt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(xt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(xt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(xt.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===ld.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r==null?void 0:r[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(l,o,c)=>!!l&&c.indexOf(l)===o,a=r.map(l=>l.audioCodec).filter(n),i=r.map(l=>l.videoCodec).filter(n);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const h=d.shift();this.getMediaKeysPromise(h,a,i).then(m=>l({keySystem:h,mediaKeys:m})).catch(m=>{d.length?c(d):m instanceof Yp?o(m):o(new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.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 cyt===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=TFs(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: ${ec(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const h=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const m=c.mediaKeys=d.createMediaKeys().then(x=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,h.then(g=>g?this.setMediaKeysServerCertificate(x,t,g):x)));return m.catch(x=>{this.error(`Failed to create media-keys for "${t}"}: ${x}`)}),m})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Xh(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=gq(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 ${Xh(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})=>V_e(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=V_e(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=MR(this.config),n=t.map($de).filter(a=>!!a&&r.indexOf(a)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:r}))))).then(c=>{const d="cenc",h=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,h,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[n]=o,o}return l.catch(o=>{if(o instanceof Yp){const c=Cl({},o.data);this.getKeyStatus(r)==="internal-error"&&(c.decryptdata=r);const d=new Yp(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 Yp){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${Xh(n.keyId||[])})`:""}`),this.hls.trigger(xt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(xt.ERROR,{type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=gq(t),n=this.keyIdToKeySessionPromise[r];if(!n){const a=$de(t.keyFormat),i=a?[a]:MR(this.config);return this.attemptKeySystemAccess(i)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=MR(this.config)),t.length===0)throw new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ec({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(i).catch(l)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>n.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,r,n,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const v=l.call(this.hls,r,n,t);if(!v)throw new Error("Invalid response from configured generateRequest filter");r=v.initDataType,n=v.initData?v.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(v){if(this.warn(v.message),this.hls&&this.hls.config.debug)throw v}if(n===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=gq(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 RMe,h=t._onmessage=v=>{const j=t.mediaKeysSession;if(!j){d.emit("error",new Error("invalid state"));return}const{messageType:b,message:N}=v;this.log(`"${b}" message event for session "${j.sessionId}" message size: ${N.byteLength}`),b==="license-request"||b==="license-renewal"?this.renewLicense(t,N).catch(S=>{d.eventNames().length?d.emit("error",S):this.handleError(S)}):b==="license-release"?t.keySystem===ld.FAIRPLAY&&this.updateKeySession(t,eCe("acknowledged")).then(()=>this.removeSession(t)).catch(S=>this.handleError(S)):this.warn(`unhandled media key message type "${b}"`)},m=(v,j)=>{j.keyStatus=v;let b;v.startsWith("usable")?d.emit("resolved"):v==="internal-error"||v==="output-restricted"||v==="output-downscaled"?b=DGe(v,j.decryptdata):v==="expired"?b=new Error(`key expired (keyId: ${o})`):v==="released"?b=new Error("key released"):v==="status-pending"||this.warn(`unhandled key status change "${v}" (keyId: ${o})`),b&&(d.eventNames().length?d.emit("error",b):this.handleError(b))},x=t._onkeystatuseschange=v=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const b=this.getKeyStatuses(t);if(!Object.keys(b).some(A=>b[A]!=="status-pending"))return;if(b[o]==="expired"){this.log(`Expired key ${ec(b)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let S=b[o];if(S)m(S,t);else{var T;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(T=t.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const P=this.getKeyStatus(t.decryptdata);if(P&&P!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${P} from other session.`),m(P,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),S="internal-error",m(S,t)},1e3)),this.log(`No status for keyId ${o} (${ec(b)}).`)}};Nf(t.mediaKeysSession,"message",h),Nf(t.mediaKeysSession,"keystatuseschange",x);const g=new Promise((v,j)=>{d.on("error",j),d.on("resolved",v)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(v=>{throw new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_NO_SESSION,error:v,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${v}`)}).then(()=>g).catch(v=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw v}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,a)=>{if(typeof a=="string"&&typeof n=="object"){const o=a;a=n,n=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===ld.PLAYREADY&&i.length===16){const o=Xh(i);r[o]=n,oyt(i)}const l=Xh(i);n==="internal-error"&&(this.bannedKeyIds[l]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),r[l]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,a=new n(r),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=r.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(x,g,v,j)=>{l(x.data)},onError:(x,g,v,j)=>{o(new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:Cl({url:c.url,data:void 0},x)},`"${t}" certificate request failed (${i}). Status: ${x.code} (${x.text})`))},onTimeout:(x,g,v)=>{o(new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(x,g,v)=>{o(new Error("aborted"))}};a.load(c,h,m)})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((a,i)=>{t.setServerCertificate(n).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),a(t)}).catch(l=>{i(new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.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 Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const a=new DOMParser().parseFromString(n,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let h;for(let m=0,x=i.length;m in key message");return eCe(atob(d))}setupLicenseXHR(t,r,n,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,r,n,a)}).catch(l=>{if(!n.decryptdata)throw l;return t.open("POST",r,!0),i.call(this.hls,t,r,n,a)}).then(l=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,r){const n=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(h){this.error(h)}a(c)}else{const c=n.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new Yp({type:Ma.KEY_SYSTEM_ERROR,details:ir.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:l,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${l}). Status: ${o.status} (${o.statusText})`));else{const h=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,r).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,r).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==ld.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,Nf(n,"encrypted",this.onMediaEncrypted),Nf(n,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&(dp(t,"encrypted",this.onMediaEncrypted),dp(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,p2.clearKeyUriToKeyIdMap();const i=a.length;zM.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(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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: ${Xh((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(AFs(o)?new Promise((d,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(d).catch(h)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}zM.CDMCleanupPromise=void 0;function gq(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Xh(s.keyId)}function Yzs(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 Yp 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 DGe(s,t){const r=s==="output-restricted",n=r?ir.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ir.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Yp({type:Ma.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${s}"`)}class Zzs{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(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(xt.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(xt.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:n}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let h=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=h)&&(h=h-1,d.trigger(xt.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const r=t.getVideoPlaybackQuality();this.checkFPS(t,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function Jyt(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 e0t(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){Ml.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){Ml.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}r==="disabled"&&(s.mode=r)}function UA(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 cCe(s,t,r,n){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=Qzs(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 Hde(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=Hde(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.LEVEL_LOADING,this.onLevelLoading,this),t.on(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(xt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(xt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.LEVEL_LOADING,this.onLevelLoading,this),t.off(xt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(xt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(xt.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;Hde(n.textTracks).forEach(l=>{UA(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Subtitle track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(h=>!n||n.indexOf(h.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(h=>h.default)&&(this.selectDefaultTrack=!1),l.forEach((h,m)=>{h.id=m});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const h=Lv(o,l);if(h>-1)i=l[h];else{const m=Lv(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(xt.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=Lv(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(xt.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:a,deliveryDirectives:r||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const r=Hde(t.textTracks),n=this.currentTrack;let a;if(n&&(a=r.filter(i=>aCe(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||!Xn(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(xt.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===n&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:h}=a;this.hls.trigger(xt.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:h});const m=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(m)}}function e7s(){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 C8(s){let t=5381,r=s.length;for(;r;)t=t*33^s.charCodeAt(--r);return(t>>>0).toString()}const $M=.025;let kfe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function t7s(s,t,r){return`${s.identifier}-${r+1}-${C8(t)}`}class s7s{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 J_e(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=J_e(r,t);return r-n<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,r=Xn(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 J_e(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)<$M))}set appendInPlace(t){if(this.appendInPlaceStarted){this.resetOnResume=!t;return}this.appendInPlaceDisabled=!t}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let r;return this._duration!==null?r=this._duration:this.dateRange.duration?r=this.dateRange.duration:r=this.dateRange.plannedDuration||0,!isNaN(t)&&t0||this.assetListResponse!==null}toString(){return r7s(this)}}function J_e(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function pA(s){const t=s.timelineStart,r=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class n7s{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(xt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(r);this.interstitial=n,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(xt.LEVEL_LOADED,l),i.once(xt.AUDIO_TRACK_LOADED,l),i.once(xt.SUBTITLE_TRACK_LOADED,l),i.on(xt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(xt.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,i.trigger(xt.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=t0t(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=Ii.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=Ii.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: ${pA(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const RGe=.033;class a7s extends ay{constructor(t,r){super("interstitials-sched",r),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,r){return this.events?this.events.reduce((n,a)=>t<=a.startOffset&&r>a.startOffset?(delete a.error,n+1):n,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,r){if(t.event)return this.findEventIndex(t.event.identifier);let n=-1;t.nextEvent?n=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(n=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[n]||(r===void 0&&(r=t.start),n=this.findItemIndexAtTime(r));n>=0&&(i=a[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(t,r){const n=this.items;if(n)for(let a=0;ai.start&&t1)for(let i=0;io&&(r!o.includes(d.identifier)):[];l.length&&l.sort((d,h)=>{const m=d.cue.pre,x=d.cue.post,g=h.cue.pre,v=h.cue.post;if(m&&!g)return-1;if(g&&!m||x&&!v)return 1;if(v&&!x)return-1;if(!m&&!g&&!x&&!v){const j=d.startTime,b=h.startTime;if(j!==b)return j-b}return d.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,r=[],n=!1){const a=this.events||[];if(a.length||r.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(n||r.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(r,i))}}parseDateRanges(t,r,n){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,r);let c=0,d=0;if(t.forEach((h,m)=>{const x=h.cue.pre,g=h.cue.post,v=t[m-1]||null,j=h.appendInPlace,b=g?i:h.startOffset,N=h.duration,S=h.timelineOccupancy===kfe.Range?N:0,T=h.resumptionOffset,A=(v==null?void 0:v.startTime)===b,P=b+h.cumulativeDuration;let D=j?P+N:b+T;if(x||!g&&b<=0){const z=d;d+=S,h.timelineStart=P;const F=l;l+=N,n.push({event:h,start:P,end:D,playout:{start:F,end:l},integrated:{start:z,end:d}})}else if(b<=i){if(!A){const $=b-c;if($>RGe){const X=c,K=d;d+=$;const Q=l;l+=$;const Y={previousEvent:t[m-1]||null,nextEvent:h,start:X,end:X+$,playout:{start:Q,end:l},integrated:{start:K,end:d}};n.push(Y)}else $>0&&v&&(v.cumulativeDuration+=$,n[n.length-1].end=b)}g&&(D=P),h.timelineStart=P;const z=d;d+=S;const F=l;l+=N,n.push({event:h,start:P,end:D,playout:{start:F,end:l},integrated:{start:z,end:d}})}else return;const B=h.resumeTime;g||B>i?c=i:c=B}),c{const d=o.cue.pre,h=o.cue.post,m=d?0:h?a:o.startTime;this.updateAssetDurations(o),l===m?o.cumulativeDuration=i:(i=0,l=m),!h&&o.snapOptions.in&&(o.resumeAnchor=$5(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+1$M?(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=$5(null,o.fragments,n);if(!d)return this.log(`"${t.identifier}" resumption ${n} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=l==="audio"?.175:0;return Math.abs(d.start-n)<$M+h||Math.abs(d.end-n)<$M+h?!1:(this.log(`"${t.identifier}" resumption ${n} not aligned with ${l} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const r=t.timelineStart;let n=0,a=!1,i=!1;for(let l=0;l{const b=x.data,N=b==null?void 0:b.ASSETS;if(!Array.isArray(N)){const S=this.assignAssetListError(t,ir.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),v.url,g,j);this.hls.trigger(xt.ERROR,S);return}t.assetListResponse=b,this.hls.trigger(xt.ASSET_LIST_LOADED,{event:t,assetListResponse:b,networkDetails:j})},onError:(x,g,v,j)=>{const b=this.assignAssetListError(t,ir.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${x.code} ${x.text} (${g.url})`),g.url,j,v);this.hls.trigger(xt.ERROR,b)},onTimeout:(x,g,v)=>{const j=this.assignAssetListError(t,ir.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,x,v);this.hls.trigger(xt.ERROR,j)}};return o.load(c,h,m),this.hls.trigger(xt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,r,n,a,i,l){return t.error=n,{type:Ma.NETWORK_ERROR,details:r,fatal:!1,interstitial:t,url:a,error:n,networkDetails:l,stats:i}}}function OGe(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function aA(s,t){return`[${s}] Advancing timeline position to ${t}`}class o7s extends ay{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 g=this.findItemIndex(o);let v=this.schedule.findItemIndexAtTime(n);if(v===-1&&(v=g+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${n} (resolving from ${g} to ${v})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&v>g){const j=this.schedule.findJumpRestrictedIndex(g+1,v);if(j>g){this.setSchedulePosition(j);return}}this.setSchedulePosition(v);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,g))}return}const h=d.timelineStart,m=d.duration||0;if(l&&n=h+m){var x;(x=o.event)!=null&&x.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,d)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(n>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);n>=l&&this.setScheduleToAssetAtTime(n,i)},this.onScheduleUpdate=(n,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,h=n.map(j=>j.identifier),m=!!(o.length||h.length);(m||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(j=>My(j))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let x=null,g=null;l&&(x=this.updateItem(l,this.timelinePos),this.itemsMatch(l,x)?this.playingItem=x:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const v=this.bufferingItem;if(v&&(g=this.updateItem(v,this.bufferedPos),this.itemsMatch(v,g)?this.bufferingItem=g:v.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(v.event,null))),n.forEach(j=>{j.assetList.forEach(b=>{this.clearAssetPlayer(b.identifier,null)})}),this.playerQueue.forEach(j=>{if(j.interstitial.appendInPlace){const b=j.assetItem.timelineStart,N=j.timelineOffset-b;if(N)try{j.timelineOffset=b}catch(S){Math.abs(N)>$M&&this.warn(`${S} ("${j.assetId}" ${j.timelineOffset}->${b})`)}}}),m||a){if(this.hls.trigger(xt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:h}),this.isInterstitial(l)&&h.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(x,l),v&&g!==x&&this.trimInPlace(g,v),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=r,this.assetListLoader=new i7s(t),this.schedule=new a7s(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(xt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(xt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(xt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(xt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(xt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(xt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(xt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(xt.MEDIA_ENDED,this.onMediaEnded,this),t.on(xt.ERROR,this.onError,this),t.on(xt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(xt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(xt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(xt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(xt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(xt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(xt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(xt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(xt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(xt.MEDIA_ENDED,this.onMediaEnded,this),t.off(xt.ERROR,this.onError,this),t.off(xt.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){dp(t,"play",this.onPlay),dp(t,"pause",this.onPause),dp(t,"seeking",this.onSeeking),dp(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,r){const n=this.media=r.media;Nf(n,"seeking",this.onSeeking),Nf(n,"timeupdate",this.onTimeupdate),Nf(n,"play",this.onPlay),Nf(n,"pause",this.onPause)}onMediaAttached(t,r){const n=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(n);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,r){const n=!!r.transferMedia,a=this.media;if(this.media=null,!n&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,r=()=>t.bufferingItem||t.waitingItem,n=m=>m&&t.getAssetPlayer(m.identifier),a=(m,x,g,v,j)=>{if(m){let b=m[x].start;const N=m.event;if(N){if(x==="playout"||N.timelineOccupancy!==kfe.Point){const S=n(g);(S==null?void 0:S.interstitial)===N&&(b+=S.assetItem.startOffset+S[j])}}else{const S=v==="bufferedPos"?l():t[v];b+=S-m.start}return b}return 0},i=(m,x)=>{var g;if(m!==0&&x!=="primary"&&(g=t.schedule)!=null&&g.length){var v;const j=t.schedule.findItemIndexAtTime(m),b=(v=t.schedule.items)==null?void 0:v[j];if(b){const N=b[x].start-b.start;return m+N}}return m},l=()=>{const m=t.bufferedPos;return m===Number.MAX_VALUE?o("primary"):Math.max(m,0)},o=m=>{var x,g;return(x=t.primaryDetails)!=null&&x.live?t.primaryDetails.edge:((g=t.schedule)==null?void 0:g.durations[m])||0},c=(m,x)=>{var g,v;const j=t.effectivePlayingItem;if(j!=null&&(g=j.event)!=null&&g.restrictions.skip||!t.schedule)return;t.log(`seek to ${m} "${x}"`);const b=t.effectivePlayingItem,N=t.schedule.findItemIndexAtTime(m,x),S=(v=t.schedule.items)==null?void 0:v[N],T=t.getBufferingPlayer(),A=T==null?void 0:T.interstitial,P=A==null?void 0:A.appendInPlace,D=b&&t.itemsMatch(b,S);if(b&&(P||D)){const B=n(t.playingAsset),z=(B==null?void 0:B.media)||t.primaryMedia;if(z){const F=x==="primary"?z.currentTime:a(b,x,t.playingAsset,"timelinePos","currentTime"),$=m-F,X=(P?F:z.currentTime)+$;if(X>=0&&(!B||P||X<=B.duration)){z.currentTime=X;return}}}if(S){let B=m;if(x!=="primary"){const F=S[x].start,$=m-F;B=S.start+$}const z=!t.isInterstitial(S);if((!t.isInterstitial(b)||b.event.appendInPlace)&&(z||S.event.appendInPlace)){const F=t.media||(P?T==null?void 0:T.media:null);F&&(F.currentTime=B)}else if(b){const F=t.findItemIndex(b);if(N>F){const X=t.schedule.findJumpRestrictedIndex(F+1,N);if(X>F){t.setSchedulePosition(X);return}}let $=0;if(z)t.timelinePos=B,t.checkBuffer();else{const X=S.event.assetList,K=m-(S[x]||S).start;for(let Q=X.length;Q--;){const Y=X[Q];if(Y.duration&&K>=Y.startOffset&&K{const m=t.effectivePlayingItem;if(t.isInterstitial(m))return m;const x=r();return t.isInterstitial(x)?x:null},h={get bufferedEnd(){const m=r(),x=t.bufferingItem;if(x&&x===m){var g;return a(x,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-x.playout.start||((g=t.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const m=d(),x=t.effectivePlayingItem;return x&&x===m?a(x,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-x.playout.start:0},set currentTime(m){const x=d(),g=t.effectivePlayingItem;g&&g===x&&c(m+g.playout.start,"playout")},get duration(){const m=d();return m?m.playout.end-m.playout.start:0},get assetPlayers(){var m;const x=(m=d())==null?void 0:m.event.assetList;return x?x.map(g=>t.getAssetPlayer(g.identifier)):[]},get playingIndex(){var m;const x=(m=d())==null?void 0:m.event;return x&&t.effectivePlayingAsset?x.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var m;return((m=t.schedule)==null||(m=m.events)==null?void 0:m.slice(0))||[]},get schedule(){var m;return((m=t.schedule)==null||(m=m.items)==null?void 0:m.slice(0))||[]},get interstitialPlayer(){return d()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const m=r();return t.findItemIndex(m)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const m=t.effectivePlayingItem;return t.findItemIndex(m)},primary:{get bufferedEnd(){return l()},get currentTime(){const m=t.timelinePos;return m>0?m:0},set currentTime(m){c(m,"primary")},get duration(){return o("primary")},get seekableStart(){var m;return((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(r(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(m){c(m,"integrated")},get duration(){return o("integrated")},get seekableStart(){var m;return i(((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{const m=t.effectivePlayingItem,x=m==null?void 0:m.event;if(x&&!x.restrictions.skip){const g=t.findItemIndex(m);if(x.appendInPlace){const v=m.playout.start+m.event.duration;c(v+.001,"playout")}else t.advanceAfterAssetEnded(x,g,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||!Xn(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} ${ec(i)}`),this.detachedData=i}else r&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,r){var n,a;if(t.media===r)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(n=this.detachedData)==null?void 0:n.mediaSource;let h;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),h="Primary";else if(d){const v=this.getBufferingPlayer();v?(i=v.transferMedia(),h=`${v}`):h="detached MediaSource"}else h="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${ec(i)}`);else if(!this.detachedData||l.media===r){const v=this.playerQueue;v.length>1&&v.forEach(j=>{if(o&&j.interstitial.appendInPlace!==c){const b=j.interstitial;this.clearInterstitial(j.interstitial,null),b.appendInPlace=!1,b.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${b}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const m=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",x=m&&i?i:r;this.log(`${m?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${h} (media.currentTime: ${r.currentTime})`);const g=this.schedule;if(x===i&&g){const v=o&&t.assetId===g.assetIdAtEnd;x.overrides={duration:g.duration,endOfStream:!o||v,cueRemoval:!o}}t.attachMedia(x)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,r=t==null?void 0:t.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,a=this.effectivePlayingItem;if(n===-1){const i=this.hls.startPosition;if(this.timelinePos=i,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(aA("checkStart (preroll)",i));const l=t.findEventIndex(r[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(aA("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(aA("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=ewe(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=ewe(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&&My(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const h=l.event,m=this.playingAsset,x=m==null?void 0:m.identifier,g=x?this.getAssetPlayer(x):null;if(g&&x&&(!this.eventItemsMatch(l,i)||r!==void 0&&x!==h.assetList[r].identifier)){var c;const v=h.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${v+1}/${h.assetList.length} ${pA(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(xt.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:v,event:h,schedule:a.slice(0),scheduleIndex:t,player:g}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),v);return}this.retreiveMediaSource(x,i),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${My(l)}`),h.hasPlayed=!0,this.hls.trigger(xt.INTERSTITIAL_ENDED,{event:h,schedule:a.slice(0),scheduleIndex:t}),h.cue.once)){var d;this.updateSchedule();const v=(d=this.schedule)==null?void 0:d.items;if(i&&v){const j=this.findItemIndex(i);this.advanceSchedule(j,v,r,l,o)}return}}this.advanceSchedule(t,a,r,l,o)}advanceSchedule(t,r,n,a,i){const l=this.schedule;if(!l)return;const o=r[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(h=>{const m=h.interstitial,x=l.findEventIndex(m.identifier);(xt+1)&&this.clearInterstitial(m,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(n===void 0){n=l.findAssetIndex(h,this.timelinePos);const v=ewe(h,n-1);if(h.isAssetPastPlayoutLimit(v)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,t,n);return}n=v}const m=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let x=this.preloadAssets(h,n);if(this.eventItemsMatch(o,m||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${My(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(xt.INTERSTITIAL_STARTED,{event:h,schedule:r.slice(0),scheduleIndex:t})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=h.assetList[n];if(!g){this.advanceAfterAssetEnded(h,t,n||0);return}if(x||(x=this.getAssetPlayer(g.identifier)),x===null||x.destroyed){const v=h.assetList.length;this.warn(`asset ${n+1}/${v} player destroyed ${h}`),x=this.createAssetPlayer(h,g,n),x.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(x,n,r,t,c),this.shouldPlay&&OGe(x.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&OGe(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 ${My(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,r),this.log(aA("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 ${My(t)}`),this.hls.trigger(xt.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:Ii.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(aA("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(xt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(xt.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=Cl(Cl({},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=Cl(Cl({},this.altSelection),{},{audio:n});return}const i=Cl(Cl({},a),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(t,r){const n=this.hls.subtitleTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=Cl(Cl({},this.altSelection),{},{subtitles:n});return}const i=Cl(Cl({},a),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(t,r){const n=GHe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(r)||a.setAudioOption(n)))}onSubtitleTrackSwitch(t,r){const n=GHe(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=Ii.bufferInfo(this.primaryMedia,n,0);(a.end>n||(a.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${My(t)} (was ${My(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=Ii.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,n,t)}updateBufferedPos(t,r,n){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(r.length===1&&this.itemsMatch(r[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=x.event)!=null&&d.appendInPlace&&t+.01>=x.start)&&(c=m),this.isInterstitial(i)){const g=i.event;if(m-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=t,c>h&&c>o)this.bufferedToItem(x);else{const g=this.primaryDetails;this.primaryLive&&g&&t>g.edge-g.targetduration&&x.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(r))})}setBufferingItem(t){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(t,r)&&n){const{items:a,events:i}=n;if(!a||!i)return r;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${My(t)}`+(r?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=n.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((h,m)=>{const x=this.getAssetPlayer(h.identifier);x&&(m===d&&x.loadSource(),x.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(xt.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return r}bufferedToItem(t,r=0){const n=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,r);else if(n!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const r=this.findItemIndex(t),n=this.getPrimaryResumption(t,r);this.startLoadingPrimaryAt(n)}bufferedToEvent(t,r){const n=t.event,a=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(a||!i){const l=this.preloadAssets(n,r);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,r){const n=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const x=this.playingItem;!this.isInterstitial(x)&&(x==null||(o=x.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(t.cue.pre||t.cue.post)){const x=h-c;x>0&&(d=Math.round(x*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:a} ${t}${d?` live-start: ${h} start-offset: ${d}`:""}`),n)return this.createAsset(t,0,0,c,t.duration,n);const m=this.assetListLoader.loadAssetList(t,d);m&&(t.assetListLoader=m)}else if(!l&&a){for(let d=r;d{this.hls.trigger(xt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const r=this.playerQueue;for(let n=0;n1){const P=r.duration;P&&A{if(A.live){var P;const z=new Error(`Interstitials MUST be VOD assets ${t}`),F={fatal:!0,type:Ma.OTHER_ERROR,details:ir.INTERSTITIAL_ASSET_ITEM_ERROR,error:z},$=((P=this.schedule)==null?void 0:P.findEventIndex(t.identifier))||-1;this.handleAssetItemError(F,t,$,n,z.message);return}const D=A.edge-A.fragmentStart,B=r.duration;(j||B===null||D>B)&&(j=!1,this.log(`Interstitial asset "${m}" duration change ${B} > ${D}`),r.duration=D,this.updateSchedule())};v.on(xt.LEVEL_UPDATED,(A,{details:P})=>b(P)),v.on(xt.LEVEL_PTS_UPDATED,(A,{details:P})=>b(P)),v.on(xt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const N=(A,P)=>{const D=this.getAssetPlayer(m);if(D&&P.tracks){D.off(xt.BUFFER_CODECS,N),D.tracks=P.tracks;const B=this.primaryMedia;this.bufferingAsset===D.assetItem&&B&&!D.media&&this.bufferAssetPlayer(D,B)}};v.on(xt.BUFFER_CODECS,N);const S=()=>{var A;const P=this.getAssetPlayer(m);if(this.log(`buffered to end of asset ${P}`),!P||!this.schedule)return;const D=this.schedule.findEventIndex(t.identifier),B=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(B)&&this.advanceAssetBuffering(B,r)};v.on(xt.BUFFERED_TO_END,S);const T=A=>()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,D,A)};return v.once(xt.MEDIA_ENDED,T(n)),v.once(xt.PLAYOUT_LIMIT_REACHED,T(1/0)),v.on(xt.ERROR,(A,P)=>{if(!this.schedule)return;const D=this.getAssetPlayer(m);if(P.details===ir.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(P,t,this.schedule.findEventIndex(t.identifier),n,`Asset player error ${P.error} ${t}`)}),v.on(xt.DESTROYING,()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;const P=new Error(`Asset player destroyed unexpectedly ${m}`),D={fatal:!0,type:Ma.OTHER_ERROR,details:ir.INTERSTITIAL_ASSET_ITEM_ERROR,error:P};this.handleAssetItemError(D,t,this.schedule.findEventIndex(t.identifier),n,P.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${pA(r)}`),this.hls.trigger(xt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:t,player:v}),v}clearInterstitial(t,r){this.clearAssetPlayers(t,r),t.reset()}clearAssetPlayers(t,r){t.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(t){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){this.log(`reset asset player "${t}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(t,r){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){const a=this.playerQueue[n];this.log(`clear ${a} toSegment: ${r&&My(r)}`),this.transferMediaFromPlayer(a,r),this.playerQueue.splice(n,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,r,n,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,n[a]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${d} ${pA(o)}`),this.hls.trigger(xt.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:r,event:l,schedule:n.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,r){var n,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(n=this.schedule.items)==null?void 0:n[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const h=i.appendInPlace;if(h&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const m=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(h&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(m&&!Ogt(m,t.tracks)){const x=new Error(`Asset ${pA(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(m)}')`),g={fatal:!0,type:Ma.OTHER_ERROR,details:ir.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},v=i.findAssetIndex(l);this.handleAssetItemError(g,i,o,v,x.message);return}}this.transferMediaTo(t,r)}handleInPlaceStall(t){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const a=n.currentTime,i=r.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){const h=r.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,h,i)}}}}advanceInPlace(t){const r=this.primaryMedia;r&&r.currentTime!j.error))r.error=v;else for(let j=a;j{const N=parseFloat(j.DURATION);this.createAsset(i,b,h,c+h,N,j.URI),h+=N}),i.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${d}) ${i}`);const m=this.waitingItem,x=(m==null?void 0:m.event.identifier)===l;this.updateSchedule();const g=(a=this.bufferingItem)==null?void 0:a.event;if(x){var v;const j=this.schedule.findEventIndex(l),b=(v=this.schedule.items)==null?void 0:v[j];if(b){if(!this.playingItem&&this.timelinePos>b.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==j){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(j)}else if((g==null?void 0:g.identifier)===l){const j=i.assetList[0];if(j){const b=this.getAssetPlayer(j.identifier);if(g.appendInPlace){const N=this.primaryMedia;b&&N&&this.bufferAssetPlayer(b,N)}else b&&b.loadSource()}}}onError(t,r){if(this.schedule)switch(r.details){case ir.ASSET_LIST_PARSING_ERROR:case ir.ASSET_LIST_LOAD_ERROR:case ir.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case ir.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 FGe=500;class l7s extends DMe{constructor(t,r,n){super(t,r,n,"subtitle-stream-controller",da.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(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(xt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(xt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(xt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(xt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(xt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(xt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(xt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(xt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(xt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(xt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,r){this.stopLoad(),this.state=Dr.IDLE,this.setInterval(FGe),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)||(tu(n)&&(this.fragPrevious=n),this.state=Dr.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 hB(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const a=new hB(n);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,da.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!==Dr.STOPPED&&this.setInterval(FGe)}onSubtitleTrackLoaded(t,r){var n;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=r;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(n=c.details)!=null&&n.live){if(l.deltaUpdateFailed)return;const m=this.mainDetails;if(!m){this.startFragRequested=!1;return}const x=m.fragments[0];if(!c.details)l.hasProgramDateTime&&m.hasProgramDateTime?(jfe(l,m),d=l.fragmentStart):x&&(d=x.start,sCe(l,d));else{var h;d=this.alignPlaylists(l,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),d===0&&x&&(d=x.start,sCe(l,d))}m&&!this.startFragRequested&&this.setStartPosition(m,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(xt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:r.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===Dr.IDLE&&($5(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&&BM(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,PMe(a.method)).catch(o=>{throw i.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const c=performance.now();i.trigger(xt.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Dr.IDLE})}}doTick(){if(!this.media){this.state=Dr.IDLE;return}if(this.state===Dr.IDLE){const{currentTrackId:t,levels: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=Ii.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=n.details,h=this.hls.maxBufferLength+d.levelTargetDuration;if(c>h)return;const m=d.fragments,x=m.length,g=d.edge;let v=null;const j=this.fragPrevious;if(og-S?0:S;v=$5(j,m,Math.max(m[0].start,o),T),!v&&j&&j.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 d7s={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},s0t=s=>String.fromCharCode(d7s[s]||s),Ry=15,yb=100,u7s={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},h7s={17:2,18:4,21:6,22:8,23:10,19:13,20:15},m7s={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},f7s={25:2,26:4,29:6,30:8,31:10,27:13,28:15},p7s=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class x7s{constructor(){this.time=null,this.verboseLevel=0}log(t,r){if(this.verboseLevel>=t){const n=typeof r=="function"?r():r;Ml.log(`${this.time} [${t}] ${n}`)}}}const fk=function(t){const r=[];for(let n=0;nyb&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=yb)}moveCursor(t){const r=this.pos+t;if(t>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=s0t(t);if(this.pos>=yb){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 = "+ec(t));let r=t.row-1;if(this.nrRollUpRows&&r"bkgData = "+ec(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 BGe{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 twe(n),this.nonDisplayedMemory=new twe(n),this.lastOutputScreen=new twe(n),this.currRollUpRow=this.displayedMemory.rows[Ry-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[Ry-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: "+ec(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 zGe{constructor(t,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=b7s(),this.logger=void 0;const a=this.logger=new x7s;this.channels=[null,new BGe(t,r,a),new BGe(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"["+fk([r[n],r[n+1]])+"] -> ("+fk([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(v7s(a,i,c)){yq(null,null,c),this.logger.log(3,()=>"Repeated command ("+fk([a,i])+") is dropped");continue}yq(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 yq(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+fk([a,i])+" orig: "+fk([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 ("+fk([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?u7s[t]:m7s[t]:n=l===1?h7s[t]:f7s[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 '"+s0t(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 = "+fk(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=p7s[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=$,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",i({},m,{get:function(){return B},set:function($){const X=a($);if(!X)throw new SyntaxError("An invalid or illegal string was specified.");B=X,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",i({},m,{get:function(){return z},set:function($){if($<0||$>100)throw new Error("Size must be between 0 and 100.");z=$,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",i({},m,{get:function(){return F},set:function($){const X=a($);if(!X)throw new SyntaxError("An invalid or illegal string was specified.");F=X,this.hasBeenReset=!0}})),h.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class _7s{decode(t,r){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function n0t(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 w7s{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 a0t(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 dCe=new WMe(0,0,""),vq=dCe.align==="middle"?"middle":"center";function j7s(s,t,r){const n=s;function a(){const o=n0t(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 w7s;a0t(o,function(x,g){let v;switch(x){case"region":for(let j=r.length-1;j>=0;j--)if(r[j].id===g){d.set(x,r[j].region);break}break;case"vertical":d.alt(x,g,["rl","lr"]);break;case"line":v=g.split(","),d.integer(x,v[0]),d.percent(x,v[0])&&d.set("snapToLines",!1),d.alt(x,v[0],["auto"]),v.length===2&&d.alt("lineAlign",v[1],["start",vq,"end"]);break;case"position":v=g.split(","),d.percent(x,v[0]),v.length===2&&d.alt("positionAlign",v[1],["start",vq,"end","line-left","line-right","auto"]);break;case"size":d.percent(x,g);break;case"align":d.alt(x,g,["start",vq,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let h=d.get("line","auto");h==="auto"&&dCe.line===-1&&(h=-1),c.line=h,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",vq);let m=d.get("position","auto");m==="auto"&&dCe.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 i0t(s){return s.replace(//gi,` `)}class N7s{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new _7s,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=i0t(i);l")===-1){r.cue.id=i;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{j7s(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 k7s=/\r\n|\n\r|\n|\r/g,swe=function(t,r,n=0){return t.slice(n,n+r.length)===r},S7s=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(!Xn(r)||!Xn(n)||!Xn(a)||!Xn(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*a,r+=60*60*1e3*i,r};function KMe(s,t,r){return C8(s.toString())+C8(t.toString())+C8(r)}const C7s=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 T7s(s,t,r,n,a,i,l){const o=new N7s,c=Ex(new Uint8Array(s)).trim().replace(k7s,` `).split(` `),d=[],h=t?LBs(t.baseTime,t.timescale):0;let m="00:00.000",x=0,g=0,v,j=!0;o.oncue=function(b){const N=r[n];let S=r.ccOffset;const T=(x-h)/9e4;if(N!=null&&N.new&&(g!==void 0?S=r.ccOffset=N.start:C7s(r,n,T)),T){if(!t){v=new Error("Missing initPTS for VTT MPEGTS");return}S=T-r.presentationOffset}const A=b.endTime-b.startTime,P=Jp((b.startTime+S-g)*9e4,a*9e4)/9e4;b.startTime=Math.max(P,0),b.endTime=Math.max(P+A,0);const D=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(D)),b.id||(b.id=KMe(b.startTime,b.endTime,D)),b.endTime>0&&d.push(b)},o.onparsingerror=function(b){v=b},o.onflush=function(){if(v){l(v);return}i(d)},c.forEach(b=>{if(j)if(swe(b,"X-TIMESTAMP-MAP=")){j=!1,b.slice(16).split(",").forEach(N=>{swe(N,"LOCAL:")?m=N.slice(6):swe(N,"MPEGTS:")&&(x=parseInt(N.slice(7)))});try{g=S7s(m)/1e3}catch(N){v=N}return}else b===""&&(j=!1);o.parse(b+` `)}),o.flush()}const rwe="stpp.ttml.im1t",o0t=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,l0t=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,E7s={left:"start",center:"center",right:"end",start:"start",end:"end"};function $Ge(s,t,r,n){const a=no(new Uint8Array(s),["mdat"]);if(a.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>Ex(o)),l=PBs(t.baseTime,1,t.timescale);try{i.forEach(o=>r(A7s(o,l)))}catch(o){n(o)}}function A7s(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((m,x)=>(m[x]=a.getAttribute(`ttp:${x}`)||i[x],m),{}),o=a.getAttribute("xml:space")!=="preserve",c=UGe(nwe(a,"styling","style")),d=UGe(nwe(a,"layout","region")),h=nwe(a,"body","[begin]");return[].map.call(h,m=>{const x=c0t(m,o);if(!x||!m.hasAttribute("begin"))return null;const g=iwe(m.getAttribute("begin"),l),v=iwe(m.getAttribute("dur"),l);let j=iwe(m.getAttribute("end"),l);if(g===null)throw qGe(m);if(j===null){if(v===null)throw qGe(m);j=g+v}const b=new WMe(g-t,j-t,x);b.id=KMe(b.startTime,b.endTime,b.text);const N=d[m.getAttribute("region")],S=c[m.getAttribute("style")],T=M7s(N,S,c),{textAlign:A}=T;if(A){const P=E7s[A];P&&(b.lineAlign=P),b.align=A}return Vl(b,T),b}).filter(m=>m!==null)}function nwe(s,t,r){const n=s.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function UGe(s){return s.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function c0t(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?c0t(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function M7s(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=awe(t,n,c)||awe(s,n,c)||awe(a,n,c);return d&&(o[c]=d),o},{})}function awe(s,t,r){return s&&s.hasAttributeNS(t,r)?s.getAttributeNS(t,r):null}function qGe(s){return new Error(`Could not parse ttml timestamp ${s}`)}function iwe(s,t){if(!s)return null;let r=n0t(s);return r===null&&(o0t.test(s)?r=I7s(s,t):l0t.test(s)&&(r=P7s(s,t))),r}function I7s(s,t){const r=o0t.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 P7s(s,t){const r=l0t.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 bq{constructor(t,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,r,n){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class L7s{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=HGe(),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(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(xt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(xt.FRAG_LOADING,this.onFragLoading,this),t.on(xt.FRAG_LOADED,this.onFragLoaded,this),t.on(xt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(xt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(xt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(xt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(xt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(xt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(xt.FRAG_LOADING,this.onFragLoading,this),t.off(xt.FRAG_LOADED,this.onFragLoaded,this),t.off(xt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(xt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(xt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(xt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new bq(this,"textTrack1"),r=new bq(this,"textTrack2"),n=new bq(this,"textTrack3"),a=new bq(this,"textTrack4");this.cea608Parser1=new zGe(1,t,r),this.cea608Parser2=new zGe(3,n,a)}addCues(t,r,n,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=D7s(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(xt.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===da.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(xt.FRAG_LOADED,c):this.hls.trigger(xt.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{UA(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=HGe(),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===rwe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(zyt(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const l=this.media,o=l?Hde(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let h;if(o){let m=null;for(let x=0;xd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const l=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(xt.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===da.MAIN){var n,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=r.frag,h=(n=(a=r.part)==null?void 0:a.index)!=null?n:-1;i&&l&&(d!==o+1||d===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=h}}onFragLoaded(t,r){const{frag:n,payload:a}=r;if(n.type===da.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===rwe?this._parseIMSC1(n,a):this._parseVTTs(r)}}else this.hls.trigger(xt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,r){const n=this.hls;$Ge(r,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(xt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{n.logger.log(`Failed to parse IMSC1: ${a}`),n.trigger(xt.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?Zg(n.initSegment.data,new Uint8Array(a)).buffer:a;T7s(d,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,h=>{this._appendCues(h,n.level),c.trigger(xt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},h=>{const m=h.message==="Missing initPTS for VTT MPEGTS";m?l.push(t):this._fallbackToIMSC1(n,a),c.logger.log(`Failed to parse VTT cue: ${h}`),!(m&&o>n.cc)&&c.trigger(xt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:h})})}_fallbackToIMSC1(t,r){const n=this.tracks[t.level];n.textCodec||$Ge(r,this.initPTS[t.cc],()=>{n.textCodec=rwe,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=>e0t(a,i))}else{const a=this.tracks[r];if(!a)return;const i=a.default?"default":"subtitles"+r;n.trigger(xt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,r){const{frag:n}=r;n.type===da.SUBTITLE&&this.onFragLoaded(xt.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===da.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let i=0;icCe(o[c],r,n))}if(this.config.renderTextTracksNatively&&r===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>cCe(o[c],r,a))}}}extractCea608Data(t){const r=[[],[]],n=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const g=i0t(d.trim()),v=KMe(t,r,g);s!=null&&(m=s.cues)!=null&&m.getCueById(v)||(l=new h(t,r,g),l.id=v,l.line=x+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((x,g)=>x.line==="auto"||g.line==="auto"?0:x.line>8&&g.line>8?g.line-x.line:x.line-g.line),a.forEach(x=>e0t(s,x))),a}};function F7s(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const B7s=/(\d+)-(\d+)\/(\d+)/;class GGe{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||q7s,this.controller=new self.AbortController,this.stats=new SMe}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=z7s(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&&Xn(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},r.timeout),(pB(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(m=>{var x;this.response=this.loader=m;const g=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-(g-a.loading.start)),!m.ok){const{status:j,statusText:b}=m;throw new V7s(b||"fetch, bad network response",j,m)}a.loading.first=g,a.total=U7s(m.headers)||a.total;const v=(x=this.callbacks)==null?void 0:x.onProgress;return v&&Xn(r.highWaterMark)?this.loadProgressively(m,a,t,r.highWaterMark,v):l?m.arrayBuffer():t.responseType==="json"?m.json():m.text()}).then(m=>{var x,g;const v=this.response;if(!v)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const j=m[o];j&&(a.loaded=a.total=j);const b={url:v.url,data:m,code:v.status},N=(x=this.callbacks)==null?void 0:x.onProgress;N&&!Xn(r.highWaterMark)&&N(a,t,m,v),(g=this.callbacks)==null||g.onSuccess(b,a,t,v)}).catch(m=>{var x;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const g=m&&m.code||0,v=m?m.message:null;(x=this.callbacks)==null||x.onError({code:g,text:v},t,m?m.details:null,a)})}getCacheAge(){let t=null;if(this.response){const r=this.response.headers.get("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,r,n,a=0,i){const l=new byt,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(r,n,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const h=d.value,m=h.length;return r.loaded+=m,m=a&&i(r,n,l.flush().buffer,t)):i(r,n,h.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function z7s(s,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Vl({},s.headers))};return s.rangeEnd&&r.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),r}function $7s(s){const t=B7s.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function U7s(s){const t=s.get("Content-Range");if(t){const n=$7s(t);if(Xn(n))return n}const r=s.get("Content-Length");if(r)return parseInt(r)}function q7s(s,t){return new self.Request(s.url,t)}class V7s extends Error{constructor(t,r,n){super(t),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const H7s=/^age:\s*[\d.]+\s*$/im;class u0t{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 SMe,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&&Xn(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),t.send()}readystatechange(){const{context:t,loader:r,stats:n}=this;if(!t||!r)return;const a=r.readyState,i=this.config;if(!n.aborted&&a>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const d=r.status,h=r.responseType==="text"?r.responseText:null;if(d>=200&&d<300){const v=h??r.response;if(v!=null){var l,o;n.loading.end=Math.max(self.performance.now(),n.loading.first);const j=r.responseType==="arraybuffer"?v.byteLength:v.length;n.loaded=n.total=j,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const b=(l=this.callbacks)==null?void 0:l.onProgress;b&&b(n,t,v,r);const N={url:r.responseURL,data:v,code:d};(o=this.callbacks)==null||o.onSuccess(N,n,t,r);return}}const m=i.loadPolicy.errorRetry,x=n.retry,g={url:t.url,data:void 0,code:d};if(bfe(m,x,!1,g))this.retry(m);else{var c;Ml.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(bfe(t,r,!0))this.retry(t);else{var n;Ml.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=AMe(t,n.retry),n.retry++,Ml.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&&H7s.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 G7s={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},W7s=Cl(Cl({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:u0t,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:aFs,bufferController:YBs,capLevelController:VMe,errorController:dFs,fpsController:Zzs,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:cyt,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:G7s},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},K7s()),{},{subtitleStreamController:l7s,subtitleTrackController:Jzs,timelineController:L7s,audioStreamController:HBs,audioTrackController:GBs,emeController:zM,cmcdController:Gzs,contentSteeringController:Kzs,interstitialsController:o7s});function K7s(){return{cueHandler:O7s,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 Y7s(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=uCe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(h=>{const m=`${l}Loading${h}`,x=t[m];if(x!==void 0&&c){d.push(m);const g=n[o].default;switch(t[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=x,g.maxTimeToFirstByteMs=x;break;case"MaxRetry":g.errorRetry.maxNumRetry=x,g.timeoutRetry.maxNumRetry=x;break;case"RetryDelay":g.errorRetry.retryDelayMs=x,g.timeoutRetry.retryDelayMs=x;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=x,g.timeoutRetry.maxRetryDelayMs=x;break}}}),d.length&&r.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${ec(t[o])}`)}),Cl(Cl({},n),t)}function uCe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(uCe):Object.keys(s).reduce((t,r)=>(t[r]=uCe(s[r]),t),{}):s}function Z7s(s,t){const r=s.loader;r!==GGe&&r!==u0t?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):F7s()&&(s.loader=GGe,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Gde=2,X7s=.1,Q7s=.05,J7s=100;class e9s extends nyt{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(xt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.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(J7s),this.mediaSource=r.mediaSource;const n=this.media=r.media;Nf(n,"playing",this.onMediaPlaying),Nf(n,"waiting",this.onMediaWaiting),Nf(n,"ended",this.onMediaEnded)}onMediaDetaching(t,r){this.clearInterval();const{media:n}=this;n&&(dp(n,"playing",this.onMediaPlaying),dp(n,"waiting",this.onMediaWaiting),dp(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(t,r){var n,a;const i=(n=this.hls)==null?void 0:n.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,h=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==r){r&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!h&&t>r&&this.nudgeOnVideoHole(t,r)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(h){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(xt.MEDIA_ENDED,{stalled:!1}));return}if(!Ii.getBuffered(l).length){this.nudgeRetry=0;return}const m=Ii.bufferInfo(l,t,0),x=m.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const D=WGe(this.hls.inFlightFragments,t),B=m.len>Gde,z=!x||D||x-t>Gde&&!g.getPartialFragment(t);if(B||z)return;this.moved=!1}const v=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(m.len>0)&&!x)return;const B=Math.max(x,m.start||0)-t,F=!!(v!=null&&v.live)?v.targetduration*2:Gde,$=_q(t,g);if(B>0&&(B<=F||$)){l.paused||this._trySkipBufferHole($);return}}const j=i.detectStallWithCurrentTimeMs,b=self.performance.now(),N=this.waiting;let S=this.stalled;if(S===null)if(N>0&&b-N=j||N)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(v!=null&&v.live)&&Math.abs(t-((v==null?void 0:v.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(xt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(m),!this.media||!this.hls)return}const P=Ii.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(P,T,t)}stallResolved(t){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${t}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(xt.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=Ii.bufferedInfo(Ii.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&r>=i.start){const l=Ii.timeRangesToArray(a),o=Ii.bufferedInfo(l,r,0).bufferedIndex;if(o>-1&&oo)&&h-d<1&&t-d<2){const m=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${h} buffered index: ${c}`);this.warn(m.message),this.media.currentTime+=1e-6;let x=_q(t,this.fragmentTracker);x&&"fragment"in x?x=x.fragment:x||(x=void 0);const g=Ii.bufferInfo(this.media,t,0);this.hls.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:x,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(t,r,n){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,h=_q(n,l);if((h||d!=null&&d.live&&n1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-nc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,r){const n=this.fragmentTracker,a=t.nextStart;if(n&&a){const i=n.getFragAtPos(r,da.MAIN),l=n.getFragAtPos(a,da.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 (${ec(t)})`);this.warn(l.message),r.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.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=Ii.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,x=c-l;if(x>0&&(h||m)){if(x>i.maxBufferHole){let v=!1;if(l===0){const j=n.getAppendedFrag(0,da.MAIN);j&&c"u"))return self.VTTCue||self.TextTrackCue}function owe(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,ec(a?Cl({type:a},n):n))}return i}const wq=(()=>{const s=hCe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class s9s{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(xt.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(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(xt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(xt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(xt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(xt.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&&UA(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;rwq&&(m=wq),m-h<=0&&(m=h+t9s);for(let g=0;gh.type===cx.audioId3&&c:a==="video"?d=h=>h.type===cx.emsg&&o:d=h=>h.type===cx.audioId3&&c||h.type===cx.emsg&&o,cCe(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=hCe();if(n&&a&&!l){const{fragmentStart:j,fragmentEnd:b}=t;let N=this.assetCue;N?(N.startTime=j,N.endTime=b):o&&(N=this.assetCue=owe(o,j,b,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),N&&(N.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(N),N.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,h=Object.keys(d);let m=this.dateRangeCuesAppended;if(c&&r){var x;if((x=c.cues)!=null&&x.length){const j=Object.keys(m).filter(b=>!h.includes(b));for(let b=j.length;b--;){var g;const N=j[b],S=(g=m[N])==null?void 0:g.cues;delete m[N],S&&Object.keys(S).forEach(T=>{const A=S[T];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else m=this.dateRangeCuesAppended={}}const v=t.fragments[t.fragments.length-1];if(!(h.length===0||!Xn(v==null?void 0:v.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let j=0;j{if(K!==N.id){const Q=d[K];if(Q.class===N.class&&Q.startDate>N.startDate&&(!X||N.startDate.01&&(K.startTime=S,K.endTime=D);else if(o){let Q=N.attr[X];NFs(X)&&(Q=Fgt(Q));const ne=owe(o,S,D,{key:X,data:Q},cx.dateRange);ne&&(ne.id=b,this.id3Track.addCue(ne),A[X]=ne,l&&(X==="X-ASSET-LIST"||X==="X-ASSET-URL")&&ne.addEventListener("enter",this.onEventCueEnter))}}m[b]={cues:A,dateRange:N,durationKnown:P}}}}}class r9s{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!n.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+n.targetduration);if(c.05&&this.forwardBufferLength>1){const m=Math.min(2,Math.max(1,l)),x=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(m,Math.max(1,x));this.changeMediaPlaybackRate(r,g)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&n||r;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const h=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),r=this.targetLatency;if(t===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const a=n.edge,i=t-r-this.edgeStalled,l=a-n.totalduration,o=a-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const r=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-r,0)}get forwardBufferLength(){const{media:t}=this,r=this.levelDetails;if(!t||!r)return 0;const n=t.buffered.length;return(n?t.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(xt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(xt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(xt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(xt.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===ir.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 n9s extends qMe{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(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(xt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(xt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(xt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(xt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,r){this.resetLevels()}onManifestLoaded(t,r){const n=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;r.levels.forEach(h=>{const m=h.attrs;let{audioCodec:x,videoCodec:g}=h;x&&(h.audioCodec=x=xfe(x,n)||void 0),g&&(g=h.videoCodec=z8s(g));const{width:v,height:j,unknownCodecs:b}=h,N=(b==null?void 0:b.length)||0;if(o||(o=!!(v&&j)),c||(c=!!g),d||(d=!!x),N||x&&!this.isAudioSupported(x)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}const{CODECS:S,"FRAME-RATE":T,"HDCP-LEVEL":A,"PATHWAY-ID":P,RESOLUTION:D,"VIDEO-RANGE":B}=m,F=`${`${P||"."}-`}${h.bitrate}-${D}-${T}-${S}-${B}-${A}`;if(i[F])if(i[F].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const $=l[F]+=1;h.attrs["PATHWAY-ID"]=new Array($+1).join(".");const X=this.createLevel(h);i[F]=X,a.push(X)}else i[F].addGroupId("audio",m.AUDIO),i[F].addGroupId("text",m.SUBTITLES);else{const $=this.createLevel(h);i[F]=$,l[F]=1,a.push($)}}),this.filterAndSortMediaOptions(a,r,o,c,d)}createLevel(t){const r=new hB(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=Zgt(a,[])}return r}isAudioSupported(t){return dB(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return dB(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,r,n,a,i){var l;let o=[],c=[],d=t;const h=((l=r.stats)==null?void 0:l.parsing)||{};if((n||a)&&i&&(d=d.filter(({videoCodec:S,videoRange:T,width:A,height:P})=>(!!S||!!(A&&P))&&Z8s(T))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let S="no level with compatible codecs found in manifest",T=S;r.levels.length&&(T=`one or more CODECS in variant not supported: ${ec(r.levels.map(P=>P.attrs.CODECS).filter((P,D,B)=>B.indexOf(P)===D))}`,this.warn(T),S+=` (${T})`);const A=new Error(S);this.hls.trigger(xt.ERROR,{type:Ma.MEDIA_ERROR,details:ir.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:A,reason:T})}}),h.end=performance.now();return}r.audioTracks&&(o=r.audioTracks.filter(S=>!S.audioCodec||this.isAudioSupported(S.audioCodec)),YGe(o)),r.subtitles&&(c=r.subtitles,YGe(c));const m=d.slice(0);d.sort((S,T)=>{if(S.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(S.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&S.height!==T.height)return S.height-T.height;if(S.frameRate!==T.frameRate)return S.frameRate-T.frameRate;if(S.videoRange!==T.videoRange)return gfe.indexOf(S.videoRange)-gfe.indexOf(T.videoRange);if(S.videoCodec!==T.videoCodec){const A=zHe(S.videoCodec),P=zHe(T.videoCodec);if(A!==P)return P-A}if(S.uri===T.uri&&S.codecSet!==T.codecSet){const A=pfe(S.codecSet),P=pfe(T.codecSet);if(A!==P)return P-A}return S.averageBitrate!==T.averageBitrate?S.averageBitrate-T.averageBitrate:0});let x=m[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==m.length)){for(let S=0;SA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=P)}break}const v=i&&!a,j=this.hls.config,b=!!(j.audioStreamController&&j.audioTrackController),N={levels:d,audioTracks:o,subtitleTracks:c,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:i,video:a,altAudio:b&&!v&&o.some(S=>!!S.url)};h.end=performance.now(),this.hls.trigger(xt.MANIFEST_PARSED,N)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const r=this._levels;if(r.length===0)return;if(t<0||t>=r.length){const h=new Error("invalid level idx"),m=t<0;if(this.hls.trigger(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.LEVEL_SWITCH_ERROR,level:t,fatal:m,error:h,reason:h.message}),m)return;t=Math.min(t,r.length-1)}const n=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=r[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,n===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${n}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(xt.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const h=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const r=this.steering.pathways(),n=t.filter(a=>r.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(t,r){r.fatal||!r.context||r.context.type===io.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(t,{frag:r}){if(r!==void 0&&r.type===da.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(xt.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));gyt(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(xt.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(xt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function YGe(s){const t={};s.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function h0t(){return self.SourceBuffer||self.WebKitSourceBuffer}function m0t(){if(!P2())return!1;const t=h0t();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function a9s(){if(!m0t())return!1;const s=P2();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(uB(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(uB(t,"audio"))))}function i9s(){var s;const t=h0t();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const o9s=100;class l9s extends DMe{constructor(t,r,n){super(t,r,n,"stream-controller",da.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||!Xn(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,da.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(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(xt.LEVEL_LOADING,this.onLevelLoading,this),t.on(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(xt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(xt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(xt.BUFFER_CREATED,this.onBufferCreated,this),t.on(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(xt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(xt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(xt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(xt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(xt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(xt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(xt.BUFFER_CREATED,this.onBufferCreated,this),t.off(xt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(xt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(xt.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(o9s),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=Dr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Dr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Dr.WAITING_LEVEL:{const{levels:t,level: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=Dr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Dr.IDLE;break}break}case Dr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Dr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded: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 j={};this.altAudio===2&&(j.type="video"),this.hls.trigger(xt.BUFFER_EOS,j),this.state=Dr.ENDED;return}if(!this.buffering)return;t.loadLevel!==i&&t.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=t.nextLoadLevel=i;const d=l.details;if(!d||this.state===Dr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Dr.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,m=this.getMaxBufferLength(l.maxBitrate);if(h>=m)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const x=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(x,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&tu(g)&&this.fragmentTracker.getState(g)!==$u.OK){var v;const b=((v=this.backtrackFragment)!=null?v:g).sn-d.startSN,N=d.fragments[b-1];N&&g.cc===N.cc&&(g=N,this.fragmentTracker.removeFragment(N))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,x)){if(!g.gap){const b=this.audioOnly&&!this.altAudio?Gl.AUDIO:Gl.VIDEO,N=(b===Gl.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;N&&this.afterBufferFlushed(N,b,da.MAIN)}g=this.getNextFragmentLoopLoading(g,d,o,da.MAIN,m)}g&&(this.exceedsMaxBuffer(o,m,g)||(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,l,x)))}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);a===$u.NOT_LOADED||a===$u.PARTIAL?tu(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,da.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(xt.AUDIO_TRACK_SWITCHED,r)}),n.trigger(xt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(xt.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(t,r){const n=yfe(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===da.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===Dr.PARSED&&(this.state=Dr.IDLE);return}const o=a?a.stats:n.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),tu(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,a)}const l=this.media;l&&(!this._hasEnoughToStart&&Ii.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=Dr.ERROR;return}switch(r.details){case ir.FRAG_GAP:case ir.FRAG_PARSING_ERROR:case ir.FRAG_DECRYPT_ERROR:case ir.FRAG_LOAD_ERROR:case ir.FRAG_LOAD_TIMEOUT:case ir.KEY_LOAD_ERROR:case ir.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(da.MAIN,r);break;case ir.LEVEL_LOAD_ERROR:case ir.LEVEL_LOAD_TIMEOUT:case ir.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Dr.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===io.LEVEL&&(this.state=Dr.IDLE);break;case ir.BUFFER_ADD_CODEC_ERROR:case ir.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case ir.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 ir.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=Dr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:r}){if(r!==Gl.AUDIO||!this.altAudio){const n=(r===Gl.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,da.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=Dr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const l=i.stats;l.parsing.start=l.parsing.end=l.buffering.start=l.buffering.end=self.performance.now(),a.trigger(xt.FRAG_LOADED,n),i.bitrateTest=!1}).catch(n=>{this.state===Dr.STOPPED||this.state===Dr.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const r=this.playlistType,{hls:n}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:h,text:m,id3:x,initSegment:g}=a,{details:v}=d,j=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Dr.PARSING,g){const b=g.tracks;if(b){const A=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,b,A,i),n.trigger(xt.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:r,tracks:b})}const N=g.initPTS,S=g.timescale,T=this.initPTS[o.cc];if(Xn(N)&&(!T||T.baseTime!==N||T.timescale!==S)){const A=g.trackId;this.initPTS[o.cc]={baseTime:N,timescale:S,trackId:A},n.trigger(xt.INIT_PTS_FOUND,{frag:o,id:r,initPTS:N,timescale:S,trackId:A})}}if(h&&v){j&&h.type==="audiovideo"&&this.logMuxedErr(o);const b=v.fragments[o.sn-1-v.startSN],N=o.sn===v.startSN,S=!b||o.cc>b.cc;if(a.independent!==!1){const{startPTS:T,endPTS:A,startDTS:P,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:A,startDTS:P,endDTS:D};else if(h.firstKeyFrame&&h.independent&&i.id===1&&!S&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),z=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,F=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!N&&zGde&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,A,P,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,i,N||S)}else if(N||S)o.gap=!0;else{this.backtrack(o);return}}if(j){const{startPTS:b,endPTS:N,startDTS:S,endDTS:T}=j;c&&(c.elementaryStreams[Gl.AUDIO]={startPTS:b,endPTS:N,startDTS:S,endDTS:T}),o.setElementaryStreamInfo(Gl.AUDIO,b,N,S,T),this.bufferFragmentData(j,o,c,i)}if(v&&x!=null&&x.samples.length){const b={id:r,frag:o,details:v,samples:x.samples};n.trigger(xt.FRAG_PARSING_METADATA,b)}if(v&&m){const b={id:r,frag:o,details:v,samples:m.samples};n.trigger(xt.FRAG_PARSING_USERDATA,b)}}logMuxedErr(t){this.warn(`${tu(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,r,n,a){if(this.state!==Dr.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:i,video:l,audiovideo:o}=r;if(i){const d=t.audioCodec;let h=Bde(i.codec,d);h==="mp4a"&&(h="mp4a.40.5");const m=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const x=i.metadata;x&&"channelCount"in x&&(x.channelCount||1)!==1&&m.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&m.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),d&&d!==h&&this.log(`Swapping manifest audio codec "${d}" for "${h}"`),i.levelCodec=h,i.id=da.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${h||""}/${d||""}/${i.codec}]`),delete r.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=da.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(xt.BUFFER_CODECS,r),!this.hls)return;c.forEach(d=>{const m=r[d].initSegment;m!=null&&m.byteLength&&this.hls.trigger(xt.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,da.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=Dr.IDLE}checkFragmentChanged(){const t=this.media;let r=null;if(t&&t.readyState>1&&t.seeking===!1){const n=t.currentTime;if(Ii.isBuffered(t,n)?r=this.getAppendedFrag(n):Ii.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(xt.FRAG_CHANGED,{frag:r}),(!a||a.level!==i)&&this.hls.trigger(xt.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 Xn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var t;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Xn(r)){const n=this.getLevelDetails(),a=this.currentFrag||(n?$5(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 c9s extends ay{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=ir.KEY_LOAD_ERROR,n,a,i){return new Cb({type:Ma.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=$de(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=MR(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,ir.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,ir.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=lwe(i);let c=this.keyIdToKeyInfo[o];if((n=c)!=null&&n.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:m}=h;return i.key=m.decryptdata.key,{frag:t,keyInfo:m}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+Xh(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,ir.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=T8s(r.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Xh(o)}`),p2.setKeyIdForUri(t.decryptdata.uri,o)):(o=p2.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Xh(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!tu(r))return Promise.resolve(n);const i=this.emeController.loadKey(n);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,n))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=r),l})}return Promise.resolve(n)}loadKeyHTTP(t,r){const n=this.config,a=n.loader,i=new a(n);return r.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:r,responseType:"arraybuffer",url:t.decryptdata.uri},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(x,g,v,j)=>{const{frag:b,keyInfo:N}=v,S=lwe(N.decryptdata);if(!b.decryptdata||N!==this.keyIdToKeyInfo[S])return o(this.createKeyLoadError(b,ir.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),j));N.decryptdata.key=b.decryptdata.key=new Uint8Array(x.data),b.keyLoader=null,N.loader=null,l({frag:b,keyInfo:N})},onError:(x,g,v,j)=>{this.resetLoader(g),o(this.createKeyLoadError(r,ir.KEY_LOAD_ERROR,new Error(`HTTP Error ${x.code} loading key ${x.text}`),v,Cl({url:c.url,data:void 0},x)))},onTimeout:(x,g,v)=>{this.resetLoader(g),o(this.createKeyLoadError(r,ir.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(x,g,v)=>{this.resetLoader(g),o(this.createKeyLoadError(r,ir.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};i.load(c,h,m)})}resetLoader(t){const{frag:r,keyInfo:n,url:a}=t,i=n.loader;r.keyLoader===i&&(r.keyLoader=null,n.loader=null);const l=lwe(n.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function lwe(s){if(s.keyFormat!==em.FAIRPLAY){const t=s.keyId;if(t)return Xh(t)}return s.uri}function ZGe(s){const{type:t}=s;switch(t){case io.AUDIO_TRACK:return da.AUDIO;case io.SUBTITLE_TRACK:return da.SUBTITLE;default:return da.MAIN}}function cwe(s,t){let r=s.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}class d9s{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(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(xt.LEVEL_LOADING,this.onLevelLoading,this),t.on(xt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(xt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(xt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(xt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(xt.LEVEL_LOADING,this.onLevelLoading,this),t.off(xt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(xt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(xt.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:io.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:io.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:io.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:io.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,r){const n=this.loaders[io.LEVEL];if(n){const a=n.context;a&&!r.levels.some(i=>i===a.levelOrTrack)&&(n.abort(),delete this.loaders[io.LEVEL])}}load(t){var r;const n=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,h=a.context;if(h&&h.levelOrTrack===t.levelOrTrack&&(h.url===t.url||h.deliveryDirectives&&!t.deliveryDirectives)){h.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${h.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===io.MANIFEST?i=n.manifestLoadPolicy.default:i=Vl({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Xn((r=t.deliveryDirectives)==null?void 0:r.part)){let d;if(t.type===io.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===io.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===io.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const h=d.partTarget,m=d.targetduration;if(h&&m){const x=Math.max(h*3,m*.8)*1e3;i=Vl({},i,{maxTimeToFirstByteMs:Math.min(x,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(x,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,h,m,x)=>{const g=this.getInternalLoader(m);this.resetInternalLoader(m.type);const v=d.data;h.parsing.start=performance.now(),Dv.isMediaPlaylist(v)||m.type!==io.MANIFEST?this.handleTrackOrLevelPlaylist(d,h,m,x||null,g):this.handleMasterPlaylist(d,h,m,x)},onError:(d,h,m,x)=>{this.handleNetworkError(h,m,!1,d,x)},onTimeout:(d,h,m)=>{this.handleNetworkError(h,m,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:r},forceStartLoad:n}=this.hls;(t||n)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(t,r,n,a){const i=this.hls,l=t.data,o=cwe(t,n),c=Dv.parseMasterPlaylist(l,o);if(c.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(t,n,c.playlistParsingError,a,r);return}const{contentSteering:d,levels:h,sessionData:m,sessionKeys:x,startTimeOffset:g,variableList:v}=c;this.variableList=v,h.forEach(S=>{const{unknownCodecs:T}=S;if(T){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:P,videoCodec:D}=S;for(let B=T.length;B--;){const z=T[B];dB(z,"audio",A)?(S.audioCodec=P=P?`${P},${z}`:z,uP.audio[P.substring(0,4)]=2,T.splice(B,1)):dB(z,"video",A)&&(S.videoCodec=D=D?`${D},${z}`:z,uP.video[D.substring(0,4)]=2,T.splice(B,1))}}});const{AUDIO:j=[],SUBTITLES:b,"CLOSED-CAPTIONS":N}=Dv.parseMasterPlaylistMedia(l,o,c);j.length&&!j.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),j.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new sd({}),bitrate:0,url:""})),i.trigger(xt.MANIFEST_LOADED,{levels:h,audioTracks:j,subtitles:b,captions:N,contentSteering:d,url:o,stats:r,networkDetails:a,sessionData:m,sessionKeys:x,startTimeOffset:g,variableList:v})}handleTrackOrLevelPlaylist(t,r,n,a,i){const l=this.hls,{id:o,level:c,type:d}=n,h=cwe(t,n),m=Xn(c)?c:Xn(o)?o:0,x=ZGe(n),g=Dv.parseLevelPlaylist(t.data,h,m,x,0,this.variableList);if(d===io.MANIFEST){const v={attrs:new sd({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=r.loading.start+fyt(g,0),l.trigger(xt.MANIFEST_LOADED,{levels:[v],audioTracks:[],url:h,stats:r,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=g,this.handlePlaylistLoaded(g,t,r,n,a,i)}handleManifestParsingError(t,r,n,a,i){this.hls.trigger(xt.ERROR,{type:Ma.NETWORK_ERROR,details:ir.MANIFEST_PARSING_ERROR,fatal:r.type===io.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===io.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===io.AUDIO_TRACK||t.type===io.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=ir.UNKNOWN,d=!1;const h=this.getInternalLoader(t);switch(t.type){case io.MANIFEST:c=n?ir.MANIFEST_LOAD_TIMEOUT:ir.MANIFEST_LOAD_ERROR,d=!0;break;case io.LEVEL:c=n?ir.LEVEL_LOAD_TIMEOUT:ir.LEVEL_LOAD_ERROR,d=!1;break;case io.AUDIO_TRACK:c=n?ir.AUDIO_TRACK_LOAD_TIMEOUT:ir.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case io.SUBTITLE_TRACK:c=n?ir.SUBTITLE_TRACK_LOAD_TIMEOUT:ir.SUBTITLE_LOAD_ERROR,d=!1;break}h&&this.resetInternalLoader(t.type);const m={type:Ma.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:h,context:t,error:o,networkDetails:r,stats:i};if(a){const x=(r==null?void 0:r.url)||t.url;m.response=Cl({url:x,data:void 0},a)}this.hls.trigger(xt.ERROR,m)}handlePlaylistLoaded(t,r,n,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:h,id:m,groupId:x,deliveryDirectives:g}=a,v=cwe(r,a),j=ZGe(a);let b=typeof a.level=="number"&&j===da.MAIN?d:void 0;const N=t.playlistParsingError;if(N){if(this.hls.logger.warn(`${N} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(xt.ERROR,{type:Ma.NETWORK_ERROR,details:ir.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:N,reason:N.message,response:r,context:a,level:b,parent:j,networkDetails:i,stats:n});return}t.playlistParsingError=null}if(!t.fragments.length){const S=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(xt.ERROR,{type:Ma.NETWORK_ERROR,details:ir.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:S,reason:S.message,response:r,context:a,level:b,parent:j,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 io.MANIFEST:case io.LEVEL:if(b){if(!h)b=0;else if(h!==o.levels[b]){const S=o.levels.indexOf(h);S>-1&&(b=S)}}o.trigger(xt.LEVEL_LOADED,{details:t,levelInfo:h||o.levels[0],level:b||0,id:m||0,stats:n,networkDetails:i,deliveryDirectives:g,withoutMultiVariant:c===io.MANIFEST});break;case io.AUDIO_TRACK:o.trigger(xt.AUDIO_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:x||"",stats:n,networkDetails:i,deliveryDirectives:g});break;case io.SUBTITLE_TRACK:o.trigger(xt.SUBTITLE_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:x||"",stats:n,networkDetails:i,deliveryDirectives:g});break}}}class Cv{static get version(){return mB}static isMSESupported(){return m0t()}static isSupported(){return a9s()}static getMediaSource(){return P2()}static get Events(){return xt}static get MetadataSchema(){return cx}static get ErrorTypes(){return Ma}static get ErrorDetails(){return ir}static get DefaultConfig(){return Cv.defaultConfig?Cv.defaultConfig:W7s}static set DefaultConfig(t){Cv.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 RMe,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=x8s(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=Y7s(Cv.DefaultConfig,t,r);this.userConfig=t,n.progressive&&Z7s(n,r);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=n,d=new o(this),h=this.abrController=new a(this),m=new uFs(this),x=n.interstitialsController,g=x?this.interstitialsController=new x(this,Cv):null,v=this.bufferController=new i(this,m),j=this.capLevelController=new l(this),b=new c(this),N=new d9s(this),S=n.contentSteeringController,T=S?new S(this):null,A=this.levelController=new n9s(this,T),P=new s9s(this),D=new c9s(this.config,this.logger),B=this.streamController=new l9s(this,m,D),z=this.gapController=new e9s(this,m);j.setStreamController(B),b.setStreamController(B);const F=[N,A,B];g&&F.splice(1,0,g),T&&F.splice(1,0,T),this.networkControllers=F;const $=[h,v,z,j,b,P,m];this.audioTrackController=this.createController(n.audioTrackController,F);const X=n.audioStreamController;X&&F.push(this.audioStreamController=new X(this,m,D)),this.subtitleTrackController=this.createController(n.subtitleTrackController,F);const K=n.subtitleStreamController;K&&F.push(this.subtititleStreamController=new K(this,m,D)),this.createController(n.timelineController,$),D.emeController=this.emeController=this.createController(n.emeController,$),this.cmcdController=this.createController(n.cmcdController,$),this.latencyController=this.createController(r9s,$),this.coreComponents=$,F.push(d);const Q=d.onErrorOut;typeof Q=="function"&&this.on(xt.ERROR,Q,d),this.on(xt.MANIFEST_LOADED,N.onManifestLoaded,N)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,a){this._emitter.off(t,r,n,a)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const a=t===xt.ERROR;this.trigger(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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(xt.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(xt.ERROR,{type:Ma.OTHER_ERROR,details:ir.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(xt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(xt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(xt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,a=this._url=kMe.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(xt.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={[da.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[da.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[da.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=e7s()),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){Y8s(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=Jgt(r);return Xgt(t,n,navigator.mediaCapabilities)}}Cv.defaultConfig=void 0;const u9s=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function qA(s){return!!s&&u9s.test(s)&&!/\.mp4($|\?)/i.test(s)}function h9s(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function m9s(s,t){if(!s)return null;const r=h9s(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 f9s(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const mCe=k.forwardRef(function({sourceUrl:t,thumbnailUrl:r,autoPlay:n,muted:a,loop:i,playsInline:l=!0,...o},c){const d=k.useRef(null),[h,m]=k.useState(null),x=k.useMemo(()=>m9s(t,{autoplay:!!n,muted:!!a,loop:!!i}),[t,n,a,i]);k.useEffect(()=>{let v=!1;if(!t){m(null);return}if(!qA(t)){m(t);return}if(!x){m(null);return}return m(null),fetch(x).then(async j=>{if(!j.ok)throw new Error(`Failed to load Bunny embed (${j.status})`);const b=await j.text();return f9s(b)}).then(j=>{v||m(j)}).catch(()=>{v||m(null)}),()=>{v=!0}},[x,t]),k.useEffect(()=>{const v=d.current;if(!v||!h)return;let j=null;const b=()=>{if(!n)return;const S=v.play();S&&S.catch(()=>{})};if(v.muted=!!a,v.loop=!!i,h.endsWith(".m3u8")){if(v.canPlayType("application/vnd.apple.mpegurl")){v.src=h;const S=()=>b();return v.addEventListener("loadedmetadata",S),()=>{v.removeEventListener("loadedmetadata",S),v.removeAttribute("src"),v.load()}}return Cv.isSupported()?(j=new Cv({enableWorker:!0,lowLatencyMode:!0}),j.loadSource(h),j.attachMedia(v),j.on(Cv.Events.MANIFEST_PARSED,b),()=>{j==null||j.destroy(),v.removeAttribute("src"),v.load()}):void 0}v.src=h;const N=()=>b();return v.addEventListener("loadedmetadata",N),()=>{v.removeEventListener("loadedmetadata",N),v.removeAttribute("src"),v.load()}},[n,i,a,h]),k.useEffect(()=>{const v=d.current;if(v){if(v.muted=!!a,v.loop=!!i,n&&h){const j=v.play();j&&j.catch(()=>{});return}v.pause()}},[n,i,a,h]);const g=v=>{if(d.current=v,typeof c=="function"){c(v);return}c&&(c.current=v)};return e.jsx("video",{ref:g,poster:r||void 0,autoPlay:n,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),p9s={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 x9s(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function XGe(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 YMe({config:s,appSlug:t="video_greeter",preview:r=!1,embedded:n=!1}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[h,m]=k.useState(!1),[x,g]=k.useState("portrait"),[v,j]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState({name:"",email:"",phone:""}),[A,P]=k.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),D=k.useRef(null),B=k.useRef(null),z=k.useRef(!1),F=async(Re,Qe)=>{if(!r)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Re,visitor_token:x9s(),page_url:typeof window<"u"?window.location.href:null,metadata:Qe||{}})}catch{}};k.useEffect(()=>{if(h)return;const Re=typeof window<"u"?window.location.pathname:"/",Qe=s.targeting||{mode:"all"};if(Qe.mode==="include"&&!XGe(Qe.include,Re)||Qe.mode==="exclude"&&XGe(Qe.exclude,Re))return;const Ke=s.trigger||{type:"immediate"};if(Ke.type==="immediate"||r){i(!0);return}if(Ke.type==="delay"){const Ce=(Ke.value||3)*1e3,nt=setTimeout(()=>i(!0),Ce);return()=>clearTimeout(nt)}if(Ke.type==="scroll"){const Ce=(Ke.value||25)/100,nt=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ce&&(i(!0),window.removeEventListener("scroll",nt))};return window.addEventListener("scroll",nt,{passive:!0}),()=>window.removeEventListener("scroll",nt)}if(Ke.type==="exit_intent"){const Ce=nt=>{nt.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ce),()=>document.removeEventListener("mouseleave",Ce)}},[h,s.targeting,s.trigger,r]),k.useEffect(()=>{a&&!z.current&&(z.current=!0,F("impression"))},[a]),k.useEffect(()=>{if(l&&B.current&&!qA(s.video_url)){B.current.currentTime=0,B.current.muted=!1,d(!1);const Re=B.current.play();Re&&Re.catch(()=>{})}else l&&qA(s.video_url)&&d(!1)},[l,s.video_url]),k.useEffect(()=>{if(!s.thumbnail_url)return;let Re=!1;const Qe=new Image;return Qe.onload=()=>{Re||g(Qe.naturalWidth>Qe.naturalHeight?"landscape":"portrait")},Qe.src=s.thumbnail_url,()=>{Re=!0}},[s.thumbnail_url]),k.useEffect(()=>{const Re=()=>{P({width:window.innerWidth,height:window.innerHeight})};return Re(),window.addEventListener("resize",Re),()=>window.removeEventListener("resize",Re)},[]);const $=()=>{o(!0),F("expand")},X=Re=>{Re.stopPropagation(),m(!0),o(!1)},K=Re=>{F("cta_click",{cta_id:Re.id,label:Re.label,url:Re.url})},Q=async Re=>{if(Re.preventDefault(),r){j(!0);return}if(!(!S.email||!S.name)){N(!0);try{const{error:Qe}=await H.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:S.name,email:S.email,phone:S.phone||void 0,page_url:window.location.href}});if(Qe)throw Qe;F("lead_capture",{email:S.email}),j(!0)}catch(Qe){console.error("lead submit failed",Qe)}finally{N(!1)}}};if(!a||h||!s.video_url&&!s.video_embed_url)return null;const Y=p9s[x][s.size||"md"],ne=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",de=s.shape==="circle"?"rounded-full":"rounded-2xl",ce=r?x==="landscape"?"w-[280px]":"w-[220px]":x==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ae=x==="landscape"?"aspect-video":"aspect-[9/16]",ie=s.agent||{},me=s.lead_form_fields||["name","email","phone"],oe=!!(s.show_socials&&(ie.instagram_url||ie.facebook_url||ie.linkedin_url)),ge=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!v?72+me.length*42:0)+(v?40:0)+(oe?34:0),be=Math.max(300,A.height-32),Oe=Math.max(220,A.width-32),Me=Math.max(150,be-ge),Pe=Math.floor(x==="landscape"?Me*(16/9):Me*(9/16)),Ee=x==="landscape"?Math.max(220,Math.min(420,Oe,Pe)):Math.max(180,Math.min(340,Oe,Pe)),$e=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":`${ce} 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`,Se=n?{width:`${Ee}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,ze=n?"p-3 space-y-2.5":"p-4 space-y-3",Te=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",ye=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",ct=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",ve=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",rt=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:`${ne} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:$e,style:Se,children:[e.jsxs("div",{className:`relative bg-black ${ae}`,children:[qA(s.video_url)?e.jsx(mCe,{ref:B,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Re=>{const{videoWidth:Qe,videoHeight:Ke}=Re.currentTarget;Qe&&Ke&&g(Qe>Ke?"landscape":"portrait")},onEnded:()=>F("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:B,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>F("watch_complete"),onLoadedMetadata:Re=>{const{videoWidth:Qe,videoHeight:Ke}=Re.currentTarget;Qe&&Ke&&g(Qe>Ke?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{B.current&&(B.current.muted=!B.current.muted,d(B.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(BO,{className:"w-4 h-4"}):e.jsx(FO,{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:ze,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ie.avatar_url&&e.jsx("img",{src:ie.avatar_url,alt:ie.name||"",className:Te}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:ye,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:ct,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Re=>{var Qe;return e.jsxs("a",{href:Re.url,target:(Qe=Re.url)!=null&&Qe.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>K(Re),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 ${Re.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:Re.label}),e.jsx(Yr,{className:"w-3.5 h-3.5 opacity-60"})]},Re.id)})}),s.lead_form_enabled&&!v&&e.jsxs("form",{onSubmit:Q,className:"space-y-2 pt-1",children:[me.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:S.name,onChange:Re=>T({...S,name:Re.target.value}),className:ve}),me.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:S.email,onChange:Re=>T({...S,email:Re.target.value}),className:ve}),me.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:S.phone,onChange:Re=>T({...S,phone:Re.target.value}),className:ve}),e.jsxs("button",{type:"submit",disabled:b,className:rt,children:[e.jsx(Zr,{className:"w-3.5 h-3.5"}),b?"Sending...":"Send"]})]}),v&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ie.instagram_url||ie.facebook_url||ie.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ie.instagram_url&&e.jsx("a",{href:ie.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"instagram"}),children:e.jsx(au,{className:"w-4 h-4"})}),ie.facebook_url&&e.jsx("a",{href:ie.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"facebook"}),children:e.jsx(ku,{className:"w-4 h-4"})}),ie.linkedin_url&&e.jsx("a",{href:ie.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"linkedin"}),children:e.jsx(om,{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:$,className:`relative ${de} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:Y.w,height:Y.h},"aria-label":"Play video greeting",children:[qA(s.video_url)?e.jsx(mCe,{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:Re=>{const{videoWidth:Qe,videoHeight:Ke}=Re.currentTarget;Qe&&Ke&&g(Qe>Ke?"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:Re=>{const{videoWidth:Qe,videoHeight:Ke}=Re.currentTarget;Qe&&Ke&&g(Qe>Ke?"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:X,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 ZMe({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 H.rpc("get_public_video_greeter_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(YMe,{config:t}):null}const f0t="eip_last_shown",QGe="eip_visitor_token";function g9s(){try{let s=localStorage.getItem(QGe);return s||(s=crypto.randomUUID(),localStorage.setItem(QGe,s)),s}catch{return}}function y9s(s){try{const t=Number(localStorage.getItem(f0t)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function v9s(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 p0t({config:s,preview:t=!1,forceOpen:r=!1}){const[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({name:"",email:"",phone:""}),m=k.useRef(!1),x=k.useRef(!1),g=async(D,B={})=>{if(!t)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:D,visitor_token:g9s(),page_url:window.location.href,metadata:B})}catch{}};k.useEffect(()=>{if(t||!v9s(s.targeting)||!y9s(s.frequency_days))return;const D=/Mobi|Android/i.test(navigator.userAgent),B={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,z=K=>{if(!m.current){m.current=!0,a(!0);try{localStorage.setItem(f0t,String(Date.now()))}catch{}g("impression",{reason:K})}},F=K=>{K.clientY<=B&&z("mouse_leave")},$=()=>{s.enable_mobile_back&&D&&z("back_button")};if(s.enable_mobile_back&&D){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",$)}else document.addEventListener("mouseleave",F);let X;return s.enable_time_fallback&&(X=window.setTimeout(()=>z("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",F),window.removeEventListener("popstate",$),X&&window.clearTimeout(X)}},[s,t]),k.useEffect(()=>{n&&!x.current&&!t&&!m.current&&(x.current=!0)},[n,t]);const v=()=>{a(!1),t||g("close")},j=async D=>{if(D.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:B}=await H.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(B)throw B;g("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(B){console.error("exit intent submit failed",B)}finally{c(!1)}}};if(!n)return null;const b=s.form_fields||["name","email"],N=s.agent||{},S=[N.first_name,N.last_name].filter(Boolean).join(" "),T=s.use_agent_photo&&N.avatar_url||s.image_url,A=s.theme_color||"#f97316",P=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:P,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}, ${dwe(A,-25)})`}}),e.jsx("button",{onClick:v,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(_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:[T&&e.jsx("img",{src:T,alt:S||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${A}33`,"--tw-ring-color":A}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${A}1A`,color:A},children:[e.jsx(jr,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${A}10`,color:A},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:A},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:j,className:"space-y-2.5",children:[b.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:D=>h({...d,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),b.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:D=>h({...d,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),b.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:D=>h({...d,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${A}, ${dwe(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:()=>g("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}, ${dwe(A,-20)})`},children:s.cta_label}),S&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",S]})]})]})})}function dwe(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function XMe({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 H.rpc("get_public_exit_intent_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(p0t,{config:t}):null}const JGe="lm_dismissed",eWe="lm_visitor_token";function b9s(){try{let s=localStorage.getItem(eWe);return s||(s=crypto.randomUUID(),localStorage.setItem(eWe,s)),s}catch{return}}function _9s(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 QMe({config:s,preview:t=!1}){const[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState({name:"",email:"",phone:""}),x=k.useRef(!1),g=async(T,A={})=>{if(!t)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:T,visitor_token:b9s(),page_url:window.location.href,metadata:A})}catch{}};k.useEffect(()=>{if(t){n(!0);return}if(!_9s(s.targeting))return;try{if(sessionStorage.getItem(JGe))return}catch{}const T=()=>{x.current||(x.current=!0,n(!0),g("impression"))};if(s.trigger_type==="immediate")T();else if(s.trigger_type==="delay"){const A=window.setTimeout(T,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(A)}else if(s.trigger_type==="scroll"){const A=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&T()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const v=()=>{n(!1);try{sessionStorage.setItem(JGe,"1")}catch{}t||g("close")},j=async T=>{if(T.preventDefault(),t){o(!0);return}if(!(!h.email||!h.name)){d(!0);try{const{error:A}=await H.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:h.name,email:h.email,phone:h.phone||void 0,page_url:window.location.href}});if(A)throw A;g("lead_capture",{email:h.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const P=document.createElement("a");P.href=s.download_url,P.target="_blank",P.rel="noopener",P.download="",document.body.appendChild(P),P.click(),P.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!r)return null;const b=s.theme_color||"#2563eb",N=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${b}, ${uR(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(li,{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),g("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:b},children:s.download_label}),e.jsx("button",{onClick:v,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(_r,{className:"w-4 h-4"})})]})}),a&&S()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),g("expand")},className:`${N} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${b}, ${uR(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(Th,{className:"w-5 h-5"})}),e.jsxs("div",{className:"text-left text-white",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:s.badge_label}),e.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:s.title})]}),e.jsx("button",{onClick:T=>{T.stopPropagation(),v()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(_r,{className:"w-3 h-3"})})]}),a&&S()]});return S();function S(){const T=s.form_fields||["name","email"],A=s.agent||{},P=[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}, ${uR(b,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ln,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:b},children:[e.jsx(li,{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(Xa,{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:j,className:"space-y-2.5",children:[T.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:h.name,onChange:D=>m({...h,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),T.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:h.email,onChange:D=>m({...h,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),T.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:h.phone,onChange:D=>m({...h,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${b}, ${uR(b,-20)})`},children:[e.jsx(Xa,{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:()=>g("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}, ${uR(b,-20)})`},children:s.download_label}),P&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",P]})]})]})})}}function uR(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function JMe({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 H.rpc("get_public_lead_magnet_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(QMe,{config:t}):null}function w9s({children:s,siteConfig:t}){var oe,ge,be,Oe,Me,Pe,Ee,$e,Se,ze;const r=sc(),n=vr(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState([]),[x,g]=k.useState([]),[v,j]=k.useState(null),b=k.useRef(null),N=k.useRef(null),{user:S,profile:T,signOut:A}=nye();jMe(t,S==null?void 0:S.id),NMe(t,S==null?void 0:S.id);const P=((oe=t.agent)==null?void 0:oe.full_name)||"Agent",D=t.siteTitle||`${P} Real Estate`,B=r.pathname==="/search",z=r.pathname==="/",F=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{(async()=>{const{data:ye}=await H.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(ye||[])})()},[t.id]),k.useEffect(()=>{(async()=>{const{data:ye}=await H.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});g(ye||[])})()},[t.id]),k.useEffect(()=>{const Te=ye=>{b.current&&!b.current.contains(ye.target)&&d(!1),N.current&&!N.current.contains(ye.target)&&j(null)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[]);const $=((ge=t==null?void 0:t.themeConfig)==null?void 0:ge.referralMode)===!0||!t.mlsProviderId,X=x.length>0,K=[{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"}],Q=X?[]:K,Y=x.filter(Te=>!Te.parent_id),ne=Te=>x.filter(ye=>ye.parent_id===Te),de=z?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ce=t.siteTitle||`${P} - Real Estate`,ae=t.siteTagline||`Browse homes and listings with ${P}`,ie=t.ogImageUrl||((be=t.agent)==null?void 0:be.avatar_url)||"",me=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${B?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(_Me,{siteConfig:t,pagePath:r.pathname}),e.jsx(wMe,{siteConfig:t}),e.jsxs(il,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:ae}),e.jsx("meta",{property:"og:title",content:ce}),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}),ie&&e.jsx("meta",{property:"og:image",content:ie}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ce}),e.jsx("meta",{name:"twitter:description",content:ae}),ie&&e.jsx("meta",{name:"twitter:image",content:ie}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${me}${r.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${z?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${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.jsxs(Kn,{to:"/",className:"flex items-center gap-3",children:[((Oe=t.agent)==null?void 0:Oe.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:P,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:[Q.map(Te=>e.jsx(Kn,{to:Te.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===Te.to?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Te.label},Te.to)),X&&Y.map(Te=>{if(Te.item_type==="dropdown"){const ye=ne(Te.id);return e.jsxs("div",{ref:N,className:"relative",children:[e.jsxs("button",{onClick:()=>j(v===Te.id?null:Te.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Te.label," ",e.jsx(so,{className:`h-3.5 w-3.5 transition-transform ${v===Te.id?"rotate-180":""}`})]}),v===Te.id&&ye.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:ye.map(ct=>e.jsx(jq,{item:ct,onClick:()=>j(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"},ct.id))})]},Te.id)}return e.jsx(jq,{item:Te,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Te.id)}),h.length>0&&e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname.startsWith("/homes-for-sale-in-")?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"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(so,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:h.map(Te=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Te.city_slug}`),d(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:Te.city_name},Te.city_slug))})]}),S?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Kn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(hi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Kn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${z?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Me=T==null?void 0:T.name)==null?void 0:Me.split(" ")[0])||"Account"})]})]}):F?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${z?"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 ${z?"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(D3,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${z?"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:[Q.map(Te=>e.jsx(Kn,{to:Te.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===Te.to?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Te.label},Te.to)),X&&Y.map(Te=>{if(Te.item_type==="dropdown"){const ye=ne(Te.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${z?"text-white/40":"text-gray-400"}`,children:Te.label}),ye.map(ct=>e.jsx(jq,{item:ct,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},ct.id))]},Te.id)}return e.jsx(jq,{item:Te,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Te.id)}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${z?"text-white/40":"text-gray-400"}`,children:"Cities"}),h.map(Te=>e.jsx(Kn,{to:`/homes-for-sale-in-${Te.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${Te.city_slug}`?z?"bg-white/15 text-white":"bg-gray-100 text-gray-900":z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Te.city_name},Te.city_slug))]}),S?e.jsxs(e.Fragment,{children:[e.jsx(Kn,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${z?"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 ${z?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):F?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${z?"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}),!B&&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:[((Pe=t.agent)==null?void 0:Pe.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:P,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:P}),e.jsx("p",{className:"text-sm text-gray-500",children:((Ee=t.agent)==null?void 0:Ee.title)||"Real Estate Professional"})]})]}),(($e=t.agent)==null?void 0:$e.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(Nn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Se=t.agent)==null?void 0:Se.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(Qs,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("ul",{className:"space-y-3 text-sm",children:Q.map(Te=>e.jsx("li",{children:e.jsx(Kn,{to:Te.to,className:"hover:text-white transition-colors",children:Te.label})},Te.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(Kn,{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:[P," · ",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()," ",P,". Powered by LevelUp."]})]})]})]})}),!B&&((ze=t.agent)==null?void 0:ze.avatar_url)&&e.jsx(j9s,{agent:t.agent}),l&&e.jsx(bMe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(ZMe,{slug:t.subdomainSlug}),e.jsx(XMe,{slug:t.subdomainSlug}),e.jsx(JMe,{slug:t.subdomainSlug})]})}function j9s({agent:s}){var a;const[t,r]=k.useState(!1),n=vr();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:t?e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-gray-900 text-sm",children:s.full_name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.title||"Real Estate Professional"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(Nn,{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(Qs,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),n("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>r(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(a=s.full_name)==null?void 0:a.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function jq({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(Kn,{to:n,className:t,onClick:r,children:s.label})}function N9s({children:s,siteConfig:t}){var ie,me,oe,ge,be,Oe,Me;const r=sc(),n=vr(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState([]),[x,g]=k.useState(!1),v=k.useRef(null),{user:j,profile:b,signOut:N}=nye();jMe(t,j==null?void 0:j.id),NMe(t,j==null?void 0:j.id);const S=((ie=t.agent)==null?void 0:ie.full_name)||"Agent",T=t.siteTitle||`${S} Real Estate`,A=t.brokerageLegalName?`${S} | ${t.brokerageLegalName}`:S,P=Pe=>{if(!Pe)return Pe;const Ee=S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$e=new RegExp(`^\\s*${Ee}\\s*[|\\-–—:]\\s*`,"i");return Pe.replace($e,"").trim()},D=T&&T!==`${S} Real Estate`?T:null,B=D?P(D):null,z=B&&B.toLowerCase()!==S.toLowerCase()?B:null,F=r.pathname==="/search",$=r.pathname==="/",X=t.leadRegistrationMode!=="disabled",K="#c9a96e";k.useEffect(()=>{const Pe=()=>g(window.scrollY>80);return window.addEventListener("scroll",Pe,{passive:!0}),()=>window.removeEventListener("scroll",Pe)},[]),k.useEffect(()=>{(async()=>{const{data:Ee}=await H.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(Ee||[])})()},[t.id]),k.useEffect(()=>{const Pe=Ee=>{v.current&&!v.current.contains(Ee.target)&&d(!1)};return document.addEventListener("mousedown",Pe),()=>document.removeEventListener("mousedown",Pe)},[]);const Q=[{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"}],Y=t.siteTitle||`${S} - Real Estate`,ne=t.siteTagline||`Browse homes and listings with ${S}`,de=t.ogImageUrl||((me=t.agent)==null?void 0:me.avatar_url)||"",ce=`https://${t.subdomainSlug||""}.thelocalmove.com`,ae=$?x?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${F?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(_Me,{siteConfig:t,pagePath:r.pathname}),e.jsx(wMe,{siteConfig:t}),e.jsxs(il,{children:[e.jsx("title",{children:Y}),e.jsx("meta",{name:"description",content:ne}),e.jsx("meta",{property:"og:title",content:Y}),e.jsx("meta",{property:"og:description",content:ne}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ce+r.pathname}),de&&e.jsx("meta",{property:"og:image",content:de}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Y}),e.jsx("meta",{name:"twitter:description",content:ne}),de&&e.jsx("meta",{name:"twitter:image",content:de}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ce}${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:`${$?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${ae}`,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(Kn,{to:"/",className:"flex items-center gap-3 min-w-0",children:e.jsxs("span",{className:"flex flex-col leading-none max-w-[320px] xl:max-w-[420px]",children:[e.jsx("span",{className:"block whitespace-normal text-white text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:A}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[Q.map(Pe=>e.jsx(Kn,{to:Pe.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===Pe.to?"text-white":"text-white/40 hover:text-white"}`,children:Pe.label},Pe.to)),h.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(so,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:h.map(Pe=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Pe.city_slug}`),d(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:Pe.city_name},Pe.city_slug))})]}),j?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Kn,{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(hi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Kn,{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(Bi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((oe=b==null?void 0:b.name)==null?void 0:oe.split(" ")[0])||"Account"})]})]}):X?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:[Q.map(Pe=>e.jsx(Kn,{to:Pe.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===Pe.to?"text-white":"text-white/40 hover:text-white"}`,children:Pe.label},Pe.to)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:K},children:"Cities"}),h.map(Pe=>e.jsx(Kn,{to:`/homes-for-sale-in-${Pe.city_slug}`,onClick:()=>i(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:Pe.city_name},Pe.city_slug))]}),j?e.jsxs(e.Fragment,{children:[e.jsx(Kn,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await N(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):X?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!F&&e.jsx("footer",{className:"bg-[#0a0908] text-white/30 border-t border-white/5",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:S}),e.jsx("p",{className:"text-white/20 text-xs tracking-[0.15em] uppercase mb-6",children:((ge=t.agent)==null?void 0:ge.title)||"Real Estate Professional"}),((be=t.agent)==null?void 0:be.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/30 hover:text-white transition-colors mb-3",children:[e.jsx(Nn,{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/30 hover:text-white transition-colors",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6",style:{color:K},children:"Quick Links"}),e.jsx("ul",{className:"space-y-3",children:Q.map(Pe=>e.jsx("li",{children:e.jsx(Kn,{to:Pe.to,className:"text-xs tracking-wider uppercase text-white/30 hover:text-white transition-colors",children:Pe.label})},Pe.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6",style:{color:K},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/20 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsx(Kn,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/15 text-white/50 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/5",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-40"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[10px] text-white/15 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[S," · ",t.brokerageLegalName]}),t.agentLicenseNumber&&e.jsx("span",{children:t.agentLicenseNumber}),t.brokerageLicenseNumber&&e.jsxs("span",{children:["Brokerage #",t.brokerageLicenseNumber]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-30"}),e.jsx("p",{className:"text-[10px] text-white/15 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-white/15 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",S,". Powered by LevelUp."]})]})]})]})}),!F&&((Me=t.agent)==null?void 0:Me.avatar_url)&&e.jsx(k9s,{agent:t.agent,accentColor:K}),l&&e.jsx(bMe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:K}),e.jsx(ZMe,{slug:t.subdomainSlug}),e.jsx(XMe,{slug:t.subdomainSlug}),e.jsx(JMe,{slug:t.subdomainSlug})]})}function k9s({agent:s,accentColor:t}){var i;const[r,n]=k.useState(!1),a=vr();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:r?e.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s.full_name}),e.jsx("p",{className:"text-white/30 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(Qs,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{n(!1),a("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:t},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>n(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(_r,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>n(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:t},children:"Let's connect →"})]})]})}):null}const hR="#2c1810",iv="#b8860b";function S9s({children:s,siteConfig:t}){var z,F,$;const r=sc();vr();const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState([]),[m,x]=k.useState(!1),g=k.useRef(null),{user:v,profile:j,signOut:b}=nye();jMe(t,v==null?void 0:v.id),NMe(t,v==null?void 0:v.id);const N=((z=t.agent)==null?void 0:z.full_name)||"Agent",S=t.siteTitle||`${N} Land & Ranch`,T=r.pathname==="/",A=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{const X=()=>x(window.scrollY>80);return window.addEventListener("scroll",X,{passive:!0}),()=>window.removeEventListener("scroll",X)},[]),k.useEffect(()=>{(async()=>{const{data:K}=await H.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");K&&h(K)})()},[t.id]),k.useEffect(()=>{const X=K=>{g.current&&!g.current.contains(K.target)&&c(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[]);const P=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],D=m||!T?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",B=m||!T?hR:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(il,{children:[e.jsx("title",{children:S}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(_Me,{siteConfig:t}),e.jsx(wMe,{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(Kn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(eM,{className:"w-7 h-7",style:{color:iv}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:B,fontFamily:"'Playfair Display', Georgia, serif"},children:S})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[P.map(X=>e.jsx(Kn,{to:X.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===X.path?iv:B},children:X.label},X.path)),d.length>0&&e.jsxs("div",{ref:g,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:B},children:["Areas ",e.jsx(so,{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(X=>e.jsx(Kn,{to:`/homes-for-sale-in-${X.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:hR},onClick:()=>c(!1),children:X.city_name},X.city_slug))})]}),v?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Kn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:iv,color:B},children:[e.jsx(Bi,{className:"w-4 h-4 inline mr-1.5"}),(j==null?void 0:j.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:iv},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!n),className:"md:hidden p-2",style:{color:B},children:n?e.jsx(_r,{className:"w-6 h-6"}):e.jsx(D3,{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:[P.map(X=>e.jsx(Kn,{to:X.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===X.path?iv:hR},onClick:()=>a(!1),children:X.label},X.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(X=>e.jsx(Kn,{to:`/homes-for-sale-in-${X.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:hR},onClick:()=>a(!1),children:X.city_name},X.city_slug))]}),!v&&A&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:iv},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:hR},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(eM,{className:"w-6 h-6",style:{color:iv}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:S})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:P.map(X=>e.jsx(Kn,{to:X.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:X.label},X.path))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),e.jsxs("div",{className:"space-y-3",children:[((F=t.agent)==null?void 0:F.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(Nn,{className:"w-4 h-4",style:{color:iv}}),t.agent.phone]}),(($=t.agent)==null?void 0:$.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(Qs,{className:"w-4 h-4",style:{color:iv}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",S,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:iv}})]})]})}),i&&e.jsx(bMe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(ZMe,{slug:t.subdomainSlug}),e.jsx(XMe,{slug:t.subdomainSlug}),e.jsx(JMe,{slug:t.subdomainSlug})]})}const C9s=k.lazy(()=>ni(()=>import("./LeadSiteHome-DGdoA_hj.js"),__vite__mapDeps([0,1,2,3]))),T9s=k.lazy(()=>ni(()=>import("./LeadSiteLuxuryHome-BX7ef1Qv.js"),__vite__mapDeps([4,2,3]))),E9s=k.lazy(()=>ni(()=>import("./LeadSiteLandRanchHome-CtbCFo3g.js"),__vite__mapDeps([5,1,2,3]))),A9s=k.lazy(()=>ni(()=>import("./LeadSiteSearch-CV4AWby9.js"),__vite__mapDeps([6,1,7,3,8]))),M9s=k.lazy(()=>ni(()=>import("./LeadSiteLuxurySearch-BiewJoBE.js"),__vite__mapDeps([9,1,7,3,8]))),I9s=k.lazy(()=>ni(()=>import("./LeadSiteListingDetail-oNSdmSb7.js"),__vite__mapDeps([10,11,3,12]))),P9s=k.lazy(()=>ni(()=>import("./LeadSiteLuxuryListingDetail-DHek7nIb.js"),__vite__mapDeps([13,11,3,12]))),L9s=k.lazy(()=>ni(()=>import("./LeadSiteAbout-BT94OXGW.js"),[])),D9s=k.lazy(()=>ni(()=>import("./LeadSiteLuxuryAbout-Xxbhycxi.js"),[])),R9s=k.lazy(()=>ni(()=>import("./LeadSiteContact-DHuJ5cum.js"),[])),O9s=k.lazy(()=>ni(()=>import("./LeadSiteLuxuryContact-CWKg4-Yi.js"),[])),F9s=k.lazy(()=>ni(()=>import("./LeadSiteConsumerDashboard-2YajQHKB.js"),[])),tWe=k.lazy(()=>ni(()=>import("./LeadSiteBlog-Box57FZU.js"),__vite__mapDeps([14,15]))),B9s=k.lazy(()=>ni(()=>import("./LeadSiteCommunity-DzFKHJ4F.js"),[])),z9s=k.lazy(()=>ni(()=>import("./LeadSiteSellers-CqfPRUcS.js"),[])),$9s=k.lazy(()=>ni(()=>import("./LeadSiteCityPage-BiikyE4v.js"),__vite__mapDeps([16,3,8]))),U9s=k.lazy(()=>ni(()=>import("./LeadSiteSubdivisionPage-BpEjEZTD.js"),__vite__mapDeps([17,3]))),q9s=k.lazy(()=>ni(()=>import("./LeadSiteCustomPage-iJ2ZpslX.js"),[]));function V9s(){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 H9s(){const{siteConfig:s,themeConfig:t,isLoading:r,error:n}=XOs();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?S9s:a?N9s:w9s,o=i?e.jsx(E9s,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(T9s,{siteConfig:s,themeConfig:t??void 0}):e.jsx(C9s,{siteConfig:s,themeConfig:t??void 0});return e.jsx(JOs,{siteConfig:s,children:e.jsx(l,{siteConfig:s,children:e.jsx(k.Suspense,{fallback:e.jsx(V9s,{}),children:e.jsxs(Nue,{children:[e.jsx(ps,{path:"/",element:o}),e.jsx(ps,{path:"/search",element:a?e.jsx(M9s,{siteConfig:s}):e.jsx(A9s,{siteConfig:s})}),e.jsx(ps,{path:"/listing/:mlsNumber",element:a?e.jsx(P9s,{siteConfig:s}):e.jsx(I9s,{siteConfig:s})}),e.jsx(ps,{path:"/about",element:a?e.jsx(D9s,{siteConfig:s}):e.jsx(L9s,{siteConfig:s})}),e.jsx(ps,{path:"/contact",element:a?e.jsx(O9s,{siteConfig:s}):e.jsx(R9s,{siteConfig:s})}),e.jsx(ps,{path:"/account",element:e.jsx(F9s,{siteConfig:s})}),e.jsx(ps,{path:"/blog",element:e.jsx(tWe,{siteConfig:s,isLuxury:a})}),e.jsx(ps,{path:"/blog/:slug",element:e.jsx(tWe,{siteConfig:s,isLuxury:a})}),e.jsx(ps,{path:"/sell",element:e.jsx(z9s,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(ps,{path:"/community",element:e.jsx(B9s,{siteConfig:s,isLuxury:a})}),e.jsx(ps,{path:"/p/:pageSlug",element:e.jsx(q9s,{siteConfig:s})}),e.jsx(ps,{path:"/*",element:e.jsx(G9s,{siteConfig:s,referralMode:(t==null?void 0:t.referralMode)===!0||!s.mlsProviderId})})]})})})})}function G9s({siteConfig:s,referralMode:t}){const r=sc(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return e.jsx(U9s,{siteConfig:s,subdivisionSlug:n[1]});const a=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx($9s,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}const W9s=({team:s,onSelect:t})=>{const{data:r}=gt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:n}=await H.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 H.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(Ne,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Ot,{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(zt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Nr,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Ge,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(fr,{className:"h-3 w-3 mr-1"}),(r==null?void 0:r.count)??"…"]})]})}),e.jsxs(De,{className:"space-y-3",children:[(r==null?void 0:r.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vn,{className:"h-6 w-6",children:[e.jsx(ga,{src:r.leaderProfile.avatar_url||""}),e.jsx(bn,{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(nm,{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(Zu,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"capitalize text-xs",children:s.contact_visibility.replace("_"," ")})]}),s.lead_pond_enabled&&e.jsx(Ge,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Ge,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Ge,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},K9s=()=>{const{user:s,isAdmin:t,isBrokerageManager:r,brokerageId:n,managedBrokerages:a,selectedBrokerageId:i}=As(),l=i||(a.length>0?a[0].id:n),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:h,updateTeam:m,deleteTeam:x,addMember:g,removeMember:v,updateMemberRole:j}=Z5(o),[b,N]=k.useState(!1),[S,T]=k.useState(null),{data:A}=gt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:B,error:z}=await H.from("brokerages").select("id, name").order("name");if(z)throw z;return B||[]},enabled:t}),{data:P}=gt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:B,error:z}=await H.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(z)throw z;return B||[]},enabled:!!l}),D=async B=>{const z=B.brokerage_id||l||null,F=await h.mutateAsync({name:B.name,brokerage_id:z,description:B.description});if(B.leaderId&&B.leaderId!=="none"&&await g.mutateAsync({team_id:F.id,user_id:B.leaderId,role:"team_leader"}),B.memberIds)for(const $ of B.memberIds)await g.mutateAsync({team_id:F.id,user_id:$,role:"team_member"});N(!1)};return!r&&!t?e.jsx(_s,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("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(_s,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(G,{onClick:()=>N(!0),children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(Jlt,{open:b,onOpenChange:N,onCreateTeam:D,isCreating:h.isPending,brokerageAgents:P||[],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(B=>e.jsx(Ne,{children:e.jsxs(De,{className:"p-6",children:[e.jsx(Vs,{className:"h-5 w-32 mb-3"}),e.jsx(Vs,{className:"h-4 w-48 mb-4"}),e.jsx(Vs,{className:"h-8 w-full"})]})},B))}),!d&&c.length===0&&!S&&e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(G,{onClick:()=>N(!0),children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!S&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(B=>e.jsx(W9s,{team:B,onSelect:()=>T(B)},B.id))}),S&&e.jsx(Qlt,{team:S,brokerageAgents:P||[],onBack:()=>T(null),onUpdate:B=>m.mutateAsync({id:S.id,...B}).then(z=>T(z)),onAddMember:(B,z)=>g.mutateAsync({team_id:S.id,user_id:B,role:z}),onRemoveMember:B=>v.mutateAsync({team_id:S.id,member_id:B}),onUpdateRole:(B,z)=>j.mutateAsync({team_id:S.id,member_id:B,role:z}),onDeleteTeam:()=>x.mutate(S.id),isUpdating:m.isPending,isAddingMember:g.isPending})]})})},Y9s=()=>{const{data:s,isLoading:t}=Xg(),{useTeamMembers:r}=Z5(),{data:n=[],isLoading:a}=r((s==null?void 0:s.teamId)||"");if(t)return e.jsx(_s,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{className:"h-8 w-48"}),e.jsx(Vs,{className:"h-40 w-full"})]})});if(!s)return e.jsx(_s,{title:"My Team",description:"Your team",children:e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("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(_s,{title:"My Team",description:i.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:i.name}),e.jsx(Ge,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(nm,{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(Rn,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Dn,{className:"flex-wrap",children:[e.jsx(Xt,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(Xt,{value:"contacts",children:[e.jsx(k3,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(Xt,{value:"lead-pond",children:[e.jsx(t0,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(Xt,{value:"shared-assets",children:[e.jsx(im,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(as,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Vs,{className:"h-16 w-full"},l))}):n.map(l=>{var o,c,d,h;return e.jsx(Ne,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsxs(vn,{className:"h-10 w-10",children:[e.jsx(ga,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(bn,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(h=l.profile)==null?void 0:h.email})]}),l.role==="team_leader"?e.jsxs(Ge,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(nm,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ge,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(as,{value:"contacts",className:"space-y-4",children:e.jsx($Te,{})}),i.lead_pond_enabled&&e.jsx(as,{value:"lead-pond",className:"space-y-4",children:e.jsx(UTe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(as,{value:"shared-assets",className:"space-y-4",children:e.jsx(Xlt,{teamId:s.teamId})})]})]})})};function Z9s(){const{user:s}=As(),t=es(),r=gt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await H.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(N)throw N;return b},enabled:!!s}),n=gt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await H.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(N)throw N;return b},enabled:!!s}),a=gt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await H.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(N)throw N;return b},enabled:!!s}),i=gt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await H.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(N)throw N;return b},enabled:!!s}),l=gt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await H.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(N)throw N;return b},enabled:!!s}),o=Lt({mutationFn:async()=>{const{data:b,error:N}=await H.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(N)throw N;const S=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:T}=await H.from("agent_booking_types").insert(S.map(D=>({...D,user_id:s.id})));if(T)throw T;const A=[1,2,3,4,5].map(D=>({user_id:s.id,day_of_week:D,start_time:"09:00",end_time:"17:00"})),{error:P}=await H.from("agent_availability_slots").insert(A);if(P)throw P;return b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ue.success("Scheduler set up successfully!")},onError:b=>ue.error(b.message)}),c=Lt({mutationFn:async b=>{const{error:N}=await H.from("agent_booking_settings").update(b).eq("user_id",s.id);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ue.success("Settings updated")},onError:b=>ue.error(b.message)}),d=Lt({mutationFn:async b=>{const N={...b,user_id:s.id};if(b.id){const{error:S}=await H.from("agent_booking_types").update(N).eq("id",b.id);if(S)throw S}else{const{error:S}=await H.from("agent_booking_types").insert(N);if(S)throw S}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ue.success("Booking type saved")},onError:b=>ue.error(b.message)}),h=Lt({mutationFn:async b=>{const{error:N}=await H.from("agent_booking_types").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ue.success("Booking type deleted")},onError:b=>ue.error(b.message)}),m=Lt({mutationFn:async b=>{const N={...b,user_id:s.id};if(b.id){const{error:S}=await H.from("agent_availability_slots").update(N).eq("id",b.id);if(S)throw S}else{const{error:S}=await H.from("agent_availability_slots").insert(N);if(S)throw S}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>ue.error(b.message)}),x=Lt({mutationFn:async b=>{const{error:N}=await H.from("agent_availability_slots").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>ue.error(b.message)}),g=Lt({mutationFn:async b=>{const{error:N}=await H.from("agent_blocked_dates").insert({...b,user_id:s.id});if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ue.success("Date blocked")},onError:b=>ue.error(b.message)}),v=Lt({mutationFn:async b=>{const{error:N}=await H.from("agent_blocked_dates").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:b=>ue.error(b.message)}),j=Lt({mutationFn:async({id:b,reason:N})=>{const{error:S}=await H.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:N}).eq("id",b);if(S)throw S},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ue.success("Booking cancelled")},onError:b=>ue.error(b.message)});return{settings:r.data,bookingTypes:n.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:r.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:h,upsertAvailability:m,deleteAvailability:x,addBlockedDate:g,removeBlockedDate:v,cancelBooking:j}}const sWe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function X9s({types:s,onSave:t,onDelete:r}){const[n,a]=k.useState(null),[i,l]=k.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=h=>{a({...h}),l(!0)},d=()=>{n!=null&&n.name&&(t(n),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(zt,{children:"Booking Types"}),e.jsx(Nr,{children:"The meeting types prospects can book with you"})]}),e.jsxs(G,{onClick:o,size:"sm",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(De,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-lg",style:{backgroundColor:h.color+"20"},children:sWe[h.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:h.name}),!h.is_active&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Inactive"}),h.qualification_enabled&&e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(gO,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cn,{className:"h-3 w-3"}),h.duration_minutes," min",h.description&&e.jsxs("span",{children:["· ",h.description.slice(0,60),h.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(h),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>r(h.id),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},h.id))})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(js,{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(he,{children:"Name"}),e.jsx(ke,{value:n.name||"",onChange:h=>a({...n,name:h.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:n.description||"",onChange:h=>a({...n,description:h.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Duration (minutes)"}),e.jsx(ke,{type:"number",min:15,max:180,step:15,value:n.duration_minutes||30,onChange:h=>a({...n,duration_minutes:parseInt(h.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(ke,{value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(sWe).map(([h,m])=>e.jsx("button",{onClick:()=>a({...n,icon:h}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${n.icon===h?"border-primary bg-primary/10":"hover:bg-muted"}`,children:m},h))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Meeting Link Override (optional)"}),e.jsx(ke,{value:n.meeting_link_override||"",onChange:h=>a({...n,meeting_link_override:h.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(br,{checked:n.qualification_enabled||!1,onCheckedChange:h=>a({...n,qualification_enabled:h})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Active"}),e.jsx(br,{checked:n.is_active??!0,onCheckedChange:h=>a({...n,is_active:h})})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:d,children:"Save"})]})]})})]})}const rWe=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Q9s({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=rWe.map((m,x)=>s.filter(g=>g.day_of_week===x)),h=()=>{n!==null&&(t({day_of_week:n,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Nr,{children:"Set your available hours for each day"})]}),e.jsx(De,{className:"space-y-2",children:rWe.map((m,x)=>{const g=d[x];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:m})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):g.map(v=>{var j,b;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(j=v.start_time)==null?void 0:j.slice(0,5),onBlur:N=>t({id:v.id,start_time:N.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ke,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(b=v.end_time)==null?void 0:b.slice(0,5),onBlur:N=>t({id:v.id,end_time:N.target.value})}),e.jsx(br,{checked:v.is_active,onCheckedChange:N=>t({id:v.id,is_active:N})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>r(v.id),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},v.id)}),n===x?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:v=>l(v.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ke,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:v=>c(v.target.value)}),e.jsx(G,{size:"sm",className:"h-8",onClick:h,children:"Add"}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(x),children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},m)})})]})}const J9s={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 e$s({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(Bi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Ge,{className:`text-xs ${J9s[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(pd,{className:"h-3.5 w-3.5"}),Ss(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cn,{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(Qs,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(Ge,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Mc,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsx(zt,{children:"Upcoming Bookings"}),e.jsxs(Nr,{children:[r.length," upcoming appointment",r.length!==1?"s":""]})]}),e.jsx(De,{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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{children:"Past & Cancelled"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:n.slice(0,20).map(i=>a(i))})})]})]})}function t$s({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(Ne,{children:[e.jsxs(Ot,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(JR,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Nr,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(De,{children:[n&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(ke,{type:"date",value:i,onChange:h=>l(h.target.value),className:"w-40"}),e.jsx(ke,{placeholder:"Reason (optional)",value:o,onChange:h=>c(h.target.value),className:"flex-1"}),e.jsx(G,{size:"sm",onClick:d,children:"Add"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(h=>e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border bg-muted/50 text-sm",children:[e.jsx("span",{children:Ss(new Date(h.blocked_date+"T00:00:00"),"MMM d, yyyy")}),h.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",h.reason,")"]}),e.jsx("button",{onClick:()=>r(h.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(_r,{className:"h-3.5 w-3.5"})})]},h.id))})]})]})}function s$s(){const{settings:s,bookingTypes:t,availability:r,blockedDates:n,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:h,deleteAvailability:m,addBlockedDate:x,removeBlockedDate:g,cancelBooking:v}=Z9s(),[j,b]=k.useState(""),[N,S]=k.useState(15);j||s!=null&&s.meeting_link;const T=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(_s,{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(_s,{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(pd,{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:[T&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(T),ue.success("Booking link copied!")},children:[e.jsx(Ra,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(br,{id:"scheduler-active",checked:s.is_active,onCheckedChange:A=>o.mutate({is_active:A})})]})]})]}),e.jsxs(Rn,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"types",children:"Booking Types"}),e.jsx(Xt,{value:"availability",children:"Availability"}),e.jsx(Xt,{value:"settings",children:"Settings"}),e.jsxs(Xt,{value:"bookings",children:["Bookings",a.filter(A=>A.status==="confirmed").length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(A=>A.status==="confirmed").length})]})]}),e.jsx(as,{value:"types",children:e.jsx(X9s,{types:t,onSave:A=>c.mutate(A),onDelete:A=>d.mutate(A)})}),e.jsx(as,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Q9s,{slots:r,onSave:A=>h.mutate(A),onDelete:A=>m.mutate(A)}),e.jsx(t$s,{blockedDates:n,onAdd:A=>x.mutate(A),onRemove:A=>g.mutate(A)})]})}),e.jsx(as,{value:"settings",children:e.jsxs(Ne,{children:[e.jsxs(Ot,{children:[e.jsxs(zt,{className:"flex items-center gap-2",children:[e.jsx(EO,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Nr,{children:"Configure your booking page defaults"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>{T&&(navigator.clipboard.writeText(T),ue.success("Copied!"))},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"meeting-link",children:[e.jsx(rl,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(ke,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:A=>o.mutate({meeting_link:A.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:A=>o.mutate({buffer_minutes:parseInt(A.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:A=>o.mutate({min_notice_hours:parseInt(A.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:A=>o.mutate({max_advance_days:parseInt(A.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(as,{value:"bookings",children:e.jsx(e$s,{bookings:a,onCancel:A=>v.mutate({id:A})})})]})]})}):e.jsx(_s,{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(pd,{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(Ne,{children:e.jsxs(De,{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(A=>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:A.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:A.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:A.desc})]})]},A.title))}),e.jsx(po,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(G,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const nWe=[{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 r$s(){const{user:s}=As(),t=na(),{toast:r}=Ea(),n=vr(),a=es(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState({title:"",description:"",page_type:"lead_capture"}),{data:g=[],isLoading:v}=gt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:S,error:T}=await H.from("landing_pages").select("*").eq("user_id",t).order("created_at",{ascending:!1});if(T)throw T;return S},enabled:!!t}),j=Lt({mutationFn:async()=>{const S=m.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:T}=await H.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=m.page_type==="just_listed"||m.page_type==="just_sold",{data:P,error:D}=await H.from("landing_pages").insert({user_id:t,title:m.title,description:m.description||null,page_type:m.page_type,slug:S,hero_headline:A?m.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":m.page_type==="lead_magnet"?"📥 Free Download":m.title,agent_name:(T==null?void 0:T.name)||null,agent_phone:(T==null?void 0:T.phone)||null,agent_email:(T==null?void 0:T.email)||s.email||null,agent_photo_url:(T==null?void 0:T.avatar_url)||null,property_status:A?m.page_type.replace("just_",""):null}).select().single();if(D)throw D;const B=n$s(m.page_type);if(B.length>0){const{error:z}=await H.from("landing_page_fields").insert(B.map((F,$)=>({...F,page_id:P.id,sort_order:$})));if(z)throw z}return P},onSuccess:S=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),x({title:"",description:"",page_type:"lead_capture"}),r({title:"Landing page created!"}),n(`/mission-control/landing-pages/${S.id}`)},onError:S=>r({title:"Error",description:S.message,variant:"destructive"})}),b=Lt({mutationFn:async S=>{const{error:T}=await H.from("landing_pages").delete().eq("id",S);if(T)throw T},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),r({title:"Landing page deleted"})}}),N=S=>`https://pages.relevelup.com/${S}`;return e.jsxs(_s,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs(G,{onClick:()=>l(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," New Page"]})]}),v?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):g.length===0?e.jsx(Ne,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ln,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(G,{onClick:()=>l(!0),children:[e.jsx(Ws,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:g.map(S=>{var T;return e.jsx(Ne,{className:"hover:shadow-md transition-shadow",children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>n(`/mission-control/landing-pages/${S.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:S.title}),e.jsx(Ge,{variant:S.is_published?"default":"secondary",className:"text-[10px]",children:S.is_published?"Published":"Draft"}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:((T=nWe.find(A=>A.id===S.page_type))==null?void 0:T.label)||S.page_type})]}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:S.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"})," ",S.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," ",S.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[S.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>h(N(S.slug)),children:e.jsx(Hv,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(N(S.slug)),r({title:"Link copied!"})},children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:N(S.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(lu,{children:[e.jsx(cu,{asChild:!0,children:e.jsx(G,{size:"sm",variant:"ghost",children:e.jsx(Eg,{className:"h-4 w-4"})})}),e.jsxs(Vd,{align:"end",children:[e.jsxs(Da,{onClick:()=>n(`/mission-control/landing-pages/${S.id}`),children:[e.jsx(Ta,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Da,{onClick:()=>c(S.id),className:"text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},S.id)})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(js,{children:e.jsx(bs,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Page Title"}),e.jsx(ke,{value:m.title,onChange:S=>x(T=>({...T,title:S.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description (optional)"}),e.jsx(ur,{value:m.description,onChange:S=>x(T=>({...T,description:S.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Page Template"}),e.jsxs(zs,{value:m.page_type,onValueChange:S=>x(T=>({...T,page_type:S})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:nWe.map(S=>e.jsx(mt,{value:S.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:S.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.description})]})},S.id))})]})]})]}),e.jsxs(on,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>j.mutate(),disabled:!m.title.trim()||j.isPending,children:j.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Yo,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Fo,{children:[e.jsxs(Bo,{children:[e.jsx($o,{children:"Delete Landing Page?"}),e.jsx(Uo,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(zo,{children:[e.jsx(qo,{children:"Cancel"}),e.jsx(Eo,{onClick:()=>o&&b.mutate(o),children:"Delete"})]})]})}),e.jsx(vs,{open:!!d,onOpenChange:()=>h(null),children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsx(js,{children:e.jsx(bs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(Bz,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),r({title:"URL copied!"}))},children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function n$s(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}const a$s=[{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 i$s=0;const aWe=()=>`f_${Date.now()}_${++i$s}`;function o$s({field:s,index:t,updateField:r,removeField:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Pxe({id:s.clientId}),h={transform:A2.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(Ne,{ref:l,style:h,children:e.jsx(De,{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(Su,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Field Type"}),e.jsxs(zs,{value:s.field_type,onValueChange:m=>r(t,{field_type:m}),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsx(Fs,{children:a$s.map(m=>e.jsx(mt,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Label"}),e.jsx(ke,{value:s.label,onChange:m=>r(t,{label:m.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Placeholder"}),e.jsx(ke,{value:s.placeholder||"",onChange:m=>r(t,{placeholder:m.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(ke,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:m=>r(t,{options:JSON.stringify(m.target.value.split(",").map(x=>x.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{checked:s.is_required,onCheckedChange:m=>r(t,{is_required:m})}),e.jsx(he,{className:"text-xs",children:"Required"})]})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(t),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function l$s(){const{pageId:s}=Xi(),t=vr(),{user:r}=As(),n=na(),{toast:a}=Ea(),i=es(),[l,o]=k.useState(null),[c,d]=k.useState(!1),{data:h,isLoading:m}=gt({queryKey:["landing-page",s],queryFn:async()=>{const{data:ae,error:ie}=await H.from("landing_pages").select("*").eq("id",s).single();if(ie)throw ie;return ae},enabled:!!s}),{data:x=[],isLoading:g}=gt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:ae,error:ie}=await H.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ie)throw ie;return ae},enabled:!!s}),{data:v=[]}=gt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:ae,error:ie}=await H.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ie)throw ie;return ae},enabled:!!s}),{data:j=[]}=gt({queryKey:["my-listings-for-pages",n],queryFn:async()=>{const{data:ae,error:ie}=await H.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",n).order("created_at",{ascending:!1});if(ie)throw ie;return ae},enabled:!!r&&((h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold")}),[b,N]=k.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"]}),[S,T]=k.useState([]);k.useEffect(()=>{h&&N({title:h.title,hero_headline:h.hero_headline,hero_subtext:h.hero_subtext||"",hero_image_url:h.hero_image_url,logo_url:h.logo_url,primary_color:h.primary_color,accent_color:h.accent_color,agent_name:h.agent_name||"",agent_phone:h.agent_phone||"",agent_email:h.agent_email||"",agent_photo_url:h.agent_photo_url,success_message:h.success_message||"Thank you! We'll be in touch soon.",is_published:h.is_published,description:h.description||"",lead_magnet_file_url:h.lead_magnet_file_url||null,lead_magnet_file_name:h.lead_magnet_file_name||null,lead_magnet_external_url:h.lead_magnet_external_url||null,listing_id:h.listing_id||null,property_address:h.property_address||"",property_price:h.property_price||"",property_beds:h.property_beds||"",property_baths:h.property_baths||"",property_sqft:h.property_sqft||"",property_description:h.property_description||"",property_photos:Array.isArray(h.property_photos)?h.property_photos:[],property_status:h.property_status||"just_listed",theme_style:h.theme_style||"premium",eyebrow:h.eyebrow||"",headline_accent:h.headline_accent||"",heading_font:h.heading_font||"playfair",trust_pills:Array.isArray(h.trust_pills)?h.trust_pills:["No obligation","100% free","60 seconds or less"]})},[h]),k.useEffect(()=>{x.length>0&&T(x.map(ae=>({id:ae.id,clientId:ae.id||aWe(),field_type:ae.field_type,label:ae.label,placeholder:ae.placeholder,is_required:ae.is_required,options:typeof ae.options=="string"?ae.options:ae.options?JSON.stringify(ae.options):null,sort_order:ae.sort_order})))},[x]);const A=Lt({mutationFn:async()=>{const{error:ae}=await H.from("landing_pages").update({title:b.title,hero_headline:b.hero_headline,hero_subtext:b.hero_subtext||null,hero_image_url:b.hero_image_url,logo_url:b.logo_url,primary_color:b.primary_color,accent_color:b.accent_color,agent_name:b.agent_name||null,agent_phone:b.agent_phone||null,agent_email:b.agent_email||null,agent_photo_url:b.agent_photo_url,success_message:b.success_message,is_published:b.is_published,description:b.description||null,lead_magnet_file_url:b.lead_magnet_file_url,lead_magnet_file_name:b.lead_magnet_file_name,lead_magnet_external_url:b.lead_magnet_external_url,listing_id:b.listing_id,property_address:b.property_address||null,property_price:b.property_price||null,property_beds:b.property_beds||null,property_baths:b.property_baths||null,property_sqft:b.property_sqft||null,property_description:b.property_description||null,property_photos:b.property_photos,property_status:b.property_status,theme_style:b.theme_style,eyebrow:b.eyebrow||null,headline_accent:b.headline_accent||null,heading_font:b.heading_font,trust_pills:b.trust_pills,updated_at:new Date().toISOString()}).eq("id",s);if(ae)throw ae;if(await H.from("landing_page_fields").delete().eq("page_id",s),S.length>0){const{error:ie}=await H.from("landing_page_fields").insert(S.map((me,oe)=>({page_id:s,field_type:me.field_type,label:me.label,placeholder:me.placeholder||null,is_required:me.is_required,options:me.options?JSON.parse(me.options):null,sort_order:oe})));if(ie)throw ie}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:ae=>a({title:"Error",description:ae.message,variant:"destructive"})}),P=async(ae,ie)=>{const me=ae.name.split(".").pop(),oe=`landing-pages/${r.id}/${ie}-${Date.now()}.${me}`,{error:ge}=await H.storage.from("recruit-landing").upload(oe,ae);if(ge)throw ge;const{data:{publicUrl:be}}=H.storage.from("recruit-landing").getPublicUrl(oe);return be},D=async(ae,ie)=>{var oe;const me=(oe=ae.target.files)==null?void 0:oe[0];if(me){o(ie);try{const ge=await P(me,ie);N(be=>({...be,[ie]:ge})),a({title:"Image uploaded!"})}catch(ge){a({title:"Upload failed",description:ge.message,variant:"destructive"})}finally{o(null)}}},B=async ae=>{var me;const ie=(me=ae.target.files)==null?void 0:me[0];if(ie){o("lead_magnet");try{const oe=await P(ie,"lead-magnet");N(ge=>({...ge,lead_magnet_file_url:oe,lead_magnet_file_name:ie.name})),a({title:"File uploaded!"})}catch(oe){a({title:"Upload failed",description:oe.message,variant:"destructive"})}finally{o(null)}}},z=async ae=>{const ie=ae.target.files;if(!(!ie||ie.length===0)){o("property_photos");try{const me=[];for(const oe of Array.from(ie)){const ge=await P(oe,"property-photo");me.push(ge)}N(oe=>({...oe,property_photos:[...oe.property_photos,...me]})),a({title:`${me.length} photo(s) uploaded!`})}catch(me){a({title:"Upload failed",description:me.message,variant:"destructive"})}finally{o(null)}}},F=async ae=>{const ie=j.find(oe=>oe.id===ae);if(!ie)return;const{data:me}=await H.from("listing_photos").select("photo_url").eq("listing_id",ae).order("sort_order");N(oe=>({...oe,listing_id:ae,property_address:ie.property_address||`${ie.city}, ${ie.state}`,property_price:ie.price?`$${ie.price.toLocaleString()}`:"",property_beds:ie.bedrooms?String(ie.bedrooms):"",property_baths:ie.bathrooms?String(ie.bathrooms):"",property_sqft:ie.square_footage?ie.square_footage.toLocaleString():"",property_description:ie.description||"",property_photos:(me==null?void 0:me.map(ge=>ge.photo_url))||oe.property_photos})),a({title:"Listing data imported!"})},$=()=>{T(ae=>[...ae,{clientId:aWe(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:ae.length}])},X=(ae,ie)=>{T(me=>me.map((oe,ge)=>ge===ae?{...oe,...ie}:oe))},K=ae=>{T(ie=>ie.filter((me,oe)=>oe!==ae))},Q=Nxe(CI(zP,{activationConstraint:{distance:6}}),CI(Cxe,{coordinateGetter:wct})),Y=ae=>{const{active:ie,over:me}=ae;!me||ie.id===me.id||T(oe=>{const ge=oe.findIndex(Oe=>Oe.clientId===ie.id),be=oe.findIndex(Oe=>Oe.clientId===me.id);return ge<0||be<0?oe:Mxe(oe,ge,be).map((Oe,Me)=>({...Oe,sort_order:Me}))})},ne=h?`https://pages.relevelup.com/${h.slug}`:"",de=(h==null?void 0:h.page_type)==="lead_magnet",ce=(h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold";return m||g?e.jsx(_s,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):h?e.jsxs(_s,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(wa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Ge,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"})," ",h.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(fr,{className:"h-3 w-3"})," ",v.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(Hv,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(ne),a({title:"Link copied!"})},children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ne,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(G,{onClick:()=>A.mutate(),disabled:A.isPending,children:[e.jsx(ql,{className:"h-4 w-4 mr-2"}),A.isPending?"Saving...":"Save"]})]})]}),e.jsxs(Rn,{defaultValue:"design",children:[e.jsxs(Dn,{children:[e.jsx(Xt,{value:"design",children:"Design"}),de&&e.jsx(Xt,{value:"lead_magnet",children:"Lead Magnet"}),ce&&e.jsx(Xt,{value:"property",children:"Property Details"}),e.jsxs(Xt,{value:"fields",children:["Form Fields (",S.length,")"]}),e.jsxs(Xt,{value:"submissions",children:["Submissions (",v.length,")"]}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(as,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Page Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Page Title (internal)"}),e.jsx(ke,{value:b.title,onChange:ae=>N(ie=>({...ie,title:ae.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description (internal)"}),e.jsx(ke,{value:b.description,onChange:ae=>N(ie=>({...ie,description:ae.target.value}))})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Theme Style"}),e.jsxs(zs,{value:b.theme_style,onValueChange:ae=>N(ie=>({...ie,theme_style:ae})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(mt,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline Font"}),e.jsxs(zs,{value:b.heading_font,onValueChange:ae=>N(ie=>({...ie,heading_font:ae})),children:[e.jsx(Os,{children:e.jsx(Us,{})}),e.jsxs(Fs,{children:[e.jsx(mt,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(mt,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(mt,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(mt,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(ke,{value:b.trust_pills.join(", "),onChange:ae=>N(ie=>({...ie,trust_pills:ae.target.value.split(",").map(me=>me.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(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(he,{children:"Eyebrow (small label above headline)"}),e.jsx(ke,{value:b.eyebrow,onChange:ae=>N(ie=>({...ie,eyebrow:ae.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(ke,{value:b.hero_headline,onChange:ae=>N(ie=>({...ie,hero_headline:ae.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(he,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(ke,{value:b.headline_accent,onChange:ae=>N(ie=>({...ie,headline_accent:ae.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Subtext"}),e.jsx(ur,{value:b.hero_subtext,onChange:ae=>N(ie=>({...ie,hero_subtext:ae.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(he,{children:["Background Image ",b.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.hero_image_url&&e.jsx("img",{src:b.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(oa,{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:ae=>D(ae,"hero_image_url")})]}),b.hero_image_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N(ae=>({...ae,hero_image_url:null})),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Branding"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.logo_url&&e.jsx("img",{src:b.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ae=>D(ae,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ae=>D(ae,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.primary_color,onChange:ae=>N(ie=>({...ie,primary_color:ae.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ke,{value:b.primary_color,onChange:ae=>N(ie=>({...ie,primary_color:ae.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.accent_color,onChange:ae=>N(ie=>({...ie,accent_color:ae.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ke,{value:b.accent_color,onChange:ae=>N(ie=>({...ie,accent_color:ae.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(De,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Name"}),e.jsx(ke,{value:b.agent_name,onChange:ae=>N(ie=>({...ie,agent_name:ae.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(ke,{value:b.agent_phone,onChange:ae=>N(ie=>({...ie,agent_phone:ae.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(ke,{value:b.agent_email,onChange:ae=>N(ie=>({...ie,agent_email:ae.target.value}))})]})]})})]})]}),de&&e.jsx(as,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(he,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.lead_magnet_file_name&&e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:B})]}),b.lead_magnet_file_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N(ae=>({...ae,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"flex-1 border-t"}),e.jsx("span",{children:"OR"}),e.jsx("div",{className:"flex-1 border-t"})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1",children:[e.jsx(rl,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(ke,{value:b.lead_magnet_external_url||"",onChange:ae=>N(ie=>({...ie,lead_magnet_external_url:ae.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ce&&e.jsxs(as,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsxs(zt,{className:"text-base flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(De,{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(zs,{value:b.listing_id||"",onValueChange:ae=>F(ae),children:[e.jsx(Os,{children:e.jsx(Us,{placeholder:"Select a listing to import..."})}),e.jsx(Fs,{children:j.map(ae=>{var ie;return e.jsxs(mt,{value:ae.id,children:[ae.property_address||`${ae.city}, ${ae.state}`," — $",(ie=ae.price)==null?void 0:ie.toLocaleString()]},ae.id)})})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Property Information"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Property Address"}),e.jsx(ke,{value:b.property_address,onChange:ae=>N(ie=>({...ie,property_address:ae.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Price"}),e.jsx(ke,{value:b.property_price,onChange:ae=>N(ie=>({...ie,property_price:ae.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Beds"}),e.jsx(ke,{value:b.property_beds,onChange:ae=>N(ie=>({...ie,property_beds:ae.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Baths"}),e.jsx(ke,{value:b.property_baths,onChange:ae=>N(ie=>({...ie,property_baths:ae.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Sq Ft"}),e.jsx(ke,{value:b.property_sqft,onChange:ae=>N(ie=>({...ie,property_sqft:ae.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(ur,{value:b.property_description,onChange:ae=>N(ie=>({...ie,property_description:ae.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Property Photos"})}),e.jsxs(De,{className:"space-y-4",children:[b.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:b.property_photos.map((ae,ie)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ae,alt:`Property ${ie+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(G,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>N(me=>({...me,property_photos:me.property_photos.filter((oe,ge)=>ge!==ie)})),children:e.jsx(yr,{className:"h-3 w-3"})})]},ie))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:z})]})]})]})]}),e.jsxs(as,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(G,{size:"sm",onClick:$,children:[e.jsx(Ws,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),S.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(Axe,{sensors:Q,collisionDetection:kxe,onDragEnd:Y,children:e.jsx(Ixe,{items:S.map(ae=>ae.clientId),strategy:tss,children:e.jsx("div",{className:"space-y-3",children:S.map((ae,ie)=>e.jsx(o$s,{field:ae,index:ie,updateField:X,removeField:K},ae.clientId))})})})]}),e.jsx(as,{value:"submissions",className:"mt-4",children:v.length===0?e.jsx(Ne,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:v.map(ae=>e.jsx(Ne,{children:e.jsx(De,{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:ae.contact_name||"Anonymous"}),ae.synced_to_crm&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[ae.contact_email&&e.jsx("span",{className:"mr-3",children:ae.contact_email}),ae.contact_phone&&e.jsx("span",{children:ae.contact_phone})]}),ae.answers&&typeof ae.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(ae.answers).map(([ie,me])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ie,":"]})," ",e.jsx("span",{children:String(me)})]},ie))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(ae.created_at).toLocaleDateString()})]})})},ae.id))})}),e.jsxs(as,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Publishing"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(br,{checked:b.is_published,onCheckedChange:ae=>N(ie=>({...ie,is_published:ae}))})]}),b.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:ne})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ot,{children:e.jsx(zt,{className:"text-base",children:"Thank You Message"})}),e.jsx(De,{children:e.jsx(ur,{value:b.success_message,onChange:ae=>N(ie=>({...ie,success_message:ae.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(js,{children:e.jsx(bs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(Bz,{value:ne,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:ne})]})]})})]}):e.jsx(_s,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(G,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}function c$s(){return gt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await H.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function lye(){const{user:s}=As();return gt({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 H.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(r)throw r;return t||[]},enabled:!!(s!=null&&s.id)})}function cye(){const{user:s}=As(),t=es();return Lt({mutationFn:async({app_slug:r,enabled:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await H.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:r,enabled:n},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ue.success(n.enabled?"App installed":"App turned off")},onError:r=>ue.error(r.message||"Failed to update app")})}const d$s={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"}},u$s={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 h$s(){const s=vr(),{data:t=[],isLoading:r}=c$s(),{data:n=[]}=lye(),{hasLeadSite:a,siteUrl:i}=ey(),l=cye(),[o,c]=k.useState(!1),d=m=>{var x;return((x=n.find(g=>g.app_slug===m))==null?void 0:x.enabled)??!1},h=m=>n.some(x=>x.app_slug===m);return e.jsxs(_s,{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(Xu,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(jr,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(G,{onClick:()=>c(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(mf,{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(Ne,{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(gc,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(Yr,{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(Yr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(Ne,{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(Mb,{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(m=>{const x=Vfe[m.icon||"Sparkles"]||jr,g=d(m.slug),v=h(m.slug),j=m.status==="coming_soon",b=d$s[m.slug]||u$s;return e.jsxs(Ne,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${b.ring} hover:ring-2 transition-all hover:shadow-xl ${j?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${b.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${b.iconBg} ${b.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(x,{className:"w-7 h-7"})}),j?e.jsx(Ge,{variant:"secondary",children:"Coming soon"}):g?e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),"Live"]}):v?e.jsx(Ge,{variant:"outline",children:"Paused"}):e.jsx(Ge,{className:b.chip+" hover:"+b.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:m.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m.description})]}),!j&&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(br,{checked:g,onCheckedChange:N=>l.mutate({app_slug:m.slug,enabled:N})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:g?"On":"Off"})]}),e.jsxs(G,{size:"sm",className:`bg-gradient-to-r ${b.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(lo,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Ga,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(js,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(bs,{children:"How to use Website Apps"})}),o&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const uwe={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 m$s(){const{user:s}=As();return gt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return uwe;const{data:t,error:r}=await H.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t?{...uwe,...t}:uwe},enabled:!!(s!=null&&s.id)})}function f$s(){const{user:s}=As(),t=es();return Lt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:n}=await H.from("video_greeter_configs").upsert({user_id:s.id,...r},{onConflict:"user_id"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ue.success("Saved")},onError:r=>ue.error(r.message||"Failed to save")})}function p$s({label:s,value:t,onChange:r,thumbnailUrl:n,placeholder:a="https://...",hint:i}){const l=k.useRef(null),[o,c]=k.useState(!1),d=async h=>{var x;const m=(x=h.target.files)==null?void 0:x[0];if(m){if(!m.type.startsWith("video/")){ue.error("Please select a video file");return}if(m.size>50*1024*1024){ue.error("Video must be under 50MB");return}c(!0);try{const g=m.name.split(".").pop()||"mp4",v=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${g}`,{error:j}=await H.storage.from("agent-uploads").upload(v,m,{upsert:!0});if(j)throw j;const{data:{publicUrl:b}}=H.storage.from("agent-uploads").getPublicUrl(v);r(b),ue.success("Video uploaded!")}catch(g){ue.error(g.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(he,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{value:t,onChange:h=>r(h.target.value),placeholder:a,className:"flex-1"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var h;return(h=l.current)==null?void 0:h.click()},disabled:o,children:[o?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(oa,{className:"h-3.5 w-3.5"}),o?"Uploading...":"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:d})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i}),t&&e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:"rounded-lg border border-border overflow-hidden bg-black w-full max-w-sm aspect-[9/16] mx-auto",children:qA(t)?e.jsx(mCe,{sourceUrl:t,thumbnailUrl:n,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",muted:!0,preload:"metadata"})}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>r(""),children:e.jsx(_r,{className:"h-3 w-3"})})]})]})}const x$s=[{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 g$s({onVideoReady:s}){const[t,r]=k.useState(!1),[n,a]=k.useState("script"),[i,l]=k.useState(""),[o,c]=k.useState(!0),[d,h]=k.useState(!1),[m,x]=k.useState(0),[g,v]=k.useState(0),j=O_(),b=()=>{a("script"),l(""),x(0),v(0),c(!0)},N=T=>{!T&&(n==="uploading"||n==="processing")||(r(T),T||b())},S=k.useCallback(async(T,A)=>{a("uploading");try{const P="Video Greeter",{videoId:D,libraryId:B}=await sT(P),{uploadUrl:z,apiKey:F}=await rT(D),$=new XMLHttpRequest;$.upload.onprogress=ie=>{ie.lengthComputable&&x(ie.loaded/ie.total*100)},await new Promise((ie,me)=>{$.onload=()=>$.status>=200&&$.status<300?ie():me(new Error("Upload failed")),$.onerror=()=>me(new Error("Upload failed")),$.open("PUT",z),$.setRequestHeader("AccessKey",F),$.send(T)}),a("processing");let X=0;const K=Date.now(),Q=9e4,Y=`https://iframe.mediadelivery.net/embed/${B}/${D}`,ne=`https://iframe.mediadelivery.net/play/${B}/${D}`;for(;X<4;){if(await new Promise(me=>setTimeout(me,3e3)),Date.now()-K>Q){const me=T.size/1048576,oe=await j.mutateAsync({bunny_video_id:D,playback_url:ne,file_size_mb:me,title:P,status:"processing",touch_type:"video"});s({videoId:(oe==null?void 0:oe.id)||D,playbackUrl:Y,thumbnailUrl:null}),ue.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{r(!1),b()},1500);return}const ie=await u1(D);if(X=ie.status,v(ie.encodeProgress||0),X===5||X===6)throw new Error("Video processing failed")}const de=await u1(D),ce=(de.storageSize||T.size)/(1024*1024),ae=await j.mutateAsync({bunny_video_id:D,playback_url:de.directPlayUrl||Y,thumbnail_url:de.thumbnailUrl,preview_url:de.previewUrl||null,duration_seconds:de.length||A,file_size_mb:ce,title:P,status:"ready",touch_type:"video"});s({videoId:(ae==null?void 0:ae.id)||D,playbackUrl:de.directPlayUrl||Y,thumbnailUrl:de.thumbnailUrl||null}),ue.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{r(!1),b()},1500)}catch(P){console.error(P),ue.error("Failed to process video. Please try again."),a("record")}},[j,s]);return e.jsxs(vs,{open:t,onOpenChange:N,children:[e.jsx(Ni,{asChild:!0,children:e.jsxs(G,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(ys,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),n==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(ti,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:x$s.map(T=>e.jsxs(Ne,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(T.text),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:T.title}),e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:T.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:T.description})]},T.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(ur,{rows:5,value:i,onChange:T=>l(T.target.value),placeholder:"Pick a script above or type your own. Leave blank to freestyle."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsx(G,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(G,{onClick:()=>a("record"),children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),n==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(xL,{maxDurationSeconds:60,onRecordingComplete:S,onRecordingStateChange:h,onError:T=>ue.error(T),teleprompterContent:o&&i?e.jsx(cMe,{text:i,isVisible:o,onToggleVisibility:()=>c(!1),isRecording:d,startCountdown:!1}):void 0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),n==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ri,{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(ri,{value:g,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(g),"%"]})]}),n==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(mi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function y$s(){var A;const s=vr(),{user:t}=As(),{leadSite:r}=ey(),{data:n}=m$s(),a=f$s(),{data:i=[]}=lye(),l=cye(),[o,c]=k.useState(null),[d,h]=k.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(k.useEffect(()=>{n&&!o&&c(n)},[n,o]),k.useEffect(()=>{t!=null&&t.id&&H.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:P})=>{const D=P||[];h({impressions:D.filter(B=>B.event_type==="impression").length,expands:D.filter(B=>B.event_type==="expand").length,ctaClicks:D.filter(B=>B.event_type==="cta_click").length,leads:D.filter(B=>B.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(_s,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const m=((A=i.find(P=>P.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,x=P=>c({...o,...P}),g=P=>x({ctas:P}),v=()=>g([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),j=P=>g((o.ctas||[]).filter(D=>D.id!==P)),b=(P,D)=>g((o.ctas||[]).map(B=>B.id===P?{...B,...D}:B)),N=()=>a.mutate(o),S=(r==null?void 0:r.subdomain_slug)||(t==null?void 0:t.id)||"",T=`